babylon.viewer.max.js 6.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811
  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 = 19);
  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__(22); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(23); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(24); } 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. /** @hidden */
  523. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  524. // Rebuild shaders source code
  525. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  526. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  527. vertexCode = prefix + vertexCode;
  528. fragmentCode = prefix + fragmentCode;
  529. // Number lines of shaders source code
  530. var i = 2;
  531. var regex = /\n/gm;
  532. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  533. i = 2;
  534. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  535. // Dump shaders name and formatted source code
  536. if (this.name.vertexElement) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  539. }
  540. else if (this.name.vertex) {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  543. }
  544. else {
  545. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  546. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  547. }
  548. };
  549. ;
  550. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  551. var preparedSourceCode = this._processPrecision(sourceCode);
  552. if (this._engine.webGLVersion == 1) {
  553. callback(preparedSourceCode);
  554. return;
  555. }
  556. // Already converted
  557. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  558. callback(preparedSourceCode.replace("#version 300 es", ""));
  559. return;
  560. }
  561. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  562. // Remove extensions
  563. // #extension GL_OES_standard_derivatives : enable
  564. // #extension GL_EXT_shader_texture_lod : enable
  565. // #extension GL_EXT_frag_depth : enable
  566. // #extension GL_EXT_draw_buffers : require
  567. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  568. var result = preparedSourceCode.replace(regex, "");
  569. // Migrate to GLSL v300
  570. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  571. result = result.replace(/attribute[ \t]/g, "in ");
  572. result = result.replace(/[ \t]attribute/g, " in");
  573. if (isFragment) {
  574. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  576. result = result.replace(/texture2D\s*\(/g, "texture(");
  577. result = result.replace(/textureCube\s*\(/g, "texture(");
  578. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  579. result = result.replace(/gl_FragColor/g, "glFragColor");
  580. result = result.replace(/gl_FragData/g, "glFragData");
  581. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  582. }
  583. callback(result);
  584. };
  585. Effect.prototype._processIncludes = function (sourceCode, callback) {
  586. var _this = this;
  587. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  588. var match = regex.exec(sourceCode);
  589. var returnValue = new String(sourceCode);
  590. while (match != null) {
  591. var includeFile = match[1];
  592. // Uniform declaration
  593. if (includeFile.indexOf("__decl__") !== -1) {
  594. includeFile = includeFile.replace(/__decl__/, "");
  595. if (this._engine.supportsUniformBuffers) {
  596. includeFile = includeFile.replace(/Vertex/, "Ubo");
  597. includeFile = includeFile.replace(/Fragment/, "Ubo");
  598. }
  599. includeFile = includeFile + "Declaration";
  600. }
  601. if (Effect.IncludesShadersStore[includeFile]) {
  602. // Substitution
  603. var includeContent = Effect.IncludesShadersStore[includeFile];
  604. if (match[2]) {
  605. var splits = match[3].split(",");
  606. for (var index = 0; index < splits.length; index += 2) {
  607. var source = new RegExp(splits[index], "g");
  608. var dest = splits[index + 1];
  609. includeContent = includeContent.replace(source, dest);
  610. }
  611. }
  612. if (match[4]) {
  613. var indexString = match[5];
  614. if (indexString.indexOf("..") !== -1) {
  615. var indexSplits = indexString.split("..");
  616. var minIndex = parseInt(indexSplits[0]);
  617. var maxIndex = parseInt(indexSplits[1]);
  618. var sourceIncludeContent = includeContent.slice(0);
  619. includeContent = "";
  620. if (isNaN(maxIndex)) {
  621. maxIndex = this._indexParameters[indexSplits[1]];
  622. }
  623. for (var i = minIndex; i < maxIndex; i++) {
  624. if (!this._engine.supportsUniformBuffers) {
  625. // Ubo replacement
  626. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  627. return p1 + "{X}";
  628. });
  629. }
  630. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  631. }
  632. }
  633. else {
  634. if (!this._engine.supportsUniformBuffers) {
  635. // Ubo replacement
  636. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  637. return p1 + "{X}";
  638. });
  639. }
  640. includeContent = includeContent.replace(/\{X\}/g, indexString);
  641. }
  642. }
  643. // Replace
  644. returnValue = returnValue.replace(match[0], includeContent);
  645. }
  646. else {
  647. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  648. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  649. Effect.IncludesShadersStore[includeFile] = fileContent;
  650. _this._processIncludes(returnValue, callback);
  651. });
  652. return;
  653. }
  654. match = regex.exec(sourceCode);
  655. }
  656. callback(returnValue);
  657. };
  658. Effect.prototype._processPrecision = function (source) {
  659. if (source.indexOf("precision highp float") === -1) {
  660. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  661. source = "precision mediump float;\n" + source;
  662. }
  663. else {
  664. source = "precision highp float;\n" + source;
  665. }
  666. }
  667. else {
  668. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  669. source = source.replace("precision highp float", "precision mediump float");
  670. }
  671. }
  672. return source;
  673. };
  674. /**
  675. * Recompiles the webGL program
  676. * @param vertexSourceCode The source code for the vertex shader.
  677. * @param fragmentSourceCode The source code for the fragment shader.
  678. * @param onCompiled Callback called when completed.
  679. * @param onError Callback called on error.
  680. */
  681. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  682. var _this = this;
  683. this._isReady = false;
  684. this._vertexSourceCodeOverride = vertexSourceCode;
  685. this._fragmentSourceCodeOverride = fragmentSourceCode;
  686. this.onError = function (effect, error) {
  687. if (onError) {
  688. onError(error);
  689. }
  690. };
  691. this.onCompiled = function () {
  692. var scenes = _this.getEngine().scenes;
  693. for (var i = 0; i < scenes.length; i++) {
  694. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  695. }
  696. if (onCompiled) {
  697. onCompiled(_this._program);
  698. }
  699. };
  700. this._fallbacks = null;
  701. this._prepareEffect();
  702. };
  703. /**
  704. * Gets the uniform locations of the the specified variable names
  705. * @param names THe names of the variables to lookup.
  706. * @returns Array of locations in the same order as variable names.
  707. */
  708. Effect.prototype.getSpecificUniformLocations = function (names) {
  709. var engine = this._engine;
  710. return engine.getUniforms(this._program, names);
  711. };
  712. /**
  713. * Prepares the effect
  714. */
  715. Effect.prototype._prepareEffect = function () {
  716. var attributesNames = this._attributesNames;
  717. var defines = this.defines;
  718. var fallbacks = this._fallbacks;
  719. this._valueCache = {};
  720. var previousProgram = this._program;
  721. try {
  722. var engine = this._engine;
  723. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  724. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  725. }
  726. else {
  727. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  728. }
  729. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  730. if (engine.supportsUniformBuffers) {
  731. for (var name in this._uniformBuffersNames) {
  732. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  733. }
  734. }
  735. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  736. this._attributes = engine.getAttributes(this._program, attributesNames);
  737. var index;
  738. for (index = 0; index < this._samplers.length; index++) {
  739. var sampler = this.getUniform(this._samplers[index]);
  740. if (sampler == null) {
  741. this._samplers.splice(index, 1);
  742. index--;
  743. }
  744. }
  745. engine.bindSamplers(this);
  746. this._compilationError = "";
  747. this._isReady = true;
  748. if (this.onCompiled) {
  749. this.onCompiled(this);
  750. }
  751. this.onCompileObservable.notifyObservers(this);
  752. this.onCompileObservable.clear();
  753. // Unbind mesh reference in fallbacks
  754. if (this._fallbacks) {
  755. this._fallbacks.unBindMesh();
  756. }
  757. if (previousProgram) {
  758. this.getEngine()._deleteProgram(previousProgram);
  759. }
  760. }
  761. catch (e) {
  762. this._compilationError = e.message;
  763. // Let's go through fallbacks then
  764. BABYLON.Tools.Error("Unable to compile effect:");
  765. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  766. return " " + uniform;
  767. }));
  768. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  769. return " " + attribute;
  770. }));
  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._deferUnregister(observer);
  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._deferUnregister(this._observers[index]);
  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. // This should only be called when not iterating over _observers to avoid callback skipping.
  8330. // Removes an observer from the _observer Array.
  8331. Observable.prototype._remove = function (observer) {
  8332. if (!observer) {
  8333. return false;
  8334. }
  8335. var index = this._observers.indexOf(observer);
  8336. if (index !== -1) {
  8337. this._observers.splice(index, 1);
  8338. return true;
  8339. }
  8340. return false;
  8341. };
  8342. /**
  8343. * Notify all Observers by calling their respective callback with the given data
  8344. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8345. * @param eventData defines the data to send to all observers
  8346. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8347. * @param target defines the original target of the state
  8348. * @param currentTarget defines the current target of the state
  8349. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8350. */
  8351. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8352. if (mask === void 0) { mask = -1; }
  8353. if (!this._observers.length) {
  8354. return true;
  8355. }
  8356. var state = this._eventState;
  8357. state.mask = mask;
  8358. state.target = target;
  8359. state.currentTarget = currentTarget;
  8360. state.skipNextObservers = false;
  8361. state.lastReturnValue = eventData;
  8362. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8363. var obs = _a[_i];
  8364. if (obs._willBeUnregistered) {
  8365. continue;
  8366. }
  8367. if (obs.mask & mask) {
  8368. if (obs.scope) {
  8369. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8370. }
  8371. else {
  8372. state.lastReturnValue = obs.callback(eventData, state);
  8373. }
  8374. if (obs.unregisterOnNextCall) {
  8375. this._deferUnregister(obs);
  8376. }
  8377. }
  8378. if (state.skipNextObservers) {
  8379. return false;
  8380. }
  8381. }
  8382. return true;
  8383. };
  8384. /**
  8385. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8386. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8387. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8388. * and it is crucial that all callbacks will be executed.
  8389. * The order of the callbacks is kept, callbacks are not executed parallel.
  8390. *
  8391. * @param eventData The data to be sent to each callback
  8392. * @param mask is used to filter observers defaults to -1
  8393. * @param target defines the callback target (see EventState)
  8394. * @param currentTarget defines he current object in the bubbling phase
  8395. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8396. */
  8397. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8398. var _this = this;
  8399. if (mask === void 0) { mask = -1; }
  8400. // create an empty promise
  8401. var p = Promise.resolve(eventData);
  8402. // no observers? return this promise.
  8403. if (!this._observers.length) {
  8404. return p;
  8405. }
  8406. var state = this._eventState;
  8407. state.mask = mask;
  8408. state.target = target;
  8409. state.currentTarget = currentTarget;
  8410. state.skipNextObservers = false;
  8411. // execute one callback after another (not using Promise.all, the order is important)
  8412. this._observers.forEach(function (obs) {
  8413. if (state.skipNextObservers) {
  8414. return;
  8415. }
  8416. if (obs._willBeUnregistered) {
  8417. return;
  8418. }
  8419. if (obs.mask & mask) {
  8420. if (obs.scope) {
  8421. p = p.then(function (lastReturnedValue) {
  8422. state.lastReturnValue = lastReturnedValue;
  8423. return obs.callback.apply(obs.scope, [eventData, state]);
  8424. });
  8425. }
  8426. else {
  8427. p = p.then(function (lastReturnedValue) {
  8428. state.lastReturnValue = lastReturnedValue;
  8429. return obs.callback(eventData, state);
  8430. });
  8431. }
  8432. if (obs.unregisterOnNextCall) {
  8433. _this._deferUnregister(obs);
  8434. }
  8435. }
  8436. });
  8437. // return the eventData
  8438. return p.then(function () { return eventData; });
  8439. };
  8440. /**
  8441. * Notify a specific observer
  8442. * @param observer defines the observer to notify
  8443. * @param eventData defines the data to be sent to each callback
  8444. * @param mask is used to filter observers defaults to -1
  8445. */
  8446. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8447. if (mask === void 0) { mask = -1; }
  8448. var state = this._eventState;
  8449. state.mask = mask;
  8450. state.skipNextObservers = false;
  8451. observer.callback(eventData, state);
  8452. };
  8453. /**
  8454. * Gets a boolean indicating if the observable has at least one observer
  8455. * @returns true is the Observable has at least one Observer registered
  8456. */
  8457. Observable.prototype.hasObservers = function () {
  8458. return this._observers.length > 0;
  8459. };
  8460. /**
  8461. * Clear the list of observers
  8462. */
  8463. Observable.prototype.clear = function () {
  8464. this._observers = new Array();
  8465. this._onObserverAdded = null;
  8466. };
  8467. /**
  8468. * Clone the current observable
  8469. * @returns a new observable
  8470. */
  8471. Observable.prototype.clone = function () {
  8472. var result = new Observable();
  8473. result._observers = this._observers.slice(0);
  8474. return result;
  8475. };
  8476. /**
  8477. * Does this observable handles observer registered with a given mask
  8478. * @param mask defines the mask to be tested
  8479. * @return whether or not one observer registered with the given mask is handeled
  8480. **/
  8481. Observable.prototype.hasSpecificMask = function (mask) {
  8482. if (mask === void 0) { mask = -1; }
  8483. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8484. var obs = _a[_i];
  8485. if (obs.mask & mask || obs.mask === mask) {
  8486. return true;
  8487. }
  8488. }
  8489. return false;
  8490. };
  8491. return Observable;
  8492. }());
  8493. BABYLON.Observable = Observable;
  8494. })(BABYLON || (BABYLON = {}));
  8495. //# sourceMappingURL=babylon.observable.js.map
  8496. var BABYLON;
  8497. (function (BABYLON) {
  8498. var SmartArray = /** @class */ (function () {
  8499. function SmartArray(capacity) {
  8500. this.length = 0;
  8501. this.data = new Array(capacity);
  8502. this._id = SmartArray._GlobalId++;
  8503. }
  8504. SmartArray.prototype.push = function (value) {
  8505. this.data[this.length++] = value;
  8506. if (this.length > this.data.length) {
  8507. this.data.length *= 2;
  8508. }
  8509. };
  8510. SmartArray.prototype.forEach = function (func) {
  8511. for (var index = 0; index < this.length; index++) {
  8512. func(this.data[index]);
  8513. }
  8514. };
  8515. SmartArray.prototype.sort = function (compareFn) {
  8516. this.data.sort(compareFn);
  8517. };
  8518. SmartArray.prototype.reset = function () {
  8519. this.length = 0;
  8520. };
  8521. SmartArray.prototype.dispose = function () {
  8522. this.reset();
  8523. if (this.data) {
  8524. this.data.length = 0;
  8525. this.data = [];
  8526. }
  8527. };
  8528. SmartArray.prototype.concat = function (array) {
  8529. if (array.length === 0) {
  8530. return;
  8531. }
  8532. if (this.length + array.length > this.data.length) {
  8533. this.data.length = (this.length + array.length) * 2;
  8534. }
  8535. for (var index = 0; index < array.length; index++) {
  8536. this.data[this.length++] = (array.data || array)[index];
  8537. }
  8538. };
  8539. SmartArray.prototype.indexOf = function (value) {
  8540. var position = this.data.indexOf(value);
  8541. if (position >= this.length) {
  8542. return -1;
  8543. }
  8544. return position;
  8545. };
  8546. SmartArray.prototype.contains = function (value) {
  8547. return this.data.indexOf(value) !== -1;
  8548. };
  8549. // Statics
  8550. SmartArray._GlobalId = 0;
  8551. return SmartArray;
  8552. }());
  8553. BABYLON.SmartArray = SmartArray;
  8554. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8555. __extends(SmartArrayNoDuplicate, _super);
  8556. function SmartArrayNoDuplicate() {
  8557. var _this = _super !== null && _super.apply(this, arguments) || this;
  8558. _this._duplicateId = 0;
  8559. return _this;
  8560. }
  8561. SmartArrayNoDuplicate.prototype.push = function (value) {
  8562. _super.prototype.push.call(this, value);
  8563. if (!value.__smartArrayFlags) {
  8564. value.__smartArrayFlags = {};
  8565. }
  8566. value.__smartArrayFlags[this._id] = this._duplicateId;
  8567. };
  8568. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8569. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8570. return false;
  8571. }
  8572. this.push(value);
  8573. return true;
  8574. };
  8575. SmartArrayNoDuplicate.prototype.reset = function () {
  8576. _super.prototype.reset.call(this);
  8577. this._duplicateId++;
  8578. };
  8579. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8580. if (array.length === 0) {
  8581. return;
  8582. }
  8583. if (this.length + array.length > this.data.length) {
  8584. this.data.length = (this.length + array.length) * 2;
  8585. }
  8586. for (var index = 0; index < array.length; index++) {
  8587. var item = (array.data || array)[index];
  8588. this.pushNoDuplicate(item);
  8589. }
  8590. };
  8591. return SmartArrayNoDuplicate;
  8592. }(SmartArray));
  8593. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8594. })(BABYLON || (BABYLON = {}));
  8595. //# sourceMappingURL=babylon.smartArray.js.map
  8596. var BABYLON;
  8597. (function (BABYLON) {
  8598. /** Class used to store color gradient */
  8599. var ColorGradient = /** @class */ (function () {
  8600. function ColorGradient() {
  8601. }
  8602. /**
  8603. * Will get a color picked randomly between color1 and color2.
  8604. * If color2 is undefined then color1 will be used
  8605. * @param result defines the target Color4 to store the result in
  8606. */
  8607. ColorGradient.prototype.getColorToRef = function (result) {
  8608. if (!this.color2) {
  8609. result.copyFrom(this.color1);
  8610. return;
  8611. }
  8612. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8613. };
  8614. return ColorGradient;
  8615. }());
  8616. BABYLON.ColorGradient = ColorGradient;
  8617. /** Class used to store factor gradient */
  8618. var FactorGradient = /** @class */ (function () {
  8619. function FactorGradient() {
  8620. }
  8621. /**
  8622. * Will get a number picked randomly between factor1 and factor2.
  8623. * If factor2 is undefined then factor1 will be used
  8624. * @returns the picked number
  8625. */
  8626. FactorGradient.prototype.getFactor = function () {
  8627. if (this.factor2 === undefined) {
  8628. return this.factor1;
  8629. }
  8630. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8631. };
  8632. return FactorGradient;
  8633. }());
  8634. BABYLON.FactorGradient = FactorGradient;
  8635. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8636. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8637. var LoadFileError = /** @class */ (function (_super) {
  8638. __extends(LoadFileError, _super);
  8639. function LoadFileError(message, request) {
  8640. var _this = _super.call(this, message) || this;
  8641. _this.request = request;
  8642. _this.name = "LoadFileError";
  8643. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8644. return _this;
  8645. }
  8646. // Polyfill for Object.setPrototypeOf if necessary.
  8647. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8648. return LoadFileError;
  8649. }(Error));
  8650. BABYLON.LoadFileError = LoadFileError;
  8651. var RetryStrategy = /** @class */ (function () {
  8652. function RetryStrategy() {
  8653. }
  8654. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8655. if (maxRetries === void 0) { maxRetries = 3; }
  8656. if (baseInterval === void 0) { baseInterval = 500; }
  8657. return function (url, request, retryIndex) {
  8658. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8659. return -1;
  8660. }
  8661. return Math.pow(2, retryIndex) * baseInterval;
  8662. };
  8663. };
  8664. return RetryStrategy;
  8665. }());
  8666. BABYLON.RetryStrategy = RetryStrategy;
  8667. // Screenshots
  8668. var screenshotCanvas;
  8669. var cloneValue = function (source, destinationObject) {
  8670. if (!source)
  8671. return null;
  8672. if (source instanceof BABYLON.Mesh) {
  8673. return null;
  8674. }
  8675. if (source instanceof BABYLON.SubMesh) {
  8676. return source.clone(destinationObject);
  8677. }
  8678. else if (source.clone) {
  8679. return source.clone();
  8680. }
  8681. return null;
  8682. };
  8683. var Tools = /** @class */ (function () {
  8684. function Tools() {
  8685. }
  8686. /**
  8687. * Interpolates between a and b via alpha
  8688. * @param a The lower value (returned when alpha = 0)
  8689. * @param b The upper value (returned when alpha = 1)
  8690. * @param alpha The interpolation-factor
  8691. * @return The mixed value
  8692. */
  8693. Tools.Mix = function (a, b, alpha) {
  8694. return a * (1 - alpha) + b * alpha;
  8695. };
  8696. Tools.Instantiate = function (className) {
  8697. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8698. return Tools.RegisteredExternalClasses[className];
  8699. }
  8700. var arr = className.split(".");
  8701. var fn = (window || this);
  8702. for (var i = 0, len = arr.length; i < len; i++) {
  8703. fn = fn[arr[i]];
  8704. }
  8705. if (typeof fn !== "function") {
  8706. return null;
  8707. }
  8708. return fn;
  8709. };
  8710. /**
  8711. * Provides a slice function that will work even on IE
  8712. * @param data defines the array to slice
  8713. * @param start defines the start of the data (optional)
  8714. * @param end defines the end of the data (optional)
  8715. * @returns the new sliced array
  8716. */
  8717. Tools.Slice = function (data, start, end) {
  8718. if (data.slice) {
  8719. return data.slice(start, end);
  8720. }
  8721. return Array.prototype.slice.call(data, start, end);
  8722. };
  8723. Tools.SetImmediate = function (action) {
  8724. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8725. window.setImmediate(action);
  8726. }
  8727. else {
  8728. setTimeout(action, 1);
  8729. }
  8730. };
  8731. Tools.IsExponentOfTwo = function (value) {
  8732. var count = 1;
  8733. do {
  8734. count *= 2;
  8735. } while (count < value);
  8736. return count === value;
  8737. };
  8738. /**
  8739. * Returns the nearest 32-bit single precision float representation of a Number
  8740. * @param value A Number. If the parameter is of a different type, it will get converted
  8741. * to a number or to NaN if it cannot be converted
  8742. * @returns number
  8743. */
  8744. Tools.FloatRound = function (value) {
  8745. if (Math.fround) {
  8746. return Math.fround(value);
  8747. }
  8748. return (Tools._tmpFloatArray[0] = value);
  8749. };
  8750. /**
  8751. * Find the next highest power of two.
  8752. * @param x Number to start search from.
  8753. * @return Next highest power of two.
  8754. */
  8755. Tools.CeilingPOT = function (x) {
  8756. x--;
  8757. x |= x >> 1;
  8758. x |= x >> 2;
  8759. x |= x >> 4;
  8760. x |= x >> 8;
  8761. x |= x >> 16;
  8762. x++;
  8763. return x;
  8764. };
  8765. /**
  8766. * Find the next lowest power of two.
  8767. * @param x Number to start search from.
  8768. * @return Next lowest power of two.
  8769. */
  8770. Tools.FloorPOT = function (x) {
  8771. x = x | (x >> 1);
  8772. x = x | (x >> 2);
  8773. x = x | (x >> 4);
  8774. x = x | (x >> 8);
  8775. x = x | (x >> 16);
  8776. return x - (x >> 1);
  8777. };
  8778. /**
  8779. * Find the nearest power of two.
  8780. * @param x Number to start search from.
  8781. * @return Next nearest power of two.
  8782. */
  8783. Tools.NearestPOT = function (x) {
  8784. var c = Tools.CeilingPOT(x);
  8785. var f = Tools.FloorPOT(x);
  8786. return (c - x) > (x - f) ? f : c;
  8787. };
  8788. Tools.GetExponentOfTwo = function (value, max, mode) {
  8789. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8790. var pot;
  8791. switch (mode) {
  8792. case BABYLON.Engine.SCALEMODE_FLOOR:
  8793. pot = Tools.FloorPOT(value);
  8794. break;
  8795. case BABYLON.Engine.SCALEMODE_NEAREST:
  8796. pot = Tools.NearestPOT(value);
  8797. break;
  8798. case BABYLON.Engine.SCALEMODE_CEILING:
  8799. default:
  8800. pot = Tools.CeilingPOT(value);
  8801. break;
  8802. }
  8803. return Math.min(pot, max);
  8804. };
  8805. Tools.GetFilename = function (path) {
  8806. var index = path.lastIndexOf("/");
  8807. if (index < 0)
  8808. return path;
  8809. return path.substring(index + 1);
  8810. };
  8811. /**
  8812. * Extracts the "folder" part of a path (everything before the filename).
  8813. * @param uri The URI to extract the info from
  8814. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8815. * @returns The "folder" part of the path
  8816. */
  8817. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8818. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8819. var index = uri.lastIndexOf("/");
  8820. if (index < 0) {
  8821. if (returnUnchangedIfNoSlash) {
  8822. return uri;
  8823. }
  8824. return "";
  8825. }
  8826. return uri.substring(0, index + 1);
  8827. };
  8828. Tools.GetDOMTextContent = function (element) {
  8829. var result = "";
  8830. var child = element.firstChild;
  8831. while (child) {
  8832. if (child.nodeType === 3) {
  8833. result += child.textContent;
  8834. }
  8835. child = child.nextSibling;
  8836. }
  8837. return result;
  8838. };
  8839. Tools.ToDegrees = function (angle) {
  8840. return angle * 180 / Math.PI;
  8841. };
  8842. Tools.ToRadians = function (angle) {
  8843. return angle * Math.PI / 180;
  8844. };
  8845. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8846. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8847. var output = "";
  8848. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8849. var i = 0;
  8850. var bytes = new Uint8Array(buffer);
  8851. while (i < bytes.length) {
  8852. chr1 = bytes[i++];
  8853. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8854. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8855. enc1 = chr1 >> 2;
  8856. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8857. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8858. enc4 = chr3 & 63;
  8859. if (isNaN(chr2)) {
  8860. enc3 = enc4 = 64;
  8861. }
  8862. else if (isNaN(chr3)) {
  8863. enc4 = 64;
  8864. }
  8865. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8866. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8867. }
  8868. return "data:image/png;base64," + output;
  8869. };
  8870. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8871. if (bias === void 0) { bias = null; }
  8872. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8873. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8874. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8875. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8876. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8877. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8878. }
  8879. if (bias) {
  8880. minimum.x -= minimum.x * bias.x + bias.y;
  8881. minimum.y -= minimum.y * bias.x + bias.y;
  8882. minimum.z -= minimum.z * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. maximum.z += maximum.z * bias.x + bias.y;
  8886. }
  8887. return {
  8888. minimum: minimum,
  8889. maximum: maximum
  8890. };
  8891. };
  8892. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8893. if (bias === void 0) { bias = null; }
  8894. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8895. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8896. if (!stride) {
  8897. stride = 3;
  8898. }
  8899. for (var index = start; index < start + count; index++) {
  8900. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8901. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8902. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8903. }
  8904. if (bias) {
  8905. minimum.x -= minimum.x * bias.x + bias.y;
  8906. minimum.y -= minimum.y * bias.x + bias.y;
  8907. minimum.z -= minimum.z * bias.x + bias.y;
  8908. maximum.x += maximum.x * bias.x + bias.y;
  8909. maximum.y += maximum.y * bias.x + bias.y;
  8910. maximum.z += maximum.z * bias.x + bias.y;
  8911. }
  8912. return {
  8913. minimum: minimum,
  8914. maximum: maximum
  8915. };
  8916. };
  8917. Tools.Vector2ArrayFeeder = function (array) {
  8918. return function (index) {
  8919. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8920. var length = isFloatArray ? array.length / 2 : array.length;
  8921. if (index >= length) {
  8922. return null;
  8923. }
  8924. if (isFloatArray) {
  8925. var fa = array;
  8926. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8927. }
  8928. var a = array;
  8929. return a[index];
  8930. };
  8931. };
  8932. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8933. if (bias === void 0) { bias = null; }
  8934. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8935. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8936. var i = 0;
  8937. var cur = feeder(i++);
  8938. while (cur) {
  8939. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8940. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8941. cur = feeder(i++);
  8942. }
  8943. if (bias) {
  8944. minimum.x -= minimum.x * bias.x + bias.y;
  8945. minimum.y -= minimum.y * bias.x + bias.y;
  8946. maximum.x += maximum.x * bias.x + bias.y;
  8947. maximum.y += maximum.y * bias.x + bias.y;
  8948. }
  8949. return {
  8950. minimum: minimum,
  8951. maximum: maximum
  8952. };
  8953. };
  8954. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8955. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8956. return null;
  8957. return Array.isArray(obj) ? obj : [obj];
  8958. };
  8959. // Misc.
  8960. Tools.GetPointerPrefix = function () {
  8961. var eventPrefix = "pointer";
  8962. // Check if pointer events are supported
  8963. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8964. eventPrefix = "mouse";
  8965. }
  8966. return eventPrefix;
  8967. };
  8968. /**
  8969. * @param func - the function to be called
  8970. * @param requester - the object that will request the next frame. Falls back to window.
  8971. */
  8972. Tools.QueueNewFrame = function (func, requester) {
  8973. if (!Tools.IsWindowObjectExist()) {
  8974. return setTimeout(func, 16);
  8975. }
  8976. if (!requester) {
  8977. requester = window;
  8978. }
  8979. if (requester.requestAnimationFrame) {
  8980. return requester.requestAnimationFrame(func);
  8981. }
  8982. else if (requester.msRequestAnimationFrame) {
  8983. return requester.msRequestAnimationFrame(func);
  8984. }
  8985. else if (requester.webkitRequestAnimationFrame) {
  8986. return requester.webkitRequestAnimationFrame(func);
  8987. }
  8988. else if (requester.mozRequestAnimationFrame) {
  8989. return requester.mozRequestAnimationFrame(func);
  8990. }
  8991. else if (requester.oRequestAnimationFrame) {
  8992. return requester.oRequestAnimationFrame(func);
  8993. }
  8994. else {
  8995. return window.setTimeout(func, 16);
  8996. }
  8997. };
  8998. Tools.RequestFullscreen = function (element) {
  8999. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9000. if (!requestFunction)
  9001. return;
  9002. requestFunction.call(element);
  9003. };
  9004. Tools.ExitFullscreen = function () {
  9005. if (document.exitFullscreen) {
  9006. document.exitFullscreen();
  9007. }
  9008. else if (document.mozCancelFullScreen) {
  9009. document.mozCancelFullScreen();
  9010. }
  9011. else if (document.webkitCancelFullScreen) {
  9012. document.webkitCancelFullScreen();
  9013. }
  9014. else if (document.msCancelFullScreen) {
  9015. document.msCancelFullScreen();
  9016. }
  9017. };
  9018. Tools.SetCorsBehavior = function (url, element) {
  9019. if (url && url.indexOf("data:") === 0) {
  9020. return;
  9021. }
  9022. if (Tools.CorsBehavior) {
  9023. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9024. element.crossOrigin = Tools.CorsBehavior;
  9025. }
  9026. else {
  9027. var result = Tools.CorsBehavior(url);
  9028. if (result) {
  9029. element.crossOrigin = result;
  9030. }
  9031. }
  9032. }
  9033. };
  9034. // External files
  9035. Tools.CleanUrl = function (url) {
  9036. url = url.replace(/#/mg, "%23");
  9037. return url;
  9038. };
  9039. /**
  9040. * Loads an image as an HTMLImageElement.
  9041. * @param input url string, ArrayBuffer, or Blob to load
  9042. * @param onLoad callback called when the image successfully loads
  9043. * @param onError callback called when the image fails to load
  9044. * @param database database for caching
  9045. * @returns the HTMLImageElement of the loaded image
  9046. */
  9047. Tools.LoadImage = function (input, onLoad, onError, database) {
  9048. var url;
  9049. var usingObjectURL = false;
  9050. if (input instanceof ArrayBuffer) {
  9051. url = URL.createObjectURL(new Blob([input]));
  9052. usingObjectURL = true;
  9053. }
  9054. else if (input instanceof Blob) {
  9055. url = URL.createObjectURL(input);
  9056. usingObjectURL = true;
  9057. }
  9058. else {
  9059. url = Tools.CleanUrl(input);
  9060. url = Tools.PreprocessUrl(input);
  9061. }
  9062. var img = new Image();
  9063. Tools.SetCorsBehavior(url, img);
  9064. var loadHandler = function () {
  9065. if (usingObjectURL && img.src) {
  9066. URL.revokeObjectURL(img.src);
  9067. }
  9068. img.removeEventListener("load", loadHandler);
  9069. img.removeEventListener("error", errorHandler);
  9070. onLoad(img);
  9071. };
  9072. var errorHandler = function (err) {
  9073. if (usingObjectURL && img.src) {
  9074. URL.revokeObjectURL(img.src);
  9075. }
  9076. img.removeEventListener("load", loadHandler);
  9077. img.removeEventListener("error", errorHandler);
  9078. Tools.Error("Error while trying to load image: " + input);
  9079. if (onError) {
  9080. onError("Error while trying to load image: " + input, err);
  9081. }
  9082. };
  9083. img.addEventListener("load", loadHandler);
  9084. img.addEventListener("error", errorHandler);
  9085. var noIndexedDB = function () {
  9086. img.src = url;
  9087. };
  9088. var loadFromIndexedDB = function () {
  9089. if (database) {
  9090. database.loadImageFromDB(url, img);
  9091. }
  9092. };
  9093. //ANY database to do!
  9094. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9095. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9096. }
  9097. else {
  9098. if (url.indexOf("file:") !== -1) {
  9099. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9100. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9101. try {
  9102. var blobURL;
  9103. try {
  9104. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9105. }
  9106. catch (ex) {
  9107. // Chrome doesn't support oneTimeOnly parameter
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. img.src = blobURL;
  9111. usingObjectURL = true;
  9112. }
  9113. catch (e) {
  9114. img.src = "";
  9115. }
  9116. return img;
  9117. }
  9118. }
  9119. noIndexedDB();
  9120. }
  9121. return img;
  9122. };
  9123. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9124. url = Tools.CleanUrl(url);
  9125. url = Tools.PreprocessUrl(url);
  9126. // If file and file input are set
  9127. if (url.indexOf("file:") !== -1) {
  9128. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9129. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9130. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9131. }
  9132. }
  9133. var loadUrl = Tools.BaseUrl + url;
  9134. var aborted = false;
  9135. var fileRequest = {
  9136. onCompleteObservable: new BABYLON.Observable(),
  9137. abort: function () { return aborted = true; },
  9138. };
  9139. var requestFile = function () {
  9140. var request = new XMLHttpRequest();
  9141. var retryHandle = null;
  9142. fileRequest.abort = function () {
  9143. aborted = true;
  9144. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9145. request.abort();
  9146. }
  9147. if (retryHandle !== null) {
  9148. clearTimeout(retryHandle);
  9149. retryHandle = null;
  9150. }
  9151. };
  9152. var retryLoop = function (retryIndex) {
  9153. request.open('GET', loadUrl, true);
  9154. if (useArrayBuffer) {
  9155. request.responseType = "arraybuffer";
  9156. }
  9157. if (onProgress) {
  9158. request.addEventListener("progress", onProgress);
  9159. }
  9160. var onLoadEnd = function () {
  9161. request.removeEventListener("loadend", onLoadEnd);
  9162. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9163. fileRequest.onCompleteObservable.clear();
  9164. };
  9165. request.addEventListener("loadend", onLoadEnd);
  9166. var onReadyStateChange = function () {
  9167. if (aborted) {
  9168. return;
  9169. }
  9170. // In case of undefined state in some browsers.
  9171. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9172. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9173. request.removeEventListener("readystatechange", onReadyStateChange);
  9174. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9175. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9176. return;
  9177. }
  9178. var retryStrategy = Tools.DefaultRetryStrategy;
  9179. if (retryStrategy) {
  9180. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9181. if (waitTime !== -1) {
  9182. // Prevent the request from completing for retry.
  9183. request.removeEventListener("loadend", onLoadEnd);
  9184. request = new XMLHttpRequest();
  9185. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9186. return;
  9187. }
  9188. }
  9189. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9190. if (onError) {
  9191. onError(request, e);
  9192. }
  9193. else {
  9194. throw e;
  9195. }
  9196. }
  9197. };
  9198. request.addEventListener("readystatechange", onReadyStateChange);
  9199. request.send();
  9200. };
  9201. retryLoop(0);
  9202. };
  9203. // Caching all files
  9204. if (database && database.enableSceneOffline) {
  9205. var noIndexedDB_1 = function (request) {
  9206. if (request && request.status > 400) {
  9207. if (onError) {
  9208. onError(request);
  9209. }
  9210. }
  9211. else {
  9212. if (!aborted) {
  9213. requestFile();
  9214. }
  9215. }
  9216. };
  9217. var loadFromIndexedDB = function () {
  9218. // TODO: database needs to support aborting and should return a IFileRequest
  9219. if (aborted) {
  9220. return;
  9221. }
  9222. if (database) {
  9223. database.loadFileFromDB(url, function (data) {
  9224. if (!aborted) {
  9225. onSuccess(data);
  9226. }
  9227. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9228. }, onProgress ? function (event) {
  9229. if (!aborted) {
  9230. onProgress(event);
  9231. }
  9232. } : undefined, noIndexedDB_1, useArrayBuffer);
  9233. }
  9234. };
  9235. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9236. }
  9237. else {
  9238. requestFile();
  9239. }
  9240. return fileRequest;
  9241. };
  9242. /**
  9243. * Load a script (identified by an url). When the url returns, the
  9244. * content of this file is added into a new script element, attached to the DOM (body element)
  9245. */
  9246. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9247. var head = document.getElementsByTagName('head')[0];
  9248. var script = document.createElement('script');
  9249. script.type = 'text/javascript';
  9250. script.src = scriptUrl;
  9251. script.onload = function () {
  9252. if (onSuccess) {
  9253. onSuccess();
  9254. }
  9255. };
  9256. script.onerror = function (e) {
  9257. if (onError) {
  9258. onError("Unable to load script '" + scriptUrl + "'", e);
  9259. }
  9260. };
  9261. head.appendChild(script);
  9262. };
  9263. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9264. var reader = new FileReader();
  9265. var request = {
  9266. onCompleteObservable: new BABYLON.Observable(),
  9267. abort: function () { return reader.abort(); },
  9268. };
  9269. reader.onloadend = function (e) {
  9270. request.onCompleteObservable.notifyObservers(request);
  9271. };
  9272. reader.onload = function (e) {
  9273. //target doesn't have result from ts 1.3
  9274. callback(e.target['result']);
  9275. };
  9276. reader.onprogress = progressCallback;
  9277. reader.readAsDataURL(fileToLoad);
  9278. return request;
  9279. };
  9280. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9281. var reader = new FileReader();
  9282. var request = {
  9283. onCompleteObservable: new BABYLON.Observable(),
  9284. abort: function () { return reader.abort(); },
  9285. };
  9286. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9287. reader.onerror = function (e) {
  9288. Tools.Log("Error while reading file: " + fileToLoad.name);
  9289. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9290. };
  9291. reader.onload = function (e) {
  9292. //target doesn't have result from ts 1.3
  9293. callback(e.target['result']);
  9294. };
  9295. if (progressCallBack) {
  9296. reader.onprogress = progressCallBack;
  9297. }
  9298. if (!useArrayBuffer) {
  9299. // Asynchronous read
  9300. reader.readAsText(fileToLoad);
  9301. }
  9302. else {
  9303. reader.readAsArrayBuffer(fileToLoad);
  9304. }
  9305. return request;
  9306. };
  9307. //returns a downloadable url to a file content.
  9308. Tools.FileAsURL = function (content) {
  9309. var fileBlob = new Blob([content]);
  9310. var url = window.URL || window.webkitURL;
  9311. var link = url.createObjectURL(fileBlob);
  9312. return link;
  9313. };
  9314. // Misc.
  9315. Tools.Format = function (value, decimals) {
  9316. if (decimals === void 0) { decimals = 2; }
  9317. return value.toFixed(decimals);
  9318. };
  9319. Tools.CheckExtends = function (v, min, max) {
  9320. if (v.x < min.x)
  9321. min.x = v.x;
  9322. if (v.y < min.y)
  9323. min.y = v.y;
  9324. if (v.z < min.z)
  9325. min.z = v.z;
  9326. if (v.x > max.x)
  9327. max.x = v.x;
  9328. if (v.y > max.y)
  9329. max.y = v.y;
  9330. if (v.z > max.z)
  9331. max.z = v.z;
  9332. };
  9333. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9334. for (var prop in source) {
  9335. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9336. continue;
  9337. }
  9338. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9339. continue;
  9340. }
  9341. var sourceValue = source[prop];
  9342. var typeOfSourceValue = typeof sourceValue;
  9343. if (typeOfSourceValue === "function") {
  9344. continue;
  9345. }
  9346. try {
  9347. if (typeOfSourceValue === "object") {
  9348. if (sourceValue instanceof Array) {
  9349. destination[prop] = [];
  9350. if (sourceValue.length > 0) {
  9351. if (typeof sourceValue[0] == "object") {
  9352. for (var index = 0; index < sourceValue.length; index++) {
  9353. var clonedValue = cloneValue(sourceValue[index], destination);
  9354. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9355. destination[prop].push(clonedValue);
  9356. }
  9357. }
  9358. }
  9359. else {
  9360. destination[prop] = sourceValue.slice(0);
  9361. }
  9362. }
  9363. }
  9364. else {
  9365. destination[prop] = cloneValue(sourceValue, destination);
  9366. }
  9367. }
  9368. else {
  9369. destination[prop] = sourceValue;
  9370. }
  9371. }
  9372. catch (e) {
  9373. // Just ignore error (it could be because of a read-only property)
  9374. }
  9375. }
  9376. };
  9377. Tools.IsEmpty = function (obj) {
  9378. for (var i in obj) {
  9379. if (obj.hasOwnProperty(i)) {
  9380. return false;
  9381. }
  9382. }
  9383. return true;
  9384. };
  9385. Tools.RegisterTopRootEvents = function (events) {
  9386. for (var index = 0; index < events.length; index++) {
  9387. var event = events[index];
  9388. window.addEventListener(event.name, event.handler, false);
  9389. try {
  9390. if (window.parent) {
  9391. window.parent.addEventListener(event.name, event.handler, false);
  9392. }
  9393. }
  9394. catch (e) {
  9395. // Silently fails...
  9396. }
  9397. }
  9398. };
  9399. Tools.UnregisterTopRootEvents = function (events) {
  9400. for (var index = 0; index < events.length; index++) {
  9401. var event = events[index];
  9402. window.removeEventListener(event.name, event.handler);
  9403. try {
  9404. if (window.parent) {
  9405. window.parent.removeEventListener(event.name, event.handler);
  9406. }
  9407. }
  9408. catch (e) {
  9409. // Silently fails...
  9410. }
  9411. }
  9412. };
  9413. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9414. if (mimeType === void 0) { mimeType = "image/png"; }
  9415. // Read the contents of the framebuffer
  9416. var numberOfChannelsByLine = width * 4;
  9417. var halfHeight = height / 2;
  9418. //Reading datas from WebGL
  9419. var data = engine.readPixels(0, 0, width, height);
  9420. //To flip image on Y axis.
  9421. for (var i = 0; i < halfHeight; i++) {
  9422. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9423. var currentCell = j + i * numberOfChannelsByLine;
  9424. var targetLine = height - i - 1;
  9425. var targetCell = j + targetLine * numberOfChannelsByLine;
  9426. var temp = data[currentCell];
  9427. data[currentCell] = data[targetCell];
  9428. data[targetCell] = temp;
  9429. }
  9430. }
  9431. // Create a 2D canvas to store the result
  9432. if (!screenshotCanvas) {
  9433. screenshotCanvas = document.createElement('canvas');
  9434. }
  9435. screenshotCanvas.width = width;
  9436. screenshotCanvas.height = height;
  9437. var context = screenshotCanvas.getContext('2d');
  9438. if (context) {
  9439. // Copy the pixels to a 2D canvas
  9440. var imageData = context.createImageData(width, height);
  9441. var castData = (imageData.data);
  9442. castData.set(data);
  9443. context.putImageData(imageData, 0, 0);
  9444. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9445. }
  9446. };
  9447. /**
  9448. * Converts the canvas data to blob.
  9449. * This acts as a polyfill for browsers not supporting the to blob function.
  9450. * @param canvas Defines the canvas to extract the data from
  9451. * @param successCallback Defines the callback triggered once the data are available
  9452. * @param mimeType Defines the mime type of the result
  9453. */
  9454. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9455. if (mimeType === void 0) { mimeType = "image/png"; }
  9456. // We need HTMLCanvasElement.toBlob for HD screenshots
  9457. if (!canvas.toBlob) {
  9458. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9459. canvas.toBlob = function (callback, type, quality) {
  9460. var _this = this;
  9461. setTimeout(function () {
  9462. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9463. for (var i = 0; i < len; i++) {
  9464. arr[i] = binStr.charCodeAt(i);
  9465. }
  9466. callback(new Blob([arr]));
  9467. });
  9468. };
  9469. }
  9470. canvas.toBlob(function (blob) {
  9471. successCallback(blob);
  9472. }, mimeType);
  9473. };
  9474. /**
  9475. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9476. * @param successCallback Defines the callback triggered once the data are available
  9477. * @param mimeType Defines the mime type of the result
  9478. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9479. */
  9480. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9481. if (mimeType === void 0) { mimeType = "image/png"; }
  9482. if (successCallback) {
  9483. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9484. successCallback(base64Image);
  9485. }
  9486. else {
  9487. this.ToBlob(screenshotCanvas, function (blob) {
  9488. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9489. if (("download" in document.createElement("a"))) {
  9490. if (!fileName) {
  9491. var date = new Date();
  9492. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9493. fileName = "screenshot_" + stringDate + ".png";
  9494. }
  9495. Tools.Download(blob, fileName);
  9496. }
  9497. else {
  9498. var url = URL.createObjectURL(blob);
  9499. var newWindow = window.open("");
  9500. if (!newWindow)
  9501. return;
  9502. var img = newWindow.document.createElement("img");
  9503. img.onload = function () {
  9504. // no longer need to read the blob so it's revoked
  9505. URL.revokeObjectURL(url);
  9506. };
  9507. img.src = url;
  9508. newWindow.document.body.appendChild(img);
  9509. }
  9510. }, mimeType);
  9511. }
  9512. };
  9513. /**
  9514. * Downloads a blob in the browser
  9515. * @param blob defines the blob to download
  9516. * @param fileName defines the name of the downloaded file
  9517. */
  9518. Tools.Download = function (blob, fileName) {
  9519. if (navigator && navigator.msSaveBlob) {
  9520. navigator.msSaveBlob(blob, fileName);
  9521. return;
  9522. }
  9523. var url = window.URL.createObjectURL(blob);
  9524. var a = document.createElement("a");
  9525. document.body.appendChild(a);
  9526. a.style.display = "none";
  9527. a.href = url;
  9528. a.download = fileName;
  9529. a.addEventListener("click", function () {
  9530. if (a.parentElement) {
  9531. a.parentElement.removeChild(a);
  9532. }
  9533. });
  9534. a.click();
  9535. window.URL.revokeObjectURL(url);
  9536. };
  9537. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9538. if (mimeType === void 0) { mimeType = "image/png"; }
  9539. var width;
  9540. var height;
  9541. // If a precision value is specified
  9542. if (size.precision) {
  9543. width = Math.round(engine.getRenderWidth() * size.precision);
  9544. height = Math.round(width / engine.getAspectRatio(camera));
  9545. }
  9546. else if (size.width && size.height) {
  9547. width = size.width;
  9548. height = size.height;
  9549. }
  9550. //If passing only width, computing height to keep display canvas ratio.
  9551. else if (size.width && !size.height) {
  9552. width = size.width;
  9553. height = Math.round(width / engine.getAspectRatio(camera));
  9554. }
  9555. //If passing only height, computing width to keep display canvas ratio.
  9556. else if (size.height && !size.width) {
  9557. height = size.height;
  9558. width = Math.round(height * engine.getAspectRatio(camera));
  9559. }
  9560. //Assuming here that "size" parameter is a number
  9561. else if (!isNaN(size)) {
  9562. height = size;
  9563. width = size;
  9564. }
  9565. else {
  9566. Tools.Error("Invalid 'size' parameter !");
  9567. return;
  9568. }
  9569. if (!screenshotCanvas) {
  9570. screenshotCanvas = document.createElement('canvas');
  9571. }
  9572. screenshotCanvas.width = width;
  9573. screenshotCanvas.height = height;
  9574. var renderContext = screenshotCanvas.getContext("2d");
  9575. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9576. var newWidth = width;
  9577. var newHeight = newWidth / ratio;
  9578. if (newHeight > height) {
  9579. newHeight = height;
  9580. newWidth = newHeight * ratio;
  9581. }
  9582. var offsetX = Math.max(0, width - newWidth) / 2;
  9583. var offsetY = Math.max(0, height - newHeight) / 2;
  9584. var renderingCanvas = engine.getRenderingCanvas();
  9585. if (renderContext && renderingCanvas) {
  9586. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9587. }
  9588. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9589. };
  9590. /**
  9591. * Generates an image screenshot from the specified camera.
  9592. *
  9593. * @param engine The engine to use for rendering
  9594. * @param camera The camera to use for rendering
  9595. * @param size This parameter can be set to a single number or to an object with the
  9596. * following (optional) properties: precision, width, height. If a single number is passed,
  9597. * it will be used for both width and height. If an object is passed, the screenshot size
  9598. * will be derived from the parameters. The precision property is a multiplier allowing
  9599. * rendering at a higher or lower resolution.
  9600. * @param successCallback The callback receives a single parameter which contains the
  9601. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9602. * src parameter of an <img> to display it.
  9603. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9604. * Check your browser for supported MIME types.
  9605. * @param samples Texture samples (default: 1)
  9606. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9607. * @param fileName A name for for the downloaded file.
  9608. * @constructor
  9609. */
  9610. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9611. if (mimeType === void 0) { mimeType = "image/png"; }
  9612. if (samples === void 0) { samples = 1; }
  9613. if (antialiasing === void 0) { antialiasing = false; }
  9614. var width;
  9615. var height;
  9616. //If a precision value is specified
  9617. if (size.precision) {
  9618. width = Math.round(engine.getRenderWidth() * size.precision);
  9619. height = Math.round(width / engine.getAspectRatio(camera));
  9620. size = { width: width, height: height };
  9621. }
  9622. else if (size.width && size.height) {
  9623. width = size.width;
  9624. height = size.height;
  9625. }
  9626. //If passing only width, computing height to keep display canvas ratio.
  9627. else if (size.width && !size.height) {
  9628. width = size.width;
  9629. height = Math.round(width / engine.getAspectRatio(camera));
  9630. size = { width: width, height: height };
  9631. }
  9632. //If passing only height, computing width to keep display canvas ratio.
  9633. else if (size.height && !size.width) {
  9634. height = size.height;
  9635. width = Math.round(height * engine.getAspectRatio(camera));
  9636. size = { width: width, height: height };
  9637. }
  9638. //Assuming here that "size" parameter is a number
  9639. else if (!isNaN(size)) {
  9640. height = size;
  9641. width = size;
  9642. }
  9643. else {
  9644. Tools.Error("Invalid 'size' parameter !");
  9645. return;
  9646. }
  9647. var scene = camera.getScene();
  9648. var previousCamera = null;
  9649. if (scene.activeCamera !== camera) {
  9650. previousCamera = scene.activeCamera;
  9651. scene.activeCamera = camera;
  9652. }
  9653. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9654. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9655. texture.renderList = null;
  9656. texture.samples = samples;
  9657. if (antialiasing) {
  9658. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9659. }
  9660. texture.onAfterRenderObservable.add(function () {
  9661. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9662. });
  9663. scene.incrementRenderId();
  9664. scene.resetCachedMaterial();
  9665. texture.render(true);
  9666. texture.dispose();
  9667. if (previousCamera) {
  9668. scene.activeCamera = previousCamera;
  9669. }
  9670. camera.getProjectionMatrix(true); // Force cache refresh;
  9671. };
  9672. // XHR response validator for local file scenario
  9673. Tools.ValidateXHRData = function (xhr, dataType) {
  9674. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9675. if (dataType === void 0) { dataType = 7; }
  9676. try {
  9677. if (dataType & 1) {
  9678. if (xhr.responseText && xhr.responseText.length > 0) {
  9679. return true;
  9680. }
  9681. else if (dataType === 1) {
  9682. return false;
  9683. }
  9684. }
  9685. if (dataType & 2) {
  9686. // Check header width and height since there is no "TGA" magic number
  9687. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9688. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9689. return true;
  9690. }
  9691. else if (dataType === 2) {
  9692. return false;
  9693. }
  9694. }
  9695. if (dataType & 4) {
  9696. // Check for the "DDS" magic number
  9697. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9698. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9699. return true;
  9700. }
  9701. else {
  9702. return false;
  9703. }
  9704. }
  9705. }
  9706. catch (e) {
  9707. // Global protection
  9708. }
  9709. return false;
  9710. };
  9711. /**
  9712. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9713. * Be aware Math.random() could cause collisions, but:
  9714. * "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"
  9715. */
  9716. Tools.RandomId = function () {
  9717. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9718. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9719. return v.toString(16);
  9720. });
  9721. };
  9722. /**
  9723. * Test if the given uri is a base64 string.
  9724. * @param uri The uri to test
  9725. * @return True if the uri is a base64 string or false otherwise.
  9726. */
  9727. Tools.IsBase64 = function (uri) {
  9728. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9729. };
  9730. /**
  9731. * Decode the given base64 uri.
  9732. * @param uri The uri to decode
  9733. * @return The decoded base64 data.
  9734. */
  9735. Tools.DecodeBase64 = function (uri) {
  9736. var decodedString = atob(uri.split(",")[1]);
  9737. var bufferLength = decodedString.length;
  9738. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9739. for (var i = 0; i < bufferLength; i++) {
  9740. bufferView[i] = decodedString.charCodeAt(i);
  9741. }
  9742. return bufferView.buffer;
  9743. };
  9744. Object.defineProperty(Tools, "NoneLogLevel", {
  9745. get: function () {
  9746. return Tools._NoneLogLevel;
  9747. },
  9748. enumerable: true,
  9749. configurable: true
  9750. });
  9751. Object.defineProperty(Tools, "MessageLogLevel", {
  9752. get: function () {
  9753. return Tools._MessageLogLevel;
  9754. },
  9755. enumerable: true,
  9756. configurable: true
  9757. });
  9758. Object.defineProperty(Tools, "WarningLogLevel", {
  9759. get: function () {
  9760. return Tools._WarningLogLevel;
  9761. },
  9762. enumerable: true,
  9763. configurable: true
  9764. });
  9765. Object.defineProperty(Tools, "ErrorLogLevel", {
  9766. get: function () {
  9767. return Tools._ErrorLogLevel;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(Tools, "AllLogLevel", {
  9773. get: function () {
  9774. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9775. },
  9776. enumerable: true,
  9777. configurable: true
  9778. });
  9779. Tools._AddLogEntry = function (entry) {
  9780. Tools._LogCache = entry + Tools._LogCache;
  9781. if (Tools.OnNewCacheEntry) {
  9782. Tools.OnNewCacheEntry(entry);
  9783. }
  9784. };
  9785. Tools._FormatMessage = function (message) {
  9786. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9787. var date = new Date();
  9788. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9789. };
  9790. Tools._LogDisabled = function (message) {
  9791. // nothing to do
  9792. };
  9793. Tools._LogEnabled = function (message) {
  9794. var formattedMessage = Tools._FormatMessage(message);
  9795. console.log("BJS - " + formattedMessage);
  9796. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9797. Tools._AddLogEntry(entry);
  9798. };
  9799. Tools._WarnDisabled = function (message) {
  9800. // nothing to do
  9801. };
  9802. Tools._WarnEnabled = function (message) {
  9803. var formattedMessage = Tools._FormatMessage(message);
  9804. console.warn("BJS - " + formattedMessage);
  9805. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9806. Tools._AddLogEntry(entry);
  9807. };
  9808. Tools._ErrorDisabled = function (message) {
  9809. // nothing to do
  9810. };
  9811. Tools._ErrorEnabled = function (message) {
  9812. Tools.errorsCount++;
  9813. var formattedMessage = Tools._FormatMessage(message);
  9814. console.error("BJS - " + formattedMessage);
  9815. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9816. Tools._AddLogEntry(entry);
  9817. };
  9818. Object.defineProperty(Tools, "LogCache", {
  9819. get: function () {
  9820. return Tools._LogCache;
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Tools.ClearLogCache = function () {
  9826. Tools._LogCache = "";
  9827. Tools.errorsCount = 0;
  9828. };
  9829. Object.defineProperty(Tools, "LogLevels", {
  9830. set: function (level) {
  9831. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9832. Tools.Log = Tools._LogEnabled;
  9833. }
  9834. else {
  9835. Tools.Log = Tools._LogDisabled;
  9836. }
  9837. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9838. Tools.Warn = Tools._WarnEnabled;
  9839. }
  9840. else {
  9841. Tools.Warn = Tools._WarnDisabled;
  9842. }
  9843. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9844. Tools.Error = Tools._ErrorEnabled;
  9845. }
  9846. else {
  9847. Tools.Error = Tools._ErrorDisabled;
  9848. }
  9849. },
  9850. enumerable: true,
  9851. configurable: true
  9852. });
  9853. Tools.IsWindowObjectExist = function () {
  9854. return (typeof window) !== "undefined";
  9855. };
  9856. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9857. get: function () {
  9858. return Tools._PerformanceNoneLogLevel;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9864. get: function () {
  9865. return Tools._PerformanceUserMarkLogLevel;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9871. get: function () {
  9872. return Tools._PerformanceConsoleLogLevel;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9878. set: function (level) {
  9879. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9880. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9881. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9882. return;
  9883. }
  9884. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9885. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9886. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9887. return;
  9888. }
  9889. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9890. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9896. };
  9897. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9898. };
  9899. Tools._StartUserMark = function (counterName, condition) {
  9900. if (condition === void 0) { condition = true; }
  9901. if (!Tools._performance) {
  9902. if (!Tools.IsWindowObjectExist()) {
  9903. return;
  9904. }
  9905. Tools._performance = window.performance;
  9906. }
  9907. if (!condition || !Tools._performance.mark) {
  9908. return;
  9909. }
  9910. Tools._performance.mark(counterName + "-Begin");
  9911. };
  9912. Tools._EndUserMark = function (counterName, condition) {
  9913. if (condition === void 0) { condition = true; }
  9914. if (!condition || !Tools._performance.mark) {
  9915. return;
  9916. }
  9917. Tools._performance.mark(counterName + "-End");
  9918. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9919. };
  9920. Tools._StartPerformanceConsole = function (counterName, condition) {
  9921. if (condition === void 0) { condition = true; }
  9922. if (!condition) {
  9923. return;
  9924. }
  9925. Tools._StartUserMark(counterName, condition);
  9926. if (console.time) {
  9927. console.time(counterName);
  9928. }
  9929. };
  9930. Tools._EndPerformanceConsole = function (counterName, condition) {
  9931. if (condition === void 0) { condition = true; }
  9932. if (!condition) {
  9933. return;
  9934. }
  9935. Tools._EndUserMark(counterName, condition);
  9936. if (console.time) {
  9937. console.timeEnd(counterName);
  9938. }
  9939. };
  9940. Object.defineProperty(Tools, "Now", {
  9941. get: function () {
  9942. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9943. return window.performance.now();
  9944. }
  9945. return Date.now();
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. /**
  9951. * This method will return the name of the class used to create the instance of the given object.
  9952. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9953. * @param object the object to get the class name from
  9954. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9955. */
  9956. Tools.GetClassName = function (object, isType) {
  9957. if (isType === void 0) { isType = false; }
  9958. var name = null;
  9959. if (!isType && object.getClassName) {
  9960. name = object.getClassName();
  9961. }
  9962. else {
  9963. if (object instanceof Object) {
  9964. var classObj = isType ? object : Object.getPrototypeOf(object);
  9965. name = classObj.constructor["__bjsclassName__"];
  9966. }
  9967. if (!name) {
  9968. name = typeof object;
  9969. }
  9970. }
  9971. return name;
  9972. };
  9973. Tools.First = function (array, predicate) {
  9974. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9975. var el = array_1[_i];
  9976. if (predicate(el)) {
  9977. return el;
  9978. }
  9979. }
  9980. return null;
  9981. };
  9982. /**
  9983. * This method will return the name of the full name of the class, including its owning module (if any).
  9984. * 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).
  9985. * @param object the object to get the class name from
  9986. * @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.
  9987. */
  9988. Tools.getFullClassName = function (object, isType) {
  9989. if (isType === void 0) { isType = false; }
  9990. var className = null;
  9991. var moduleName = null;
  9992. if (!isType && object.getClassName) {
  9993. className = object.getClassName();
  9994. }
  9995. else {
  9996. if (object instanceof Object) {
  9997. var classObj = isType ? object : Object.getPrototypeOf(object);
  9998. className = classObj.constructor["__bjsclassName__"];
  9999. moduleName = classObj.constructor["__bjsmoduleName__"];
  10000. }
  10001. if (!className) {
  10002. className = typeof object;
  10003. }
  10004. }
  10005. if (!className) {
  10006. return null;
  10007. }
  10008. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10009. };
  10010. /**
  10011. * 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.
  10012. * @param array
  10013. */
  10014. Tools.arrayOrStringFeeder = function (array) {
  10015. return function (index) {
  10016. if (index >= array.length) {
  10017. return null;
  10018. }
  10019. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10020. if (val && val.getHashCode) {
  10021. val = val.getHashCode();
  10022. }
  10023. if (typeof val === "string") {
  10024. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10025. }
  10026. return val;
  10027. };
  10028. };
  10029. /**
  10030. * Compute the hashCode of a stream of number
  10031. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10032. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10033. * @return the hash code computed
  10034. */
  10035. Tools.hashCodeFromStream = function (feeder) {
  10036. // Based from here: http://stackoverflow.com/a/7616484/802124
  10037. var hash = 0;
  10038. var index = 0;
  10039. var chr = feeder(index++);
  10040. while (chr != null) {
  10041. hash = ((hash << 5) - hash) + chr;
  10042. hash |= 0; // Convert to 32bit integer
  10043. chr = feeder(index++);
  10044. }
  10045. return hash;
  10046. };
  10047. /**
  10048. * Returns a promise that resolves after the given amount of time.
  10049. * @param delay Number of milliseconds to delay
  10050. * @returns Promise that resolves after the given amount of time
  10051. */
  10052. Tools.DelayAsync = function (delay) {
  10053. return new Promise(function (resolve) {
  10054. setTimeout(function () {
  10055. resolve();
  10056. }, delay);
  10057. });
  10058. };
  10059. /**
  10060. * Gets the current gradient from an array of IValueGradient
  10061. * @param ratio defines the current ratio to get
  10062. * @param gradients defines the array of IValueGradient
  10063. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10064. */
  10065. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10066. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10067. var currentGradient = gradients[gradientIndex];
  10068. var nextGradient = gradients[gradientIndex + 1];
  10069. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10070. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10071. updateFunc(currentGradient, nextGradient, scale);
  10072. }
  10073. }
  10074. };
  10075. Tools.BaseUrl = "";
  10076. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10077. /**
  10078. * Default behaviour for cors in the application.
  10079. * It can be a string if the expected behavior is identical in the entire app.
  10080. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10081. */
  10082. Tools.CorsBehavior = "anonymous";
  10083. Tools.UseFallbackTexture = true;
  10084. /**
  10085. * Use this object to register external classes like custom textures or material
  10086. * to allow the laoders to instantiate them
  10087. */
  10088. Tools.RegisteredExternalClasses = {};
  10089. // Used in case of a texture loading problem
  10090. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAA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igD6gooor4U/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";
  10091. Tools._tmpFloatArray = new Float32Array(1);
  10092. Tools.PreprocessUrl = function (url) {
  10093. return url;
  10094. };
  10095. // Logs
  10096. Tools._NoneLogLevel = 0;
  10097. Tools._MessageLogLevel = 1;
  10098. Tools._WarningLogLevel = 2;
  10099. Tools._ErrorLogLevel = 4;
  10100. Tools._LogCache = "";
  10101. Tools.errorsCount = 0;
  10102. Tools.Log = Tools._LogEnabled;
  10103. Tools.Warn = Tools._WarnEnabled;
  10104. Tools.Error = Tools._ErrorEnabled;
  10105. // Performances
  10106. Tools._PerformanceNoneLogLevel = 0;
  10107. Tools._PerformanceUserMarkLogLevel = 1;
  10108. Tools._PerformanceConsoleLogLevel = 2;
  10109. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10110. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10111. return Tools;
  10112. }());
  10113. BABYLON.Tools = Tools;
  10114. /**
  10115. * This class is used to track a performance counter which is number based.
  10116. * The user has access to many properties which give statistics of different nature
  10117. *
  10118. * The implementer can track two kinds of Performance Counter: time and count
  10119. * 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.
  10120. * 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.
  10121. */
  10122. var PerfCounter = /** @class */ (function () {
  10123. function PerfCounter() {
  10124. this._startMonitoringTime = 0;
  10125. this._min = 0;
  10126. this._max = 0;
  10127. this._average = 0;
  10128. this._lastSecAverage = 0;
  10129. this._current = 0;
  10130. this._totalValueCount = 0;
  10131. this._totalAccumulated = 0;
  10132. this._lastSecAccumulated = 0;
  10133. this._lastSecTime = 0;
  10134. this._lastSecValueCount = 0;
  10135. }
  10136. Object.defineProperty(PerfCounter.prototype, "min", {
  10137. /**
  10138. * Returns the smallest value ever
  10139. */
  10140. get: function () {
  10141. return this._min;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(PerfCounter.prototype, "max", {
  10147. /**
  10148. * Returns the biggest value ever
  10149. */
  10150. get: function () {
  10151. return this._max;
  10152. },
  10153. enumerable: true,
  10154. configurable: true
  10155. });
  10156. Object.defineProperty(PerfCounter.prototype, "average", {
  10157. /**
  10158. * Returns the average value since the performance counter is running
  10159. */
  10160. get: function () {
  10161. return this._average;
  10162. },
  10163. enumerable: true,
  10164. configurable: true
  10165. });
  10166. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10167. /**
  10168. * Returns the average value of the last second the counter was monitored
  10169. */
  10170. get: function () {
  10171. return this._lastSecAverage;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. Object.defineProperty(PerfCounter.prototype, "current", {
  10177. /**
  10178. * Returns the current value
  10179. */
  10180. get: function () {
  10181. return this._current;
  10182. },
  10183. enumerable: true,
  10184. configurable: true
  10185. });
  10186. Object.defineProperty(PerfCounter.prototype, "total", {
  10187. get: function () {
  10188. return this._totalAccumulated;
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. Object.defineProperty(PerfCounter.prototype, "count", {
  10194. get: function () {
  10195. return this._totalValueCount;
  10196. },
  10197. enumerable: true,
  10198. configurable: true
  10199. });
  10200. /**
  10201. * Call this method to start monitoring a new frame.
  10202. * 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.
  10203. */
  10204. PerfCounter.prototype.fetchNewFrame = function () {
  10205. this._totalValueCount++;
  10206. this._current = 0;
  10207. this._lastSecValueCount++;
  10208. };
  10209. /**
  10210. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10211. * @param newCount the count value to add to the monitored count
  10212. * @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.
  10213. */
  10214. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10215. if (!PerfCounter.Enabled) {
  10216. return;
  10217. }
  10218. this._current += newCount;
  10219. if (fetchResult) {
  10220. this._fetchResult();
  10221. }
  10222. };
  10223. /**
  10224. * Start monitoring this performance counter
  10225. */
  10226. PerfCounter.prototype.beginMonitoring = function () {
  10227. if (!PerfCounter.Enabled) {
  10228. return;
  10229. }
  10230. this._startMonitoringTime = Tools.Now;
  10231. };
  10232. /**
  10233. * Compute the time lapsed since the previous beginMonitoring() call.
  10234. * @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
  10235. */
  10236. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10237. if (newFrame === void 0) { newFrame = true; }
  10238. if (!PerfCounter.Enabled) {
  10239. return;
  10240. }
  10241. if (newFrame) {
  10242. this.fetchNewFrame();
  10243. }
  10244. var currentTime = Tools.Now;
  10245. this._current = currentTime - this._startMonitoringTime;
  10246. if (newFrame) {
  10247. this._fetchResult();
  10248. }
  10249. };
  10250. PerfCounter.prototype._fetchResult = function () {
  10251. this._totalAccumulated += this._current;
  10252. this._lastSecAccumulated += this._current;
  10253. // Min/Max update
  10254. this._min = Math.min(this._min, this._current);
  10255. this._max = Math.max(this._max, this._current);
  10256. this._average = this._totalAccumulated / this._totalValueCount;
  10257. // Reset last sec?
  10258. var now = Tools.Now;
  10259. if ((now - this._lastSecTime) > 1000) {
  10260. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10261. this._lastSecTime = now;
  10262. this._lastSecAccumulated = 0;
  10263. this._lastSecValueCount = 0;
  10264. }
  10265. };
  10266. PerfCounter.Enabled = true;
  10267. return PerfCounter;
  10268. }());
  10269. BABYLON.PerfCounter = PerfCounter;
  10270. /**
  10271. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10272. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10273. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10274. * @param name The name of the class, case should be preserved
  10275. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10276. */
  10277. function className(name, module) {
  10278. return function (target) {
  10279. target["__bjsclassName__"] = name;
  10280. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10281. };
  10282. }
  10283. BABYLON.className = className;
  10284. /**
  10285. * An implementation of a loop for asynchronous functions.
  10286. */
  10287. var AsyncLoop = /** @class */ (function () {
  10288. /**
  10289. * Constroctor.
  10290. * @param iterations the number of iterations.
  10291. * @param _fn the function to run each iteration
  10292. * @param _successCallback the callback that will be called upon succesful execution
  10293. * @param offset starting offset.
  10294. */
  10295. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10296. if (offset === void 0) { offset = 0; }
  10297. this.iterations = iterations;
  10298. this._fn = _fn;
  10299. this._successCallback = _successCallback;
  10300. this.index = offset - 1;
  10301. this._done = false;
  10302. }
  10303. /**
  10304. * Execute the next iteration. Must be called after the last iteration was finished.
  10305. */
  10306. AsyncLoop.prototype.executeNext = function () {
  10307. if (!this._done) {
  10308. if (this.index + 1 < this.iterations) {
  10309. ++this.index;
  10310. this._fn(this);
  10311. }
  10312. else {
  10313. this.breakLoop();
  10314. }
  10315. }
  10316. };
  10317. /**
  10318. * Break the loop and run the success callback.
  10319. */
  10320. AsyncLoop.prototype.breakLoop = function () {
  10321. this._done = true;
  10322. this._successCallback();
  10323. };
  10324. /**
  10325. * Helper function
  10326. */
  10327. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10328. if (offset === void 0) { offset = 0; }
  10329. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10330. loop.executeNext();
  10331. return loop;
  10332. };
  10333. /**
  10334. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10335. * @param iterations total number of iterations
  10336. * @param syncedIterations number of synchronous iterations in each async iteration.
  10337. * @param fn the function to call each iteration.
  10338. * @param callback a success call back that will be called when iterating stops.
  10339. * @param breakFunction a break condition (optional)
  10340. * @param timeout timeout settings for the setTimeout function. default - 0.
  10341. * @constructor
  10342. */
  10343. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10344. if (timeout === void 0) { timeout = 0; }
  10345. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10346. if (breakFunction && breakFunction())
  10347. loop.breakLoop();
  10348. else {
  10349. setTimeout(function () {
  10350. for (var i = 0; i < syncedIterations; ++i) {
  10351. var iteration = (loop.index * syncedIterations) + i;
  10352. if (iteration >= iterations)
  10353. break;
  10354. fn(iteration);
  10355. if (breakFunction && breakFunction()) {
  10356. loop.breakLoop();
  10357. break;
  10358. }
  10359. }
  10360. loop.executeNext();
  10361. }, timeout);
  10362. }
  10363. }, callback);
  10364. };
  10365. return AsyncLoop;
  10366. }());
  10367. BABYLON.AsyncLoop = AsyncLoop;
  10368. })(BABYLON || (BABYLON = {}));
  10369. //# sourceMappingURL=babylon.tools.js.map
  10370. var BABYLON;
  10371. (function (BABYLON) {
  10372. var PromiseStates;
  10373. (function (PromiseStates) {
  10374. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10375. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10376. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10377. })(PromiseStates || (PromiseStates = {}));
  10378. var FulFillmentAgregator = /** @class */ (function () {
  10379. function FulFillmentAgregator() {
  10380. this.count = 0;
  10381. this.target = 0;
  10382. this.results = [];
  10383. }
  10384. return FulFillmentAgregator;
  10385. }());
  10386. var InternalPromise = /** @class */ (function () {
  10387. function InternalPromise(resolver) {
  10388. var _this = this;
  10389. this._state = PromiseStates.Pending;
  10390. this._children = new Array();
  10391. this._rejectWasConsumed = false;
  10392. if (!resolver) {
  10393. return;
  10394. }
  10395. try {
  10396. resolver(function (value) {
  10397. _this._resolve(value);
  10398. }, function (reason) {
  10399. _this._reject(reason);
  10400. });
  10401. }
  10402. catch (e) {
  10403. this._reject(e);
  10404. }
  10405. }
  10406. Object.defineProperty(InternalPromise.prototype, "_result", {
  10407. get: function () {
  10408. return this._resultValue;
  10409. },
  10410. set: function (value) {
  10411. this._resultValue = value;
  10412. if (this._parent && this._parent._result === undefined) {
  10413. this._parent._result = value;
  10414. }
  10415. },
  10416. enumerable: true,
  10417. configurable: true
  10418. });
  10419. InternalPromise.prototype.catch = function (onRejected) {
  10420. return this.then(undefined, onRejected);
  10421. };
  10422. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10423. var _this = this;
  10424. var newPromise = new InternalPromise();
  10425. newPromise._onFulfilled = onFulfilled;
  10426. newPromise._onRejected = onRejected;
  10427. // Composition
  10428. this._children.push(newPromise);
  10429. newPromise._parent = this;
  10430. if (this._state !== PromiseStates.Pending) {
  10431. BABYLON.Tools.SetImmediate(function () {
  10432. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10433. var returnedValue = newPromise._resolve(_this._result);
  10434. if (returnedValue !== undefined && returnedValue !== null) {
  10435. if (returnedValue._state !== undefined) {
  10436. var returnedPromise = returnedValue;
  10437. newPromise._children.push(returnedPromise);
  10438. returnedPromise._parent = newPromise;
  10439. newPromise = returnedPromise;
  10440. }
  10441. else {
  10442. newPromise._result = returnedValue;
  10443. }
  10444. }
  10445. }
  10446. else {
  10447. newPromise._reject(_this._reason);
  10448. }
  10449. });
  10450. }
  10451. return newPromise;
  10452. };
  10453. InternalPromise.prototype._moveChildren = function (children) {
  10454. var _this = this;
  10455. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10456. this._children.forEach(function (child) {
  10457. child._parent = _this;
  10458. });
  10459. if (this._state === PromiseStates.Fulfilled) {
  10460. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10461. var child = _b[_i];
  10462. child._resolve(this._result);
  10463. }
  10464. }
  10465. else if (this._state === PromiseStates.Rejected) {
  10466. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10467. var child = _d[_c];
  10468. child._reject(this._reason);
  10469. }
  10470. }
  10471. var _a;
  10472. };
  10473. InternalPromise.prototype._resolve = function (value) {
  10474. try {
  10475. this._state = PromiseStates.Fulfilled;
  10476. var returnedValue = null;
  10477. if (this._onFulfilled) {
  10478. returnedValue = this._onFulfilled(value);
  10479. }
  10480. if (returnedValue !== undefined && returnedValue !== null) {
  10481. if (returnedValue._state !== undefined) {
  10482. // Transmit children
  10483. var returnedPromise = returnedValue;
  10484. returnedPromise._parent = this;
  10485. returnedPromise._moveChildren(this._children);
  10486. value = returnedPromise._result;
  10487. }
  10488. else {
  10489. value = returnedValue;
  10490. }
  10491. }
  10492. this._result = value;
  10493. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10494. var child = _a[_i];
  10495. child._resolve(value);
  10496. }
  10497. this._children.length = 0;
  10498. delete this._onFulfilled;
  10499. delete this._onRejected;
  10500. }
  10501. catch (e) {
  10502. this._reject(e, true);
  10503. }
  10504. };
  10505. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10506. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10507. this._state = PromiseStates.Rejected;
  10508. this._reason = reason;
  10509. if (this._onRejected && !onLocalThrow) {
  10510. try {
  10511. this._onRejected(reason);
  10512. this._rejectWasConsumed = true;
  10513. }
  10514. catch (e) {
  10515. reason = e;
  10516. }
  10517. }
  10518. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10519. var child = _a[_i];
  10520. if (this._rejectWasConsumed) {
  10521. child._resolve(null);
  10522. }
  10523. else {
  10524. child._reject(reason);
  10525. }
  10526. }
  10527. this._children.length = 0;
  10528. delete this._onFulfilled;
  10529. delete this._onRejected;
  10530. };
  10531. InternalPromise.resolve = function (value) {
  10532. var newPromise = new InternalPromise();
  10533. newPromise._resolve(value);
  10534. return newPromise;
  10535. };
  10536. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10537. promise.then(function (value) {
  10538. agregator.results[index] = value;
  10539. agregator.count++;
  10540. if (agregator.count === agregator.target) {
  10541. agregator.rootPromise._resolve(agregator.results);
  10542. }
  10543. return null;
  10544. }, function (reason) {
  10545. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10546. agregator.rootPromise._reject(reason);
  10547. }
  10548. });
  10549. };
  10550. InternalPromise.all = function (promises) {
  10551. var newPromise = new InternalPromise();
  10552. var agregator = new FulFillmentAgregator();
  10553. agregator.target = promises.length;
  10554. agregator.rootPromise = newPromise;
  10555. if (promises.length) {
  10556. for (var index = 0; index < promises.length; index++) {
  10557. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10558. }
  10559. }
  10560. else {
  10561. newPromise._resolve([]);
  10562. }
  10563. return newPromise;
  10564. };
  10565. InternalPromise.race = function (promises) {
  10566. var newPromise = new InternalPromise();
  10567. if (promises.length) {
  10568. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10569. var promise = promises_1[_i];
  10570. promise.then(function (value) {
  10571. if (newPromise) {
  10572. newPromise._resolve(value);
  10573. newPromise = null;
  10574. }
  10575. return null;
  10576. }, function (reason) {
  10577. if (newPromise) {
  10578. newPromise._reject(reason);
  10579. newPromise = null;
  10580. }
  10581. });
  10582. }
  10583. }
  10584. return newPromise;
  10585. };
  10586. return InternalPromise;
  10587. }());
  10588. /**
  10589. * Helper class that provides a small promise polyfill
  10590. */
  10591. var PromisePolyfill = /** @class */ (function () {
  10592. function PromisePolyfill() {
  10593. }
  10594. /**
  10595. * Static function used to check if the polyfill is required
  10596. * If this is the case then the function will inject the polyfill to window.Promise
  10597. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10598. */
  10599. PromisePolyfill.Apply = function (force) {
  10600. if (force === void 0) { force = false; }
  10601. if (force || typeof Promise === 'undefined') {
  10602. var root = window;
  10603. root.Promise = InternalPromise;
  10604. }
  10605. };
  10606. return PromisePolyfill;
  10607. }());
  10608. BABYLON.PromisePolyfill = PromisePolyfill;
  10609. })(BABYLON || (BABYLON = {}));
  10610. //# sourceMappingURL=babylon.promise.js.map
  10611. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10612. var BABYLON;
  10613. (function (BABYLON) {
  10614. /**
  10615. * Helper class to push actions to a pool of workers.
  10616. */
  10617. var WorkerPool = /** @class */ (function () {
  10618. /**
  10619. * Constructor
  10620. * @param workers Array of workers to use for actions
  10621. */
  10622. function WorkerPool(workers) {
  10623. this._pendingActions = new Array();
  10624. this._workerInfos = workers.map(function (worker) { return ({
  10625. worker: worker,
  10626. active: false
  10627. }); });
  10628. }
  10629. /**
  10630. * Terminates all workers and clears any pending actions.
  10631. */
  10632. WorkerPool.prototype.dispose = function () {
  10633. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10634. var workerInfo = _a[_i];
  10635. workerInfo.worker.terminate();
  10636. }
  10637. delete this._workerInfos;
  10638. delete this._pendingActions;
  10639. };
  10640. /**
  10641. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10642. * pended until a worker has completed its action.
  10643. * @param action The action to perform. Call onComplete when the action is complete.
  10644. */
  10645. WorkerPool.prototype.push = function (action) {
  10646. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10647. var workerInfo = _a[_i];
  10648. if (!workerInfo.active) {
  10649. this._execute(workerInfo, action);
  10650. return;
  10651. }
  10652. }
  10653. this._pendingActions.push(action);
  10654. };
  10655. WorkerPool.prototype._execute = function (workerInfo, action) {
  10656. var _this = this;
  10657. workerInfo.active = true;
  10658. action(workerInfo.worker, function () {
  10659. workerInfo.active = false;
  10660. var nextAction = _this._pendingActions.shift();
  10661. if (nextAction) {
  10662. _this._execute(workerInfo, nextAction);
  10663. }
  10664. });
  10665. };
  10666. return WorkerPool;
  10667. }());
  10668. BABYLON.WorkerPool = WorkerPool;
  10669. })(BABYLON || (BABYLON = {}));
  10670. //# sourceMappingURL=babylon.workerPool.js.map
  10671. var BABYLON;
  10672. (function (BABYLON) {
  10673. /**
  10674. * @hidden
  10675. **/
  10676. var _AlphaState = /** @class */ (function () {
  10677. /**
  10678. * Initializes the state.
  10679. */
  10680. function _AlphaState() {
  10681. this._isAlphaBlendDirty = false;
  10682. this._isBlendFunctionParametersDirty = false;
  10683. this._isBlendEquationParametersDirty = false;
  10684. this._isBlendConstantsDirty = false;
  10685. this._alphaBlend = false;
  10686. this._blendFunctionParameters = new Array(4);
  10687. this._blendEquationParameters = new Array(2);
  10688. this._blendConstants = new Array(4);
  10689. this.reset();
  10690. }
  10691. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10692. get: function () {
  10693. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10699. get: function () {
  10700. return this._alphaBlend;
  10701. },
  10702. set: function (value) {
  10703. if (this._alphaBlend === value) {
  10704. return;
  10705. }
  10706. this._alphaBlend = value;
  10707. this._isAlphaBlendDirty = true;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10713. if (this._blendConstants[0] === r &&
  10714. this._blendConstants[1] === g &&
  10715. this._blendConstants[2] === b &&
  10716. this._blendConstants[3] === a) {
  10717. return;
  10718. }
  10719. this._blendConstants[0] = r;
  10720. this._blendConstants[1] = g;
  10721. this._blendConstants[2] = b;
  10722. this._blendConstants[3] = a;
  10723. this._isBlendConstantsDirty = true;
  10724. };
  10725. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10726. if (this._blendFunctionParameters[0] === value0 &&
  10727. this._blendFunctionParameters[1] === value1 &&
  10728. this._blendFunctionParameters[2] === value2 &&
  10729. this._blendFunctionParameters[3] === value3) {
  10730. return;
  10731. }
  10732. this._blendFunctionParameters[0] = value0;
  10733. this._blendFunctionParameters[1] = value1;
  10734. this._blendFunctionParameters[2] = value2;
  10735. this._blendFunctionParameters[3] = value3;
  10736. this._isBlendFunctionParametersDirty = true;
  10737. };
  10738. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10739. if (this._blendEquationParameters[0] === rgb &&
  10740. this._blendEquationParameters[1] === alpha) {
  10741. return;
  10742. }
  10743. this._blendEquationParameters[0] = rgb;
  10744. this._blendEquationParameters[1] = alpha;
  10745. this._isBlendEquationParametersDirty = true;
  10746. };
  10747. _AlphaState.prototype.reset = function () {
  10748. this._alphaBlend = false;
  10749. this._blendFunctionParameters[0] = null;
  10750. this._blendFunctionParameters[1] = null;
  10751. this._blendFunctionParameters[2] = null;
  10752. this._blendFunctionParameters[3] = null;
  10753. this._blendEquationParameters[0] = null;
  10754. this._blendEquationParameters[1] = null;
  10755. this._blendConstants[0] = null;
  10756. this._blendConstants[1] = null;
  10757. this._blendConstants[2] = null;
  10758. this._blendConstants[3] = null;
  10759. this._isAlphaBlendDirty = true;
  10760. this._isBlendFunctionParametersDirty = false;
  10761. this._isBlendEquationParametersDirty = false;
  10762. this._isBlendConstantsDirty = false;
  10763. };
  10764. _AlphaState.prototype.apply = function (gl) {
  10765. if (!this.isDirty) {
  10766. return;
  10767. }
  10768. // Alpha blend
  10769. if (this._isAlphaBlendDirty) {
  10770. if (this._alphaBlend) {
  10771. gl.enable(gl.BLEND);
  10772. }
  10773. else {
  10774. gl.disable(gl.BLEND);
  10775. }
  10776. this._isAlphaBlendDirty = false;
  10777. }
  10778. // Alpha function
  10779. if (this._isBlendFunctionParametersDirty) {
  10780. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10781. this._isBlendFunctionParametersDirty = false;
  10782. }
  10783. // Alpha equation
  10784. if (this._isBlendEquationParametersDirty) {
  10785. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10786. this._isBlendEquationParametersDirty = false;
  10787. }
  10788. // Constants
  10789. if (this._isBlendConstantsDirty) {
  10790. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10791. this._isBlendConstantsDirty = false;
  10792. }
  10793. };
  10794. return _AlphaState;
  10795. }());
  10796. BABYLON._AlphaState = _AlphaState;
  10797. })(BABYLON || (BABYLON = {}));
  10798. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10799. var BABYLON;
  10800. (function (BABYLON) {
  10801. /**
  10802. * @hidden
  10803. **/
  10804. var _DepthCullingState = /** @class */ (function () {
  10805. /**
  10806. * Initializes the state.
  10807. */
  10808. function _DepthCullingState() {
  10809. this._isDepthTestDirty = false;
  10810. this._isDepthMaskDirty = false;
  10811. this._isDepthFuncDirty = false;
  10812. this._isCullFaceDirty = false;
  10813. this._isCullDirty = false;
  10814. this._isZOffsetDirty = false;
  10815. this._isFrontFaceDirty = false;
  10816. this.reset();
  10817. }
  10818. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10819. get: function () {
  10820. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10821. },
  10822. enumerable: true,
  10823. configurable: true
  10824. });
  10825. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10826. get: function () {
  10827. return this._zOffset;
  10828. },
  10829. set: function (value) {
  10830. if (this._zOffset === value) {
  10831. return;
  10832. }
  10833. this._zOffset = value;
  10834. this._isZOffsetDirty = true;
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10840. get: function () {
  10841. return this._cullFace;
  10842. },
  10843. set: function (value) {
  10844. if (this._cullFace === value) {
  10845. return;
  10846. }
  10847. this._cullFace = value;
  10848. this._isCullFaceDirty = true;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10854. get: function () {
  10855. return this._cull;
  10856. },
  10857. set: function (value) {
  10858. if (this._cull === value) {
  10859. return;
  10860. }
  10861. this._cull = value;
  10862. this._isCullDirty = true;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10868. get: function () {
  10869. return this._depthFunc;
  10870. },
  10871. set: function (value) {
  10872. if (this._depthFunc === value) {
  10873. return;
  10874. }
  10875. this._depthFunc = value;
  10876. this._isDepthFuncDirty = true;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10882. get: function () {
  10883. return this._depthMask;
  10884. },
  10885. set: function (value) {
  10886. if (this._depthMask === value) {
  10887. return;
  10888. }
  10889. this._depthMask = value;
  10890. this._isDepthMaskDirty = true;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10896. get: function () {
  10897. return this._depthTest;
  10898. },
  10899. set: function (value) {
  10900. if (this._depthTest === value) {
  10901. return;
  10902. }
  10903. this._depthTest = value;
  10904. this._isDepthTestDirty = true;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10910. get: function () {
  10911. return this._frontFace;
  10912. },
  10913. set: function (value) {
  10914. if (this._frontFace === value) {
  10915. return;
  10916. }
  10917. this._frontFace = value;
  10918. this._isFrontFaceDirty = true;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. _DepthCullingState.prototype.reset = function () {
  10924. this._depthMask = true;
  10925. this._depthTest = true;
  10926. this._depthFunc = null;
  10927. this._cullFace = null;
  10928. this._cull = null;
  10929. this._zOffset = 0;
  10930. this._frontFace = null;
  10931. this._isDepthTestDirty = true;
  10932. this._isDepthMaskDirty = true;
  10933. this._isDepthFuncDirty = false;
  10934. this._isCullFaceDirty = false;
  10935. this._isCullDirty = false;
  10936. this._isZOffsetDirty = false;
  10937. this._isFrontFaceDirty = false;
  10938. };
  10939. _DepthCullingState.prototype.apply = function (gl) {
  10940. if (!this.isDirty) {
  10941. return;
  10942. }
  10943. // Cull
  10944. if (this._isCullDirty) {
  10945. if (this.cull) {
  10946. gl.enable(gl.CULL_FACE);
  10947. }
  10948. else {
  10949. gl.disable(gl.CULL_FACE);
  10950. }
  10951. this._isCullDirty = false;
  10952. }
  10953. // Cull face
  10954. if (this._isCullFaceDirty) {
  10955. gl.cullFace(this.cullFace);
  10956. this._isCullFaceDirty = false;
  10957. }
  10958. // Depth mask
  10959. if (this._isDepthMaskDirty) {
  10960. gl.depthMask(this.depthMask);
  10961. this._isDepthMaskDirty = false;
  10962. }
  10963. // Depth test
  10964. if (this._isDepthTestDirty) {
  10965. if (this.depthTest) {
  10966. gl.enable(gl.DEPTH_TEST);
  10967. }
  10968. else {
  10969. gl.disable(gl.DEPTH_TEST);
  10970. }
  10971. this._isDepthTestDirty = false;
  10972. }
  10973. // Depth func
  10974. if (this._isDepthFuncDirty) {
  10975. gl.depthFunc(this.depthFunc);
  10976. this._isDepthFuncDirty = false;
  10977. }
  10978. // zOffset
  10979. if (this._isZOffsetDirty) {
  10980. if (this.zOffset) {
  10981. gl.enable(gl.POLYGON_OFFSET_FILL);
  10982. gl.polygonOffset(this.zOffset, 0);
  10983. }
  10984. else {
  10985. gl.disable(gl.POLYGON_OFFSET_FILL);
  10986. }
  10987. this._isZOffsetDirty = false;
  10988. }
  10989. // Front face
  10990. if (this._isFrontFaceDirty) {
  10991. gl.frontFace(this.frontFace);
  10992. this._isFrontFaceDirty = false;
  10993. }
  10994. };
  10995. return _DepthCullingState;
  10996. }());
  10997. BABYLON._DepthCullingState = _DepthCullingState;
  10998. })(BABYLON || (BABYLON = {}));
  10999. //# sourceMappingURL=babylon.depthCullingState.js.map
  11000. var BABYLON;
  11001. (function (BABYLON) {
  11002. /**
  11003. * @hidden
  11004. **/
  11005. var _StencilState = /** @class */ (function () {
  11006. function _StencilState() {
  11007. this._isStencilTestDirty = false;
  11008. this._isStencilMaskDirty = false;
  11009. this._isStencilFuncDirty = false;
  11010. this._isStencilOpDirty = false;
  11011. this.reset();
  11012. }
  11013. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11014. get: function () {
  11015. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11021. get: function () {
  11022. return this._stencilFunc;
  11023. },
  11024. set: function (value) {
  11025. if (this._stencilFunc === value) {
  11026. return;
  11027. }
  11028. this._stencilFunc = value;
  11029. this._isStencilFuncDirty = true;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11035. get: function () {
  11036. return this._stencilFuncRef;
  11037. },
  11038. set: function (value) {
  11039. if (this._stencilFuncRef === value) {
  11040. return;
  11041. }
  11042. this._stencilFuncRef = value;
  11043. this._isStencilFuncDirty = true;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11049. get: function () {
  11050. return this._stencilFuncMask;
  11051. },
  11052. set: function (value) {
  11053. if (this._stencilFuncMask === value) {
  11054. return;
  11055. }
  11056. this._stencilFuncMask = value;
  11057. this._isStencilFuncDirty = true;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11063. get: function () {
  11064. return this._stencilOpStencilFail;
  11065. },
  11066. set: function (value) {
  11067. if (this._stencilOpStencilFail === value) {
  11068. return;
  11069. }
  11070. this._stencilOpStencilFail = value;
  11071. this._isStencilOpDirty = true;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11077. get: function () {
  11078. return this._stencilOpDepthFail;
  11079. },
  11080. set: function (value) {
  11081. if (this._stencilOpDepthFail === value) {
  11082. return;
  11083. }
  11084. this._stencilOpDepthFail = value;
  11085. this._isStencilOpDirty = true;
  11086. },
  11087. enumerable: true,
  11088. configurable: true
  11089. });
  11090. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11091. get: function () {
  11092. return this._stencilOpStencilDepthPass;
  11093. },
  11094. set: function (value) {
  11095. if (this._stencilOpStencilDepthPass === value) {
  11096. return;
  11097. }
  11098. this._stencilOpStencilDepthPass = value;
  11099. this._isStencilOpDirty = true;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11105. get: function () {
  11106. return this._stencilMask;
  11107. },
  11108. set: function (value) {
  11109. if (this._stencilMask === value) {
  11110. return;
  11111. }
  11112. this._stencilMask = value;
  11113. this._isStencilMaskDirty = true;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11119. get: function () {
  11120. return this._stencilTest;
  11121. },
  11122. set: function (value) {
  11123. if (this._stencilTest === value) {
  11124. return;
  11125. }
  11126. this._stencilTest = value;
  11127. this._isStencilTestDirty = true;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. _StencilState.prototype.reset = function () {
  11133. this._stencilTest = false;
  11134. this._stencilMask = 0xFF;
  11135. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11136. this._stencilFuncRef = 1;
  11137. this._stencilFuncMask = 0xFF;
  11138. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11139. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11140. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11141. this._isStencilTestDirty = true;
  11142. this._isStencilMaskDirty = true;
  11143. this._isStencilFuncDirty = true;
  11144. this._isStencilOpDirty = true;
  11145. };
  11146. _StencilState.prototype.apply = function (gl) {
  11147. if (!this.isDirty) {
  11148. return;
  11149. }
  11150. // Stencil test
  11151. if (this._isStencilTestDirty) {
  11152. if (this.stencilTest) {
  11153. gl.enable(gl.STENCIL_TEST);
  11154. }
  11155. else {
  11156. gl.disable(gl.STENCIL_TEST);
  11157. }
  11158. this._isStencilTestDirty = false;
  11159. }
  11160. // Stencil mask
  11161. if (this._isStencilMaskDirty) {
  11162. gl.stencilMask(this.stencilMask);
  11163. this._isStencilMaskDirty = false;
  11164. }
  11165. // Stencil func
  11166. if (this._isStencilFuncDirty) {
  11167. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11168. this._isStencilFuncDirty = false;
  11169. }
  11170. // Stencil op
  11171. if (this._isStencilOpDirty) {
  11172. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11173. this._isStencilOpDirty = false;
  11174. }
  11175. };
  11176. return _StencilState;
  11177. }());
  11178. BABYLON._StencilState = _StencilState;
  11179. })(BABYLON || (BABYLON = {}));
  11180. //# sourceMappingURL=babylon.stencilState.js.map
  11181. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11182. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11183. s = arguments[i];
  11184. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11185. t[p] = s[p];
  11186. }
  11187. return t;
  11188. };
  11189. var BABYLON;
  11190. (function (BABYLON) {
  11191. /**
  11192. * Keeps track of all the buffer info used in engine.
  11193. */
  11194. var BufferPointer = /** @class */ (function () {
  11195. function BufferPointer() {
  11196. }
  11197. return BufferPointer;
  11198. }());
  11199. /**
  11200. * Interface for attribute information associated with buffer instanciation
  11201. */
  11202. var InstancingAttributeInfo = /** @class */ (function () {
  11203. function InstancingAttributeInfo() {
  11204. }
  11205. return InstancingAttributeInfo;
  11206. }());
  11207. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11208. /**
  11209. * Define options used to create a render target texture
  11210. */
  11211. var RenderTargetCreationOptions = /** @class */ (function () {
  11212. function RenderTargetCreationOptions() {
  11213. }
  11214. return RenderTargetCreationOptions;
  11215. }());
  11216. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11217. /**
  11218. * Define options used to create a depth texture
  11219. */
  11220. var DepthTextureCreationOptions = /** @class */ (function () {
  11221. function DepthTextureCreationOptions() {
  11222. }
  11223. return DepthTextureCreationOptions;
  11224. }());
  11225. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11226. /**
  11227. * Class used to describe the capabilities of the engine relatively to the current browser
  11228. */
  11229. var EngineCapabilities = /** @class */ (function () {
  11230. function EngineCapabilities() {
  11231. }
  11232. return EngineCapabilities;
  11233. }());
  11234. BABYLON.EngineCapabilities = EngineCapabilities;
  11235. /**
  11236. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11237. */
  11238. var Engine = /** @class */ (function () {
  11239. /**
  11240. * Creates a new engine
  11241. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11242. * @param antialias defines enable antialiasing (default: false)
  11243. * @param options defines further options to be sent to the getContext() function
  11244. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11245. */
  11246. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11247. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11248. var _this = this;
  11249. // Public members
  11250. /**
  11251. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11252. */
  11253. this.forcePOTTextures = false;
  11254. /**
  11255. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11256. */
  11257. this.isFullscreen = false;
  11258. /**
  11259. * Gets a boolean indicating if the pointer is currently locked
  11260. */
  11261. this.isPointerLock = false;
  11262. /**
  11263. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11264. */
  11265. this.cullBackFaces = true;
  11266. /**
  11267. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11268. */
  11269. this.renderEvenInBackground = true;
  11270. /**
  11271. * Gets or sets a boolean indicating that cache can be kept between frames
  11272. */
  11273. this.preventCacheWipeBetweenFrames = false;
  11274. /**
  11275. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11276. **/
  11277. this.enableOfflineSupport = false;
  11278. /**
  11279. * 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)
  11280. **/
  11281. this.disableManifestCheck = false;
  11282. /**
  11283. * Gets the list of created scenes
  11284. */
  11285. this.scenes = new Array();
  11286. /**
  11287. * Gets the list of created postprocesses
  11288. */
  11289. this.postProcesses = new Array();
  11290. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11291. this.validateShaderPrograms = false;
  11292. // Observables
  11293. /**
  11294. * Observable event triggered each time the rendering canvas is resized
  11295. */
  11296. this.onResizeObservable = new BABYLON.Observable();
  11297. /**
  11298. * Observable event triggered each time the canvas loses focus
  11299. */
  11300. this.onCanvasBlurObservable = new BABYLON.Observable();
  11301. /**
  11302. * Observable event triggered each time the canvas gains focus
  11303. */
  11304. this.onCanvasFocusObservable = new BABYLON.Observable();
  11305. /**
  11306. * Observable event triggered each time the canvas receives pointerout event
  11307. */
  11308. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11309. /**
  11310. * Observable event triggered before each texture is initialized
  11311. */
  11312. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11313. //WebVR
  11314. this._vrDisplay = undefined;
  11315. this._vrSupported = false;
  11316. this._vrExclusivePointerMode = false;
  11317. // Uniform buffers list
  11318. /**
  11319. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11320. */
  11321. this.disableUniformBuffers = false;
  11322. /** @hidden */
  11323. this._uniformBuffers = new Array();
  11324. // Observables
  11325. /**
  11326. * Observable raised when the engine begins a new frame
  11327. */
  11328. this.onBeginFrameObservable = new BABYLON.Observable();
  11329. /**
  11330. * Observable raised when the engine ends the current frame
  11331. */
  11332. this.onEndFrameObservable = new BABYLON.Observable();
  11333. /**
  11334. * Observable raised when the engine is about to compile a shader
  11335. */
  11336. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11337. /**
  11338. * Observable raised when the engine has jsut compiled a shader
  11339. */
  11340. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11341. this._windowIsBackground = false;
  11342. this._webGLVersion = 1.0;
  11343. /** @hidden */
  11344. this._badOS = false;
  11345. /** @hidden */
  11346. this._badDesktopOS = false;
  11347. /**
  11348. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11349. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11350. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11351. */
  11352. this.disableTextureBindingOptimization = false;
  11353. /**
  11354. * Observable signaled when VR display mode changes
  11355. */
  11356. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11357. /**
  11358. * Observable signaled when VR request present is complete
  11359. */
  11360. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11361. /**
  11362. * Observable signaled when VR request present starts
  11363. */
  11364. this.onVRRequestPresentStart = new BABYLON.Observable();
  11365. this._colorWrite = true;
  11366. /** @hidden */
  11367. this._drawCalls = new BABYLON.PerfCounter();
  11368. /** @hidden */
  11369. this._textureCollisions = new BABYLON.PerfCounter();
  11370. this._renderingQueueLaunched = false;
  11371. this._activeRenderLoops = new Array();
  11372. // Deterministic lockstepMaxSteps
  11373. this._deterministicLockstep = false;
  11374. this._lockstepMaxSteps = 4;
  11375. // Lost context
  11376. /**
  11377. * Observable signaled when a context lost event is raised
  11378. */
  11379. this.onContextLostObservable = new BABYLON.Observable();
  11380. /**
  11381. * Observable signaled when a context restored event is raised
  11382. */
  11383. this.onContextRestoredObservable = new BABYLON.Observable();
  11384. this._contextWasLost = false;
  11385. this._doNotHandleContextLost = false;
  11386. // FPS
  11387. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11388. this._fps = 60;
  11389. this._deltaTime = 0;
  11390. /**
  11391. * Turn this value on if you want to pause FPS computation when in background
  11392. */
  11393. this.disablePerformanceMonitorInBackground = false;
  11394. // States
  11395. /** @hidden */
  11396. this._depthCullingState = new BABYLON._DepthCullingState();
  11397. /** @hidden */
  11398. this._stencilState = new BABYLON._StencilState();
  11399. /** @hidden */
  11400. this._alphaState = new BABYLON._AlphaState();
  11401. /** @hidden */
  11402. this._alphaMode = Engine.ALPHA_DISABLE;
  11403. // Cache
  11404. this._internalTexturesCache = new Array();
  11405. /** @hidden */
  11406. this._activeChannel = 0;
  11407. this._currentTextureChannel = -1;
  11408. /** @hidden */
  11409. this._boundTexturesCache = {};
  11410. this._compiledEffects = {};
  11411. this._vertexAttribArraysEnabled = [];
  11412. this._uintIndicesCurrentlySet = false;
  11413. this._currentBoundBuffer = new Array();
  11414. /** @hidden */
  11415. this._currentFramebuffer = null;
  11416. this._currentBufferPointers = new Array();
  11417. this._currentInstanceLocations = new Array();
  11418. this._currentInstanceBuffers = new Array();
  11419. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11420. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11421. this._vaoRecordInProgress = false;
  11422. this._mustWipeVertexAttributes = false;
  11423. this._nextFreeTextureSlots = new Array();
  11424. this._maxSimultaneousTextures = 0;
  11425. this._activeRequests = new Array();
  11426. // Hardware supported Compressed Textures
  11427. this._texturesSupported = new Array();
  11428. /**
  11429. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11430. */
  11431. this.premultipliedAlpha = true;
  11432. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11433. this._onVRFullScreenTriggered = function () {
  11434. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11435. //get the old size before we change
  11436. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11437. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11438. //get the width and height, change the render size
  11439. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11440. _this.setHardwareScalingLevel(1);
  11441. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11442. }
  11443. else {
  11444. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11445. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11446. }
  11447. };
  11448. this._unpackFlipYCached = null;
  11449. this._boundUniforms = {};
  11450. // Register promises
  11451. BABYLON.PromisePolyfill.Apply();
  11452. var canvas = null;
  11453. Engine.Instances.push(this);
  11454. if (!canvasOrContext) {
  11455. return;
  11456. }
  11457. options = options || {};
  11458. if (canvasOrContext.getContext) {
  11459. canvas = canvasOrContext;
  11460. this._renderingCanvas = canvas;
  11461. if (antialias != null) {
  11462. options.antialias = antialias;
  11463. }
  11464. if (options.deterministicLockstep === undefined) {
  11465. options.deterministicLockstep = false;
  11466. }
  11467. if (options.lockstepMaxSteps === undefined) {
  11468. options.lockstepMaxSteps = 4;
  11469. }
  11470. if (options.preserveDrawingBuffer === undefined) {
  11471. options.preserveDrawingBuffer = false;
  11472. }
  11473. if (options.audioEngine === undefined) {
  11474. options.audioEngine = true;
  11475. }
  11476. if (options.stencil === undefined) {
  11477. options.stencil = true;
  11478. }
  11479. if (options.premultipliedAlpha === false) {
  11480. this.premultipliedAlpha = false;
  11481. }
  11482. this._deterministicLockstep = options.deterministicLockstep;
  11483. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11484. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11485. // Exceptions
  11486. if (navigator && navigator.userAgent) {
  11487. var ua = navigator.userAgent;
  11488. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11489. var exception = _a[_i];
  11490. var key = exception.key;
  11491. var targets = exception.targets;
  11492. if (ua.indexOf(key) > -1) {
  11493. if (exception.capture && exception.captureConstraint) {
  11494. var capture = exception.capture;
  11495. var constraint = exception.captureConstraint;
  11496. var regex = new RegExp(capture);
  11497. var matches = regex.exec(ua);
  11498. if (matches && matches.length > 0) {
  11499. var capturedValue = parseInt(matches[matches.length - 1]);
  11500. if (capturedValue >= constraint) {
  11501. continue;
  11502. }
  11503. }
  11504. }
  11505. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11506. var target = targets_1[_b];
  11507. switch (target) {
  11508. case "uniformBuffer":
  11509. this.disableUniformBuffers = true;
  11510. break;
  11511. case "textureBindingOptimization":
  11512. this.disableTextureBindingOptimization = true;
  11513. break;
  11514. }
  11515. }
  11516. }
  11517. }
  11518. }
  11519. // GL
  11520. if (!options.disableWebGL2Support) {
  11521. try {
  11522. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11523. if (this._gl) {
  11524. this._webGLVersion = 2.0;
  11525. }
  11526. }
  11527. catch (e) {
  11528. // Do nothing
  11529. }
  11530. }
  11531. if (!this._gl) {
  11532. if (!canvas) {
  11533. throw new Error("The provided canvas is null or undefined.");
  11534. }
  11535. try {
  11536. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11537. }
  11538. catch (e) {
  11539. throw new Error("WebGL not supported");
  11540. }
  11541. }
  11542. if (!this._gl) {
  11543. throw new Error("WebGL not supported");
  11544. }
  11545. this._onCanvasFocus = function () {
  11546. _this.onCanvasFocusObservable.notifyObservers(_this);
  11547. };
  11548. this._onCanvasBlur = function () {
  11549. _this.onCanvasBlurObservable.notifyObservers(_this);
  11550. };
  11551. canvas.addEventListener("focus", this._onCanvasFocus);
  11552. canvas.addEventListener("blur", this._onCanvasBlur);
  11553. this._onBlur = function () {
  11554. if (_this.disablePerformanceMonitorInBackground) {
  11555. _this._performanceMonitor.disable();
  11556. }
  11557. _this._windowIsBackground = true;
  11558. };
  11559. this._onFocus = function () {
  11560. if (_this.disablePerformanceMonitorInBackground) {
  11561. _this._performanceMonitor.enable();
  11562. }
  11563. _this._windowIsBackground = false;
  11564. };
  11565. this._onCanvasPointerOut = function (ev) {
  11566. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11567. };
  11568. window.addEventListener("blur", this._onBlur);
  11569. window.addEventListener("focus", this._onFocus);
  11570. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11571. // Context lost
  11572. if (!this._doNotHandleContextLost) {
  11573. this._onContextLost = function (evt) {
  11574. evt.preventDefault();
  11575. _this._contextWasLost = true;
  11576. BABYLON.Tools.Warn("WebGL context lost.");
  11577. _this.onContextLostObservable.notifyObservers(_this);
  11578. };
  11579. this._onContextRestored = function (evt) {
  11580. // Adding a timeout to avoid race condition at browser level
  11581. setTimeout(function () {
  11582. // Rebuild gl context
  11583. _this._initGLContext();
  11584. // Rebuild effects
  11585. _this._rebuildEffects();
  11586. // Rebuild textures
  11587. _this._rebuildInternalTextures();
  11588. // Rebuild buffers
  11589. _this._rebuildBuffers();
  11590. // Cache
  11591. _this.wipeCaches(true);
  11592. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11593. _this.onContextRestoredObservable.notifyObservers(_this);
  11594. _this._contextWasLost = false;
  11595. }, 0);
  11596. };
  11597. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11598. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11599. }
  11600. }
  11601. else {
  11602. this._gl = canvasOrContext;
  11603. this._renderingCanvas = this._gl.canvas;
  11604. if (this._gl.renderbufferStorageMultisample) {
  11605. this._webGLVersion = 2.0;
  11606. }
  11607. options.stencil = this._gl.getContextAttributes().stencil;
  11608. }
  11609. // Viewport
  11610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11612. this.resize();
  11613. this._isStencilEnable = options.stencil ? true : false;
  11614. this._initGLContext();
  11615. if (canvas) {
  11616. // Fullscreen
  11617. this._onFullscreenChange = function () {
  11618. if (document.fullscreen !== undefined) {
  11619. _this.isFullscreen = document.fullscreen;
  11620. }
  11621. else if (document.mozFullScreen !== undefined) {
  11622. _this.isFullscreen = document.mozFullScreen;
  11623. }
  11624. else if (document.webkitIsFullScreen !== undefined) {
  11625. _this.isFullscreen = document.webkitIsFullScreen;
  11626. }
  11627. else if (document.msIsFullScreen !== undefined) {
  11628. _this.isFullscreen = document.msIsFullScreen;
  11629. }
  11630. // Pointer lock
  11631. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11632. canvas.requestPointerLock = canvas.requestPointerLock ||
  11633. canvas.msRequestPointerLock ||
  11634. canvas.mozRequestPointerLock ||
  11635. canvas.webkitRequestPointerLock;
  11636. if (canvas.requestPointerLock) {
  11637. canvas.requestPointerLock();
  11638. }
  11639. }
  11640. };
  11641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11645. // Pointer lock
  11646. this._onPointerLockChange = function () {
  11647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11648. document.webkitPointerLockElement === canvas ||
  11649. document.msPointerLockElement === canvas ||
  11650. document.pointerLockElement === canvas);
  11651. };
  11652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11656. this._onVRDisplayPointerRestricted = function () {
  11657. if (canvas) {
  11658. canvas.requestPointerLock();
  11659. }
  11660. };
  11661. this._onVRDisplayPointerUnrestricted = function () {
  11662. document.exitPointerLock();
  11663. };
  11664. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11665. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11666. }
  11667. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11668. Engine.audioEngine = new BABYLON.AudioEngine();
  11669. }
  11670. // Prepare buffer pointers
  11671. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11672. this._currentBufferPointers[i] = new BufferPointer();
  11673. }
  11674. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11675. // Load WebVR Devices
  11676. if (options.autoEnableWebVR) {
  11677. this.initWebVR();
  11678. }
  11679. // Detect if we are running on a faulty buggy OS.
  11680. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11681. // Detect if we are running on a faulty buggy desktop OS.
  11682. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11683. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11684. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11685. }
  11686. Object.defineProperty(Engine, "LastCreatedEngine", {
  11687. /**
  11688. * Gets the latest created engine
  11689. */
  11690. get: function () {
  11691. if (Engine.Instances.length === 0) {
  11692. return null;
  11693. }
  11694. return Engine.Instances[Engine.Instances.length - 1];
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "LastCreatedScene", {
  11700. /**
  11701. * Gets the latest created scene
  11702. */
  11703. get: function () {
  11704. var lastCreatedEngine = Engine.LastCreatedEngine;
  11705. if (!lastCreatedEngine) {
  11706. return null;
  11707. }
  11708. if (lastCreatedEngine.scenes.length === 0) {
  11709. return null;
  11710. }
  11711. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. /**
  11717. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11718. * @param flag defines which part of the materials must be marked as dirty
  11719. * @param predicate defines a predicate used to filter which materials should be affected
  11720. */
  11721. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11722. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11723. var engine = Engine.Instances[engineIndex];
  11724. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11725. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11726. }
  11727. }
  11728. };
  11729. Object.defineProperty(Engine, "Version", {
  11730. /**
  11731. * Returns the current version of the framework
  11732. */
  11733. get: function () {
  11734. return "3.3.0-alpha.12";
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11740. /**
  11741. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11742. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11743. */
  11744. get: function () {
  11745. return this._vrExclusivePointerMode;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11751. /**
  11752. * Gets a boolean indicating that the engine supports uniform buffers
  11753. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11754. */
  11755. get: function () {
  11756. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11762. /**
  11763. * Gets a boolean indicating that only power of 2 textures are supported
  11764. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11765. */
  11766. get: function () {
  11767. return this._webGLVersion < 2 || this.forcePOTTextures;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11773. /**
  11774. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11775. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11776. */
  11777. get: function () {
  11778. return this._doNotHandleContextLost;
  11779. },
  11780. set: function (value) {
  11781. this._doNotHandleContextLost = value;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11787. /**
  11788. * Gets the performance monitor attached to this engine
  11789. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11790. */
  11791. get: function () {
  11792. return this._performanceMonitor;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11798. /**
  11799. * Gets the list of texture formats supported
  11800. */
  11801. get: function () {
  11802. return this._texturesSupported;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11808. /**
  11809. * Gets the list of texture formats in use
  11810. */
  11811. get: function () {
  11812. return this._textureFormatInUse;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine.prototype, "currentViewport", {
  11818. /**
  11819. * Gets the current viewport
  11820. */
  11821. get: function () {
  11822. return this._cachedViewport;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11828. /**
  11829. * Gets the default empty texture
  11830. */
  11831. get: function () {
  11832. if (!this._emptyTexture) {
  11833. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11834. }
  11835. return this._emptyTexture;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11841. /**
  11842. * Gets the default empty 3D texture
  11843. */
  11844. get: function () {
  11845. if (!this._emptyTexture3D) {
  11846. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11847. }
  11848. return this._emptyTexture3D;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11854. /**
  11855. * Gets the default empty cube texture
  11856. */
  11857. get: function () {
  11858. if (!this._emptyCubeTexture) {
  11859. var faceData = new Uint8Array(4);
  11860. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11861. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11862. }
  11863. return this._emptyCubeTexture;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Engine.prototype._rebuildInternalTextures = function () {
  11869. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11870. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11871. var internalTexture = currentState_1[_i];
  11872. internalTexture._rebuild();
  11873. }
  11874. };
  11875. Engine.prototype._rebuildEffects = function () {
  11876. for (var key in this._compiledEffects) {
  11877. var effect = this._compiledEffects[key];
  11878. effect._prepareEffect();
  11879. }
  11880. BABYLON.Effect.ResetCache();
  11881. };
  11882. Engine.prototype._rebuildBuffers = function () {
  11883. // Index / Vertex
  11884. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11885. var scene = _a[_i];
  11886. scene.resetCachedMaterial();
  11887. scene._rebuildGeometries();
  11888. scene._rebuildTextures();
  11889. }
  11890. // Uniforms
  11891. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11892. var uniformBuffer = _c[_b];
  11893. uniformBuffer._rebuild();
  11894. }
  11895. };
  11896. Engine.prototype._initGLContext = function () {
  11897. // Caps
  11898. this._caps = new EngineCapabilities();
  11899. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11900. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11901. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11902. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11903. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11904. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11905. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11906. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11907. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11908. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11909. // Infos
  11910. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11911. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11912. if (rendererInfo != null) {
  11913. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11914. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11915. }
  11916. if (!this._glVendor) {
  11917. this._glVendor = "Unknown vendor";
  11918. }
  11919. if (!this._glRenderer) {
  11920. this._glRenderer = "Unknown renderer";
  11921. }
  11922. // Constants
  11923. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11924. if (this._gl.RGBA16F !== 0x881A) {
  11925. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11926. }
  11927. if (this._gl.RGBA32F !== 0x8814) {
  11928. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11929. }
  11930. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11931. this._gl.DEPTH24_STENCIL8 = 35056;
  11932. }
  11933. // Extensions
  11934. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11935. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11936. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11937. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11938. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11939. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11940. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11941. 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');
  11942. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11943. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11944. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11945. this._caps.highPrecisionShaderSupported = true;
  11946. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11947. if (this._caps.timerQuery) {
  11948. if (this._webGLVersion === 1) {
  11949. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11950. }
  11951. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11952. }
  11953. // Checks if some of the format renders first to allow the use of webgl inspector.
  11954. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11955. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11956. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11957. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11958. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11959. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11960. if (this._webGLVersion > 1) {
  11961. this._gl.HALF_FLOAT_OES = 0x140B;
  11962. }
  11963. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11964. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11965. // Draw buffers
  11966. if (this._webGLVersion > 1) {
  11967. this._caps.drawBuffersExtension = true;
  11968. }
  11969. else {
  11970. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11971. if (drawBuffersExtension !== null) {
  11972. this._caps.drawBuffersExtension = true;
  11973. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11974. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11975. for (var i = 0; i < 16; i++) {
  11976. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11977. }
  11978. }
  11979. else {
  11980. this._caps.drawBuffersExtension = false;
  11981. }
  11982. }
  11983. // Depth Texture
  11984. if (this._webGLVersion > 1) {
  11985. this._caps.depthTextureExtension = true;
  11986. }
  11987. else {
  11988. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11989. if (depthTextureExtension != null) {
  11990. this._caps.depthTextureExtension = true;
  11991. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11992. }
  11993. }
  11994. // Vertex array object
  11995. if (this._webGLVersion > 1) {
  11996. this._caps.vertexArrayObject = true;
  11997. }
  11998. else {
  11999. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12000. if (vertexArrayObjectExtension != null) {
  12001. this._caps.vertexArrayObject = true;
  12002. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12003. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12004. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12005. }
  12006. else {
  12007. this._caps.vertexArrayObject = false;
  12008. }
  12009. }
  12010. // Instances count
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.instancedArrays = true;
  12013. }
  12014. else {
  12015. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12016. if (instanceExtension != null) {
  12017. this._caps.instancedArrays = true;
  12018. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12019. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12020. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12021. }
  12022. else {
  12023. this._caps.instancedArrays = false;
  12024. }
  12025. }
  12026. // Intelligently add supported compressed formats in order to check for.
  12027. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12028. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12029. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12030. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12031. if (this._caps.astc)
  12032. this.texturesSupported.push('-astc.ktx');
  12033. if (this._caps.s3tc)
  12034. this.texturesSupported.push('-dxt.ktx');
  12035. if (this._caps.pvrtc)
  12036. this.texturesSupported.push('-pvrtc.ktx');
  12037. if (this._caps.etc2)
  12038. this.texturesSupported.push('-etc2.ktx');
  12039. if (this._caps.etc1)
  12040. this.texturesSupported.push('-etc1.ktx');
  12041. if (this._gl.getShaderPrecisionFormat) {
  12042. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12043. if (highp) {
  12044. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12045. }
  12046. }
  12047. // Depth buffer
  12048. this.setDepthBuffer(true);
  12049. this.setDepthFunctionToLessOrEqual();
  12050. this.setDepthWrite(true);
  12051. // Texture maps
  12052. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12053. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12054. this._nextFreeTextureSlots.push(slot);
  12055. }
  12056. };
  12057. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12058. /**
  12059. * Gets version of the current webGL context
  12060. */
  12061. get: function () {
  12062. return this._webGLVersion;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12068. /**
  12069. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12070. */
  12071. get: function () {
  12072. return this._isStencilEnable;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Engine.prototype._prepareWorkingCanvas = function () {
  12078. if (this._workingCanvas) {
  12079. return;
  12080. }
  12081. this._workingCanvas = document.createElement("canvas");
  12082. var context = this._workingCanvas.getContext("2d");
  12083. if (context) {
  12084. this._workingContext = context;
  12085. }
  12086. };
  12087. /**
  12088. * Reset the texture cache to empty state
  12089. */
  12090. Engine.prototype.resetTextureCache = function () {
  12091. for (var key in this._boundTexturesCache) {
  12092. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12093. continue;
  12094. }
  12095. var boundTexture = this._boundTexturesCache[key];
  12096. if (boundTexture) {
  12097. this._removeDesignatedSlot(boundTexture);
  12098. }
  12099. this._boundTexturesCache[key] = null;
  12100. }
  12101. if (!this.disableTextureBindingOptimization) {
  12102. this._nextFreeTextureSlots = [];
  12103. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12104. this._nextFreeTextureSlots.push(slot);
  12105. }
  12106. }
  12107. this._currentTextureChannel = -1;
  12108. };
  12109. /**
  12110. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12111. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12112. * @returns true if engine is in deterministic lock step mode
  12113. */
  12114. Engine.prototype.isDeterministicLockStep = function () {
  12115. return this._deterministicLockstep;
  12116. };
  12117. /**
  12118. * Gets the max steps when engine is running in deterministic lock step
  12119. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12120. * @returns the max steps
  12121. */
  12122. Engine.prototype.getLockstepMaxSteps = function () {
  12123. return this._lockstepMaxSteps;
  12124. };
  12125. /**
  12126. * Gets an object containing information about the current webGL context
  12127. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12128. */
  12129. Engine.prototype.getGlInfo = function () {
  12130. return {
  12131. vendor: this._glVendor,
  12132. renderer: this._glRenderer,
  12133. version: this._glVersion
  12134. };
  12135. };
  12136. /**
  12137. * Gets current aspect ratio
  12138. * @param camera defines the camera to use to get the aspect ratio
  12139. * @param useScreen defines if screen size must be used (or the current render target if any)
  12140. * @returns a number defining the aspect ratio
  12141. */
  12142. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12143. if (useScreen === void 0) { useScreen = false; }
  12144. var viewport = camera.viewport;
  12145. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12146. };
  12147. /**
  12148. * Gets current screen aspect ratio
  12149. * @returns a number defining the aspect ratio
  12150. */
  12151. Engine.prototype.getScreenAspectRatio = function () {
  12152. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12153. };
  12154. /**
  12155. * Gets the current render width
  12156. * @param useScreen defines if screen size must be used (or the current render target if any)
  12157. * @returns a number defining the current render width
  12158. */
  12159. Engine.prototype.getRenderWidth = function (useScreen) {
  12160. if (useScreen === void 0) { useScreen = false; }
  12161. if (!useScreen && this._currentRenderTarget) {
  12162. return this._currentRenderTarget.width;
  12163. }
  12164. return this._gl.drawingBufferWidth;
  12165. };
  12166. /**
  12167. * Gets the current render height
  12168. * @param useScreen defines if screen size must be used (or the current render target if any)
  12169. * @returns a number defining the current render height
  12170. */
  12171. Engine.prototype.getRenderHeight = function (useScreen) {
  12172. if (useScreen === void 0) { useScreen = false; }
  12173. if (!useScreen && this._currentRenderTarget) {
  12174. return this._currentRenderTarget.height;
  12175. }
  12176. return this._gl.drawingBufferHeight;
  12177. };
  12178. /**
  12179. * Gets the HTML canvas attached with the current webGL context
  12180. * @returns a HTML canvas
  12181. */
  12182. Engine.prototype.getRenderingCanvas = function () {
  12183. return this._renderingCanvas;
  12184. };
  12185. /**
  12186. * Gets the client rect of the HTML canvas attached with the current webGL context
  12187. * @returns a client rectanglee
  12188. */
  12189. Engine.prototype.getRenderingCanvasClientRect = function () {
  12190. if (!this._renderingCanvas) {
  12191. return null;
  12192. }
  12193. return this._renderingCanvas.getBoundingClientRect();
  12194. };
  12195. /**
  12196. * Defines the hardware scaling level.
  12197. * By default the hardware scaling level is computed from the window device ratio.
  12198. * 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.
  12199. * @param level defines the level to use
  12200. */
  12201. Engine.prototype.setHardwareScalingLevel = function (level) {
  12202. this._hardwareScalingLevel = level;
  12203. this.resize();
  12204. };
  12205. /**
  12206. * Gets the current hardware scaling level.
  12207. * By default the hardware scaling level is computed from the window device ratio.
  12208. * 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.
  12209. * @returns a number indicating the current hardware scaling level
  12210. */
  12211. Engine.prototype.getHardwareScalingLevel = function () {
  12212. return this._hardwareScalingLevel;
  12213. };
  12214. /**
  12215. * Gets the list of loaded textures
  12216. * @returns an array containing all loaded textures
  12217. */
  12218. Engine.prototype.getLoadedTexturesCache = function () {
  12219. return this._internalTexturesCache;
  12220. };
  12221. /**
  12222. * Gets the object containing all engine capabilities
  12223. * @returns the EngineCapabilities object
  12224. */
  12225. Engine.prototype.getCaps = function () {
  12226. return this._caps;
  12227. };
  12228. Object.defineProperty(Engine.prototype, "drawCalls", {
  12229. /** @hidden */
  12230. get: function () {
  12231. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12232. return 0;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12238. /** @hidden */
  12239. get: function () {
  12240. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12241. return null;
  12242. },
  12243. enumerable: true,
  12244. configurable: true
  12245. });
  12246. /**
  12247. * Gets the current depth function
  12248. * @returns a number defining the depth function
  12249. */
  12250. Engine.prototype.getDepthFunction = function () {
  12251. return this._depthCullingState.depthFunc;
  12252. };
  12253. /**
  12254. * Sets the current depth function
  12255. * @param depthFunc defines the function to use
  12256. */
  12257. Engine.prototype.setDepthFunction = function (depthFunc) {
  12258. this._depthCullingState.depthFunc = depthFunc;
  12259. };
  12260. /**
  12261. * Sets the current depth function to GREATER
  12262. */
  12263. Engine.prototype.setDepthFunctionToGreater = function () {
  12264. this._depthCullingState.depthFunc = this._gl.GREATER;
  12265. };
  12266. /**
  12267. * Sets the current depth function to GEQUAL
  12268. */
  12269. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12270. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12271. };
  12272. /**
  12273. * Sets the current depth function to LESS
  12274. */
  12275. Engine.prototype.setDepthFunctionToLess = function () {
  12276. this._depthCullingState.depthFunc = this._gl.LESS;
  12277. };
  12278. /**
  12279. * Sets the current depth function to LEQUAL
  12280. */
  12281. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12282. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12283. };
  12284. /**
  12285. * Gets a boolean indicating if stencil buffer is enabled
  12286. * @returns the current stencil buffer state
  12287. */
  12288. Engine.prototype.getStencilBuffer = function () {
  12289. return this._stencilState.stencilTest;
  12290. };
  12291. /**
  12292. * Enable or disable the stencil buffer
  12293. * @param enable defines if the stencil buffer must be enabled or disabled
  12294. */
  12295. Engine.prototype.setStencilBuffer = function (enable) {
  12296. this._stencilState.stencilTest = enable;
  12297. };
  12298. /**
  12299. * Gets the current stencil mask
  12300. * @returns a number defining the new stencil mask to use
  12301. */
  12302. Engine.prototype.getStencilMask = function () {
  12303. return this._stencilState.stencilMask;
  12304. };
  12305. /**
  12306. * Sets the current stencil mask
  12307. * @param mask defines the new stencil mask to use
  12308. */
  12309. Engine.prototype.setStencilMask = function (mask) {
  12310. this._stencilState.stencilMask = mask;
  12311. };
  12312. /**
  12313. * Gets the current stencil function
  12314. * @returns a number defining the stencil function to use
  12315. */
  12316. Engine.prototype.getStencilFunction = function () {
  12317. return this._stencilState.stencilFunc;
  12318. };
  12319. /**
  12320. * Gets the current stencil reference value
  12321. * @returns a number defining the stencil reference value to use
  12322. */
  12323. Engine.prototype.getStencilFunctionReference = function () {
  12324. return this._stencilState.stencilFuncRef;
  12325. };
  12326. /**
  12327. * Gets the current stencil mask
  12328. * @returns a number defining the stencil mask to use
  12329. */
  12330. Engine.prototype.getStencilFunctionMask = function () {
  12331. return this._stencilState.stencilFuncMask;
  12332. };
  12333. /**
  12334. * Sets the current stencil function
  12335. * @param stencilFunc defines the new stencil function to use
  12336. */
  12337. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12338. this._stencilState.stencilFunc = stencilFunc;
  12339. };
  12340. /**
  12341. * Sets the current stencil reference
  12342. * @param reference defines the new stencil reference to use
  12343. */
  12344. Engine.prototype.setStencilFunctionReference = function (reference) {
  12345. this._stencilState.stencilFuncRef = reference;
  12346. };
  12347. /**
  12348. * Sets the current stencil mask
  12349. * @param mask defines the new stencil mask to use
  12350. */
  12351. Engine.prototype.setStencilFunctionMask = function (mask) {
  12352. this._stencilState.stencilFuncMask = mask;
  12353. };
  12354. /**
  12355. * Gets the current stencil operation when stencil fails
  12356. * @returns a number defining stencil operation to use when stencil fails
  12357. */
  12358. Engine.prototype.getStencilOperationFail = function () {
  12359. return this._stencilState.stencilOpStencilFail;
  12360. };
  12361. /**
  12362. * Gets the current stencil operation when depth fails
  12363. * @returns a number defining stencil operation to use when depth fails
  12364. */
  12365. Engine.prototype.getStencilOperationDepthFail = function () {
  12366. return this._stencilState.stencilOpDepthFail;
  12367. };
  12368. /**
  12369. * Gets the current stencil operation when stencil passes
  12370. * @returns a number defining stencil operation to use when stencil passes
  12371. */
  12372. Engine.prototype.getStencilOperationPass = function () {
  12373. return this._stencilState.stencilOpStencilDepthPass;
  12374. };
  12375. /**
  12376. * Sets the stencil operation to use when stencil fails
  12377. * @param operation defines the stencil operation to use when stencil fails
  12378. */
  12379. Engine.prototype.setStencilOperationFail = function (operation) {
  12380. this._stencilState.stencilOpStencilFail = operation;
  12381. };
  12382. /**
  12383. * Sets the stencil operation to use when depth fails
  12384. * @param operation defines the stencil operation to use when depth fails
  12385. */
  12386. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12387. this._stencilState.stencilOpDepthFail = operation;
  12388. };
  12389. /**
  12390. * Sets the stencil operation to use when stencil passes
  12391. * @param operation defines the stencil operation to use when stencil passes
  12392. */
  12393. Engine.prototype.setStencilOperationPass = function (operation) {
  12394. this._stencilState.stencilOpStencilDepthPass = operation;
  12395. };
  12396. /**
  12397. * Sets a boolean indicating if the dithering state is enabled or disabled
  12398. * @param value defines the dithering state
  12399. */
  12400. Engine.prototype.setDitheringState = function (value) {
  12401. if (value) {
  12402. this._gl.enable(this._gl.DITHER);
  12403. }
  12404. else {
  12405. this._gl.disable(this._gl.DITHER);
  12406. }
  12407. };
  12408. /**
  12409. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12410. * @param value defines the rasterizer state
  12411. */
  12412. Engine.prototype.setRasterizerState = function (value) {
  12413. if (value) {
  12414. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12415. }
  12416. else {
  12417. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12418. }
  12419. };
  12420. /**
  12421. * stop executing a render loop function and remove it from the execution array
  12422. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12423. */
  12424. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12425. if (!renderFunction) {
  12426. this._activeRenderLoops = [];
  12427. return;
  12428. }
  12429. var index = this._activeRenderLoops.indexOf(renderFunction);
  12430. if (index >= 0) {
  12431. this._activeRenderLoops.splice(index, 1);
  12432. }
  12433. };
  12434. /** @hidden */
  12435. Engine.prototype._renderLoop = function () {
  12436. if (!this._contextWasLost) {
  12437. var shouldRender = true;
  12438. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12439. shouldRender = false;
  12440. }
  12441. if (shouldRender) {
  12442. // Start new frame
  12443. this.beginFrame();
  12444. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12445. var renderFunction = this._activeRenderLoops[index];
  12446. renderFunction();
  12447. }
  12448. // Present
  12449. this.endFrame();
  12450. }
  12451. }
  12452. if (this._activeRenderLoops.length > 0) {
  12453. // Register new frame
  12454. var requester = null;
  12455. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12456. requester = this._vrDisplay;
  12457. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12458. }
  12459. else {
  12460. this._renderingQueueLaunched = false;
  12461. }
  12462. };
  12463. /**
  12464. * Register and execute a render loop. The engine can have more than one render function
  12465. * @param renderFunction defines the function to continuously execute
  12466. */
  12467. Engine.prototype.runRenderLoop = function (renderFunction) {
  12468. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12469. return;
  12470. }
  12471. this._activeRenderLoops.push(renderFunction);
  12472. if (!this._renderingQueueLaunched) {
  12473. this._renderingQueueLaunched = true;
  12474. this._bindedRenderFunction = this._renderLoop.bind(this);
  12475. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12476. }
  12477. };
  12478. /**
  12479. * Toggle full screen mode
  12480. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12481. * @param options defines an option object to be sent to the requestFullscreen function
  12482. */
  12483. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12484. if (this.isFullscreen) {
  12485. BABYLON.Tools.ExitFullscreen();
  12486. }
  12487. else {
  12488. this._pointerLockRequested = requestPointerLock;
  12489. if (this._renderingCanvas) {
  12490. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12491. }
  12492. }
  12493. };
  12494. /**
  12495. * Clear the current render buffer or the current render target (if any is set up)
  12496. * @param color defines the color to use
  12497. * @param backBuffer defines if the back buffer must be cleared
  12498. * @param depth defines if the depth buffer must be cleared
  12499. * @param stencil defines if the stencil buffer must be cleared
  12500. */
  12501. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12502. if (stencil === void 0) { stencil = false; }
  12503. this.applyStates();
  12504. var mode = 0;
  12505. if (backBuffer && color) {
  12506. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12507. mode |= this._gl.COLOR_BUFFER_BIT;
  12508. }
  12509. if (depth) {
  12510. this._gl.clearDepth(1.0);
  12511. mode |= this._gl.DEPTH_BUFFER_BIT;
  12512. }
  12513. if (stencil) {
  12514. this._gl.clearStencil(0);
  12515. mode |= this._gl.STENCIL_BUFFER_BIT;
  12516. }
  12517. this._gl.clear(mode);
  12518. };
  12519. /**
  12520. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12521. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12522. * @param y defines the y-coordinate of the corner of the clear rectangle
  12523. * @param width defines the width of the clear rectangle
  12524. * @param height defines the height of the clear rectangle
  12525. * @param clearColor defines the clear color
  12526. */
  12527. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12528. var gl = this._gl;
  12529. // Save state
  12530. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12531. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12532. // Change state
  12533. gl.enable(gl.SCISSOR_TEST);
  12534. gl.scissor(x, y, width, height);
  12535. // Clear
  12536. this.clear(clearColor, true, true, true);
  12537. // Restore state
  12538. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12539. if (curScissor === true) {
  12540. gl.enable(gl.SCISSOR_TEST);
  12541. }
  12542. else {
  12543. gl.disable(gl.SCISSOR_TEST);
  12544. }
  12545. };
  12546. /** @hidden */
  12547. Engine.prototype._viewport = function (x, y, width, height) {
  12548. if (x !== this._viewportCached.x ||
  12549. y !== this._viewportCached.y ||
  12550. width !== this._viewportCached.z ||
  12551. height !== this._viewportCached.w) {
  12552. this._viewportCached.x = x;
  12553. this._viewportCached.y = y;
  12554. this._viewportCached.z = width;
  12555. this._viewportCached.w = height;
  12556. this._gl.viewport(x, y, width, height);
  12557. }
  12558. };
  12559. /**
  12560. * Set the WebGL's viewport
  12561. * @param viewport defines the viewport element to be used
  12562. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12563. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12564. */
  12565. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12566. var width = requiredWidth || this.getRenderWidth();
  12567. var height = requiredHeight || this.getRenderHeight();
  12568. var x = viewport.x || 0;
  12569. var y = viewport.y || 0;
  12570. this._cachedViewport = viewport;
  12571. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12572. };
  12573. /**
  12574. * Directly set the WebGL Viewport
  12575. * @param x defines the x coordinate of the viewport (in screen space)
  12576. * @param y defines the y coordinate of the viewport (in screen space)
  12577. * @param width defines the width of the viewport (in screen space)
  12578. * @param height defines the height of the viewport (in screen space)
  12579. * @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
  12580. */
  12581. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12582. var currentViewport = this._cachedViewport;
  12583. this._cachedViewport = null;
  12584. this._viewport(x, y, width, height);
  12585. return currentViewport;
  12586. };
  12587. /**
  12588. * Begin a new frame
  12589. */
  12590. Engine.prototype.beginFrame = function () {
  12591. this.onBeginFrameObservable.notifyObservers(this);
  12592. this._measureFps();
  12593. };
  12594. /**
  12595. * Enf the current frame
  12596. */
  12597. Engine.prototype.endFrame = function () {
  12598. // Force a flush in case we are using a bad OS.
  12599. if (this._badOS) {
  12600. this.flushFramebuffer();
  12601. }
  12602. // Submit frame to the vr device, if enabled
  12603. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12604. // TODO: We should only submit the frame if we read frameData successfully.
  12605. this._vrDisplay.submitFrame();
  12606. }
  12607. this.onEndFrameObservable.notifyObservers(this);
  12608. };
  12609. /**
  12610. * Resize the view according to the canvas' size
  12611. */
  12612. Engine.prototype.resize = function () {
  12613. // We're not resizing the size of the canvas while in VR mode & presenting
  12614. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12615. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12616. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12617. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12618. }
  12619. };
  12620. /**
  12621. * Force a specific size of the canvas
  12622. * @param width defines the new canvas' width
  12623. * @param height defines the new canvas' height
  12624. */
  12625. Engine.prototype.setSize = function (width, height) {
  12626. if (!this._renderingCanvas) {
  12627. return;
  12628. }
  12629. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12630. return;
  12631. }
  12632. this._renderingCanvas.width = width;
  12633. this._renderingCanvas.height = height;
  12634. for (var index = 0; index < this.scenes.length; index++) {
  12635. var scene = this.scenes[index];
  12636. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12637. var cam = scene.cameras[camIndex];
  12638. cam._currentRenderId = 0;
  12639. }
  12640. }
  12641. if (this.onResizeObservable.hasObservers) {
  12642. this.onResizeObservable.notifyObservers(this);
  12643. }
  12644. };
  12645. // WebVR functions
  12646. /**
  12647. * Gets a boolean indicating if a webVR device was detected
  12648. * @returns true if a webVR device was detected
  12649. */
  12650. Engine.prototype.isVRDevicePresent = function () {
  12651. return !!this._vrDisplay;
  12652. };
  12653. /**
  12654. * Gets the current webVR device
  12655. * @returns the current webVR device (or null)
  12656. */
  12657. Engine.prototype.getVRDevice = function () {
  12658. return this._vrDisplay;
  12659. };
  12660. /**
  12661. * Initializes a webVR display and starts listening to display change events
  12662. * The onVRDisplayChangedObservable will be notified upon these changes
  12663. * @returns The onVRDisplayChangedObservable
  12664. */
  12665. Engine.prototype.initWebVR = function () {
  12666. this.initWebVRAsync();
  12667. return this.onVRDisplayChangedObservable;
  12668. };
  12669. /**
  12670. * Initializes a webVR display and starts listening to display change events
  12671. * The onVRDisplayChangedObservable will be notified upon these changes
  12672. * @returns A promise containing a VRDisplay and if vr is supported
  12673. */
  12674. Engine.prototype.initWebVRAsync = function () {
  12675. var _this = this;
  12676. var notifyObservers = function () {
  12677. var eventArgs = {
  12678. vrDisplay: _this._vrDisplay,
  12679. vrSupported: _this._vrSupported
  12680. };
  12681. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12682. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12683. };
  12684. if (!this._onVrDisplayConnect) {
  12685. this._onVrDisplayConnect = function (event) {
  12686. _this._vrDisplay = event.display;
  12687. notifyObservers();
  12688. };
  12689. this._onVrDisplayDisconnect = function () {
  12690. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12691. _this._vrDisplay = undefined;
  12692. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12693. notifyObservers();
  12694. };
  12695. this._onVrDisplayPresentChange = function () {
  12696. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12697. };
  12698. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12699. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12700. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12701. }
  12702. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12703. this._webVRInitPromise.then(notifyObservers);
  12704. return this._webVRInitPromise;
  12705. };
  12706. /**
  12707. * Call this function to switch to webVR mode
  12708. * Will do nothing if webVR is not supported or if there is no webVR device
  12709. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12710. */
  12711. Engine.prototype.enableVR = function () {
  12712. var _this = this;
  12713. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12714. var onResolved = function () {
  12715. _this.onVRRequestPresentComplete.notifyObservers(true);
  12716. _this._onVRFullScreenTriggered();
  12717. };
  12718. var onRejected = function () {
  12719. _this.onVRRequestPresentComplete.notifyObservers(false);
  12720. };
  12721. this.onVRRequestPresentStart.notifyObservers(this);
  12722. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12723. }
  12724. };
  12725. /**
  12726. * Call this function to leave webVR mode
  12727. * Will do nothing if webVR is not supported or if there is no webVR device
  12728. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12729. */
  12730. Engine.prototype.disableVR = function () {
  12731. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12732. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12733. }
  12734. };
  12735. Engine.prototype._getVRDisplaysAsync = function () {
  12736. var _this = this;
  12737. return new Promise(function (res, rej) {
  12738. if (navigator.getVRDisplays) {
  12739. navigator.getVRDisplays().then(function (devices) {
  12740. _this._vrSupported = true;
  12741. // note that devices may actually be an empty array. This is fine;
  12742. // we expect this._vrDisplay to be undefined in this case.
  12743. _this._vrDisplay = devices[0];
  12744. res({
  12745. vrDisplay: _this._vrDisplay,
  12746. vrSupported: _this._vrSupported
  12747. });
  12748. });
  12749. }
  12750. else {
  12751. _this._vrDisplay = undefined;
  12752. _this._vrSupported = false;
  12753. res({
  12754. vrDisplay: _this._vrDisplay,
  12755. vrSupported: _this._vrSupported
  12756. });
  12757. }
  12758. });
  12759. };
  12760. /**
  12761. * Binds the frame buffer to the specified texture.
  12762. * @param texture The texture to render to or null for the default canvas
  12763. * @param faceIndex The face of the texture to render to in case of cube texture
  12764. * @param requiredWidth The width of the target to render to
  12765. * @param requiredHeight The height of the target to render to
  12766. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12767. * @param depthStencilTexture The depth stencil texture to use to render
  12768. * @param lodLevel defines le lod level to bind to the frame buffer
  12769. */
  12770. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12771. if (lodLevel === void 0) { lodLevel = 0; }
  12772. if (this._currentRenderTarget) {
  12773. this.unBindFramebuffer(this._currentRenderTarget);
  12774. }
  12775. this._currentRenderTarget = texture;
  12776. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12777. var gl = this._gl;
  12778. if (texture.isCube) {
  12779. if (faceIndex === undefined) {
  12780. faceIndex = 0;
  12781. }
  12782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12783. if (depthStencilTexture) {
  12784. if (depthStencilTexture._generateStencilBuffer) {
  12785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12786. }
  12787. else {
  12788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12789. }
  12790. }
  12791. }
  12792. if (this._cachedViewport && !forceFullscreenViewport) {
  12793. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12794. }
  12795. else {
  12796. if (!requiredWidth) {
  12797. requiredWidth = texture.width;
  12798. if (lodLevel) {
  12799. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12800. }
  12801. }
  12802. if (!requiredHeight) {
  12803. requiredHeight = texture.height;
  12804. if (lodLevel) {
  12805. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12806. }
  12807. }
  12808. this._viewport(0, 0, requiredWidth, requiredHeight);
  12809. }
  12810. this.wipeCaches();
  12811. };
  12812. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12813. if (this._currentFramebuffer !== framebuffer) {
  12814. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12815. this._currentFramebuffer = framebuffer;
  12816. }
  12817. };
  12818. /**
  12819. * Unbind the current render target texture from the webGL context
  12820. * @param texture defines the render target texture to unbind
  12821. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12822. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12823. */
  12824. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12825. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12826. this._currentRenderTarget = null;
  12827. // If MSAA, we need to bitblt back to main texture
  12828. var gl = this._gl;
  12829. if (texture._MSAAFramebuffer) {
  12830. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12831. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12832. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12833. }
  12834. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12835. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12836. gl.generateMipmap(gl.TEXTURE_2D);
  12837. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12838. }
  12839. if (onBeforeUnbind) {
  12840. if (texture._MSAAFramebuffer) {
  12841. // Bind the correct framebuffer
  12842. this.bindUnboundFramebuffer(texture._framebuffer);
  12843. }
  12844. onBeforeUnbind();
  12845. }
  12846. this.bindUnboundFramebuffer(null);
  12847. };
  12848. /**
  12849. * Unbind a list of render target textures from the webGL context
  12850. * This is used only when drawBuffer extension or webGL2 are active
  12851. * @param textures defines the render target textures to unbind
  12852. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12853. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12854. */
  12855. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12856. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12857. this._currentRenderTarget = null;
  12858. // If MSAA, we need to bitblt back to main texture
  12859. var gl = this._gl;
  12860. if (textures[0]._MSAAFramebuffer) {
  12861. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12862. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12863. var attachments = textures[0]._attachments;
  12864. if (!attachments) {
  12865. attachments = new Array(textures.length);
  12866. textures[0]._attachments = attachments;
  12867. }
  12868. for (var i = 0; i < textures.length; i++) {
  12869. var texture = textures[i];
  12870. for (var j = 0; j < attachments.length; j++) {
  12871. attachments[j] = gl.NONE;
  12872. }
  12873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12874. gl.readBuffer(attachments[i]);
  12875. gl.drawBuffers(attachments);
  12876. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12877. }
  12878. for (var i = 0; i < attachments.length; i++) {
  12879. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12880. }
  12881. gl.drawBuffers(attachments);
  12882. }
  12883. for (var i = 0; i < textures.length; i++) {
  12884. var texture = textures[i];
  12885. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12886. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12887. gl.generateMipmap(gl.TEXTURE_2D);
  12888. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12889. }
  12890. }
  12891. if (onBeforeUnbind) {
  12892. if (textures[0]._MSAAFramebuffer) {
  12893. // Bind the correct framebuffer
  12894. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12895. }
  12896. onBeforeUnbind();
  12897. }
  12898. this.bindUnboundFramebuffer(null);
  12899. };
  12900. /**
  12901. * Force the mipmap generation for the given render target texture
  12902. * @param texture defines the render target texture to use
  12903. */
  12904. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12905. if (texture.generateMipMaps) {
  12906. var gl = this._gl;
  12907. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12908. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12910. }
  12911. };
  12912. /**
  12913. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12914. */
  12915. Engine.prototype.flushFramebuffer = function () {
  12916. this._gl.flush();
  12917. };
  12918. /**
  12919. * Unbind the current render target and bind the default framebuffer
  12920. */
  12921. Engine.prototype.restoreDefaultFramebuffer = function () {
  12922. if (this._currentRenderTarget) {
  12923. this.unBindFramebuffer(this._currentRenderTarget);
  12924. }
  12925. else {
  12926. this.bindUnboundFramebuffer(null);
  12927. }
  12928. if (this._cachedViewport) {
  12929. this.setViewport(this._cachedViewport);
  12930. }
  12931. this.wipeCaches();
  12932. };
  12933. // UBOs
  12934. /**
  12935. * Create an uniform buffer
  12936. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12937. * @param elements defines the content of the uniform buffer
  12938. * @returns the webGL uniform buffer
  12939. */
  12940. Engine.prototype.createUniformBuffer = function (elements) {
  12941. var ubo = this._gl.createBuffer();
  12942. if (!ubo) {
  12943. throw new Error("Unable to create uniform buffer");
  12944. }
  12945. this.bindUniformBuffer(ubo);
  12946. if (elements instanceof Float32Array) {
  12947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12948. }
  12949. else {
  12950. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12951. }
  12952. this.bindUniformBuffer(null);
  12953. ubo.references = 1;
  12954. return ubo;
  12955. };
  12956. /**
  12957. * Create a dynamic uniform buffer
  12958. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12959. * @param elements defines the content of the uniform buffer
  12960. * @returns the webGL uniform buffer
  12961. */
  12962. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12963. var ubo = this._gl.createBuffer();
  12964. if (!ubo) {
  12965. throw new Error("Unable to create dynamic uniform buffer");
  12966. }
  12967. this.bindUniformBuffer(ubo);
  12968. if (elements instanceof Float32Array) {
  12969. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12970. }
  12971. else {
  12972. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12973. }
  12974. this.bindUniformBuffer(null);
  12975. ubo.references = 1;
  12976. return ubo;
  12977. };
  12978. /**
  12979. * Update an existing uniform buffer
  12980. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12981. * @param uniformBuffer defines the target uniform buffer
  12982. * @param elements defines the content to update
  12983. * @param offset defines the offset in the uniform buffer where update should start
  12984. * @param count defines the size of the data to update
  12985. */
  12986. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12987. this.bindUniformBuffer(uniformBuffer);
  12988. if (offset === undefined) {
  12989. offset = 0;
  12990. }
  12991. if (count === undefined) {
  12992. if (elements instanceof Float32Array) {
  12993. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12994. }
  12995. else {
  12996. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12997. }
  12998. }
  12999. else {
  13000. if (elements instanceof Float32Array) {
  13001. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13002. }
  13003. else {
  13004. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13005. }
  13006. }
  13007. this.bindUniformBuffer(null);
  13008. };
  13009. // VBOs
  13010. Engine.prototype._resetVertexBufferBinding = function () {
  13011. this.bindArrayBuffer(null);
  13012. this._cachedVertexBuffers = null;
  13013. };
  13014. /**
  13015. * Creates a vertex buffer
  13016. * @param data the data for the vertex buffer
  13017. * @returns the new WebGL static buffer
  13018. */
  13019. Engine.prototype.createVertexBuffer = function (data) {
  13020. var vbo = this._gl.createBuffer();
  13021. if (!vbo) {
  13022. throw new Error("Unable to create vertex buffer");
  13023. }
  13024. this.bindArrayBuffer(vbo);
  13025. if (data instanceof Array) {
  13026. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13027. }
  13028. else {
  13029. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13030. }
  13031. this._resetVertexBufferBinding();
  13032. vbo.references = 1;
  13033. return vbo;
  13034. };
  13035. /**
  13036. * Creates a dynamic vertex buffer
  13037. * @param data the data for the dynamic vertex buffer
  13038. * @returns the new WebGL dynamic buffer
  13039. */
  13040. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13041. var vbo = this._gl.createBuffer();
  13042. if (!vbo) {
  13043. throw new Error("Unable to create dynamic vertex buffer");
  13044. }
  13045. this.bindArrayBuffer(vbo);
  13046. if (data instanceof Array) {
  13047. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13048. }
  13049. else {
  13050. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13051. }
  13052. this._resetVertexBufferBinding();
  13053. vbo.references = 1;
  13054. return vbo;
  13055. };
  13056. /**
  13057. * Update a dynamic index buffer
  13058. * @param indexBuffer defines the target index buffer
  13059. * @param indices defines the data to update
  13060. * @param offset defines the offset in the target index buffer where update should start
  13061. */
  13062. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13063. if (offset === void 0) { offset = 0; }
  13064. // Force cache update
  13065. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13066. this.bindIndexBuffer(indexBuffer);
  13067. var arrayBuffer;
  13068. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13069. arrayBuffer = indices;
  13070. }
  13071. else {
  13072. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13073. }
  13074. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13075. this._resetIndexBufferBinding();
  13076. };
  13077. /**
  13078. * Updates a dynamic vertex buffer.
  13079. * @param vertexBuffer the vertex buffer to update
  13080. * @param data the data used to update the vertex buffer
  13081. * @param byteOffset the byte offset of the data
  13082. * @param byteLength the byte length of the data
  13083. */
  13084. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13085. this.bindArrayBuffer(vertexBuffer);
  13086. if (byteOffset === undefined) {
  13087. byteOffset = 0;
  13088. }
  13089. if (byteLength === undefined) {
  13090. if (data instanceof Array) {
  13091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13092. }
  13093. else {
  13094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13095. }
  13096. }
  13097. else {
  13098. if (data instanceof Array) {
  13099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13100. }
  13101. else {
  13102. if (data instanceof ArrayBuffer) {
  13103. data = new Uint8Array(data, byteOffset, byteLength);
  13104. }
  13105. else {
  13106. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13107. }
  13108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13109. }
  13110. }
  13111. this._resetVertexBufferBinding();
  13112. };
  13113. Engine.prototype._resetIndexBufferBinding = function () {
  13114. this.bindIndexBuffer(null);
  13115. this._cachedIndexBuffer = null;
  13116. };
  13117. /**
  13118. * Creates a new index buffer
  13119. * @param indices defines the content of the index buffer
  13120. * @param updatable defines if the index buffer must be updatable
  13121. * @returns a new webGL buffer
  13122. */
  13123. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13124. var vbo = this._gl.createBuffer();
  13125. if (!vbo) {
  13126. throw new Error("Unable to create index buffer");
  13127. }
  13128. this.bindIndexBuffer(vbo);
  13129. // Check for 32 bits indices
  13130. var arrayBuffer;
  13131. var need32Bits = false;
  13132. if (indices instanceof Uint16Array) {
  13133. arrayBuffer = indices;
  13134. }
  13135. else {
  13136. //check 32 bit support
  13137. if (this._caps.uintIndices) {
  13138. if (indices instanceof Uint32Array) {
  13139. arrayBuffer = indices;
  13140. need32Bits = true;
  13141. }
  13142. else {
  13143. //number[] or Int32Array, check if 32 bit is necessary
  13144. for (var index = 0; index < indices.length; index++) {
  13145. if (indices[index] > 65535) {
  13146. need32Bits = true;
  13147. break;
  13148. }
  13149. }
  13150. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13151. }
  13152. }
  13153. else {
  13154. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13155. arrayBuffer = new Uint16Array(indices);
  13156. }
  13157. }
  13158. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13159. this._resetIndexBufferBinding();
  13160. vbo.references = 1;
  13161. vbo.is32Bits = need32Bits;
  13162. return vbo;
  13163. };
  13164. /**
  13165. * Bind a webGL buffer to the webGL context
  13166. * @param buffer defines the buffer to bind
  13167. */
  13168. Engine.prototype.bindArrayBuffer = function (buffer) {
  13169. if (!this._vaoRecordInProgress) {
  13170. this._unbindVertexArrayObject();
  13171. }
  13172. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13173. };
  13174. /**
  13175. * Bind an uniform buffer to the current webGL context
  13176. * @param buffer defines the buffer to bind
  13177. */
  13178. Engine.prototype.bindUniformBuffer = function (buffer) {
  13179. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13180. };
  13181. /**
  13182. * Bind a buffer to the current webGL context at a given location
  13183. * @param buffer defines the buffer to bind
  13184. * @param location defines the index where to bind the buffer
  13185. */
  13186. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13187. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13188. };
  13189. /**
  13190. * Bind a specific block at a given index in a specific shader program
  13191. * @param shaderProgram defines the shader program
  13192. * @param blockName defines the block name
  13193. * @param index defines the index where to bind the block
  13194. */
  13195. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13196. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13197. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13198. };
  13199. ;
  13200. Engine.prototype.bindIndexBuffer = function (buffer) {
  13201. if (!this._vaoRecordInProgress) {
  13202. this._unbindVertexArrayObject();
  13203. }
  13204. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13205. };
  13206. Engine.prototype.bindBuffer = function (buffer, target) {
  13207. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13208. this._gl.bindBuffer(target, buffer);
  13209. this._currentBoundBuffer[target] = buffer;
  13210. }
  13211. };
  13212. /**
  13213. * update the bound buffer with the given data
  13214. * @param data defines the data to update
  13215. */
  13216. Engine.prototype.updateArrayBuffer = function (data) {
  13217. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13218. };
  13219. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13220. var pointer = this._currentBufferPointers[indx];
  13221. var changed = false;
  13222. if (!pointer.active) {
  13223. changed = true;
  13224. pointer.active = true;
  13225. pointer.index = indx;
  13226. pointer.size = size;
  13227. pointer.type = type;
  13228. pointer.normalized = normalized;
  13229. pointer.stride = stride;
  13230. pointer.offset = offset;
  13231. pointer.buffer = buffer;
  13232. }
  13233. else {
  13234. if (pointer.buffer !== buffer) {
  13235. pointer.buffer = buffer;
  13236. changed = true;
  13237. }
  13238. if (pointer.size !== size) {
  13239. pointer.size = size;
  13240. changed = true;
  13241. }
  13242. if (pointer.type !== type) {
  13243. pointer.type = type;
  13244. changed = true;
  13245. }
  13246. if (pointer.normalized !== normalized) {
  13247. pointer.normalized = normalized;
  13248. changed = true;
  13249. }
  13250. if (pointer.stride !== stride) {
  13251. pointer.stride = stride;
  13252. changed = true;
  13253. }
  13254. if (pointer.offset !== offset) {
  13255. pointer.offset = offset;
  13256. changed = true;
  13257. }
  13258. }
  13259. if (changed || this._vaoRecordInProgress) {
  13260. this.bindArrayBuffer(buffer);
  13261. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13262. }
  13263. };
  13264. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13265. if (indexBuffer == null) {
  13266. return;
  13267. }
  13268. if (this._cachedIndexBuffer !== indexBuffer) {
  13269. this._cachedIndexBuffer = indexBuffer;
  13270. this.bindIndexBuffer(indexBuffer);
  13271. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13272. }
  13273. };
  13274. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13275. var attributes = effect.getAttributesNames();
  13276. if (!this._vaoRecordInProgress) {
  13277. this._unbindVertexArrayObject();
  13278. }
  13279. this.unbindAllAttributes();
  13280. for (var index = 0; index < attributes.length; index++) {
  13281. var order = effect.getAttributeLocation(index);
  13282. if (order >= 0) {
  13283. var vertexBuffer = vertexBuffers[attributes[index]];
  13284. if (!vertexBuffer) {
  13285. continue;
  13286. }
  13287. this._gl.enableVertexAttribArray(order);
  13288. if (!this._vaoRecordInProgress) {
  13289. this._vertexAttribArraysEnabled[order] = true;
  13290. }
  13291. var buffer = vertexBuffer.getBuffer();
  13292. if (buffer) {
  13293. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13294. if (vertexBuffer.getIsInstanced()) {
  13295. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13296. if (!this._vaoRecordInProgress) {
  13297. this._currentInstanceLocations.push(order);
  13298. this._currentInstanceBuffers.push(buffer);
  13299. }
  13300. }
  13301. }
  13302. }
  13303. }
  13304. };
  13305. /**
  13306. * Records a vertex array object
  13307. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13308. * @param vertexBuffers defines the list of vertex buffers to store
  13309. * @param indexBuffer defines the index buffer to store
  13310. * @param effect defines the effect to store
  13311. * @returns the new vertex array object
  13312. */
  13313. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13314. var vao = this._gl.createVertexArray();
  13315. this._vaoRecordInProgress = true;
  13316. this._gl.bindVertexArray(vao);
  13317. this._mustWipeVertexAttributes = true;
  13318. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13319. this.bindIndexBuffer(indexBuffer);
  13320. this._vaoRecordInProgress = false;
  13321. this._gl.bindVertexArray(null);
  13322. return vao;
  13323. };
  13324. /**
  13325. * Bind a specific vertex array object
  13326. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13327. * @param vertexArrayObject defines the vertex array object to bind
  13328. * @param indexBuffer defines the index buffer to bind
  13329. */
  13330. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13331. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13332. this._cachedVertexArrayObject = vertexArrayObject;
  13333. this._gl.bindVertexArray(vertexArrayObject);
  13334. this._cachedVertexBuffers = null;
  13335. this._cachedIndexBuffer = null;
  13336. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13337. this._mustWipeVertexAttributes = true;
  13338. }
  13339. };
  13340. /**
  13341. * Bind webGl buffers directly to the webGL context
  13342. * @param vertexBuffer defines the vertex buffer to bind
  13343. * @param indexBuffer defines the index buffer to bind
  13344. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13345. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13346. * @param effect defines the effect associated with the vertex buffer
  13347. */
  13348. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13349. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13350. this._cachedVertexBuffers = vertexBuffer;
  13351. this._cachedEffectForVertexBuffers = effect;
  13352. var attributesCount = effect.getAttributesCount();
  13353. this._unbindVertexArrayObject();
  13354. this.unbindAllAttributes();
  13355. var offset = 0;
  13356. for (var index = 0; index < attributesCount; index++) {
  13357. if (index < vertexDeclaration.length) {
  13358. var order = effect.getAttributeLocation(index);
  13359. if (order >= 0) {
  13360. this._gl.enableVertexAttribArray(order);
  13361. this._vertexAttribArraysEnabled[order] = true;
  13362. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13363. }
  13364. offset += vertexDeclaration[index] * 4;
  13365. }
  13366. }
  13367. }
  13368. this._bindIndexBufferWithCache(indexBuffer);
  13369. };
  13370. Engine.prototype._unbindVertexArrayObject = function () {
  13371. if (!this._cachedVertexArrayObject) {
  13372. return;
  13373. }
  13374. this._cachedVertexArrayObject = null;
  13375. this._gl.bindVertexArray(null);
  13376. };
  13377. /**
  13378. * Bind a list of vertex buffers to the webGL context
  13379. * @param vertexBuffers defines the list of vertex buffers to bind
  13380. * @param indexBuffer defines the index buffer to bind
  13381. * @param effect defines the effect associated with the vertex buffers
  13382. */
  13383. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13384. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13385. this._cachedVertexBuffers = vertexBuffers;
  13386. this._cachedEffectForVertexBuffers = effect;
  13387. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13388. }
  13389. this._bindIndexBufferWithCache(indexBuffer);
  13390. };
  13391. /**
  13392. * Unbind all instance attributes
  13393. */
  13394. Engine.prototype.unbindInstanceAttributes = function () {
  13395. var boundBuffer;
  13396. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13397. var instancesBuffer = this._currentInstanceBuffers[i];
  13398. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13399. boundBuffer = instancesBuffer;
  13400. this.bindArrayBuffer(instancesBuffer);
  13401. }
  13402. var offsetLocation = this._currentInstanceLocations[i];
  13403. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13404. }
  13405. this._currentInstanceBuffers.length = 0;
  13406. this._currentInstanceLocations.length = 0;
  13407. };
  13408. /**
  13409. * Release and free the memory of a vertex array object
  13410. * @param vao defines the vertex array object to delete
  13411. */
  13412. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13413. this._gl.deleteVertexArray(vao);
  13414. };
  13415. /** @hidden */
  13416. Engine.prototype._releaseBuffer = function (buffer) {
  13417. buffer.references--;
  13418. if (buffer.references === 0) {
  13419. this._gl.deleteBuffer(buffer);
  13420. return true;
  13421. }
  13422. return false;
  13423. };
  13424. /**
  13425. * Creates a webGL buffer to use with instanciation
  13426. * @param capacity defines the size of the buffer
  13427. * @returns the webGL buffer
  13428. */
  13429. Engine.prototype.createInstancesBuffer = function (capacity) {
  13430. var buffer = this._gl.createBuffer();
  13431. if (!buffer) {
  13432. throw new Error("Unable to create instance buffer");
  13433. }
  13434. buffer.capacity = capacity;
  13435. this.bindArrayBuffer(buffer);
  13436. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13437. return buffer;
  13438. };
  13439. /**
  13440. * Delete a webGL buffer used with instanciation
  13441. * @param buffer defines the webGL buffer to delete
  13442. */
  13443. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13444. this._gl.deleteBuffer(buffer);
  13445. };
  13446. /**
  13447. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13448. * @param instancesBuffer defines the webGL buffer to update and bind
  13449. * @param data defines the data to store in the buffer
  13450. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13451. */
  13452. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13453. this.bindArrayBuffer(instancesBuffer);
  13454. if (data) {
  13455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13456. }
  13457. if (offsetLocations[0].index !== undefined) {
  13458. var stride = 0;
  13459. for (var i = 0; i < offsetLocations.length; i++) {
  13460. var ai = offsetLocations[i];
  13461. stride += ai.attributeSize * 4;
  13462. }
  13463. for (var i = 0; i < offsetLocations.length; i++) {
  13464. var ai = offsetLocations[i];
  13465. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13466. this._gl.enableVertexAttribArray(ai.index);
  13467. this._vertexAttribArraysEnabled[ai.index] = true;
  13468. }
  13469. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13470. this._gl.vertexAttribDivisor(ai.index, 1);
  13471. this._currentInstanceLocations.push(ai.index);
  13472. this._currentInstanceBuffers.push(instancesBuffer);
  13473. }
  13474. }
  13475. else {
  13476. for (var index = 0; index < 4; index++) {
  13477. var offsetLocation = offsetLocations[index];
  13478. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13479. this._gl.enableVertexAttribArray(offsetLocation);
  13480. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13481. }
  13482. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13483. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13484. this._currentInstanceLocations.push(offsetLocation);
  13485. this._currentInstanceBuffers.push(instancesBuffer);
  13486. }
  13487. }
  13488. };
  13489. /**
  13490. * Apply all cached states (depth, culling, stencil and alpha)
  13491. */
  13492. Engine.prototype.applyStates = function () {
  13493. this._depthCullingState.apply(this._gl);
  13494. this._stencilState.apply(this._gl);
  13495. this._alphaState.apply(this._gl);
  13496. };
  13497. /**
  13498. * Send a draw order
  13499. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13500. * @param indexStart defines the starting index
  13501. * @param indexCount defines the number of index to draw
  13502. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13503. */
  13504. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13505. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13506. };
  13507. /**
  13508. * Draw a list of points
  13509. * @param verticesStart defines the index of first vertex to draw
  13510. * @param verticesCount defines the count of vertices to draw
  13511. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13512. */
  13513. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13514. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13515. };
  13516. /**
  13517. * Draw a list of unindexed primitives
  13518. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13519. * @param verticesStart defines the index of first vertex to draw
  13520. * @param verticesCount defines the count of vertices to draw
  13521. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13522. */
  13523. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13524. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13525. };
  13526. /**
  13527. * Draw a list of indexed primitives
  13528. * @param fillMode defines the primitive to use
  13529. * @param indexStart defines the starting index
  13530. * @param indexCount defines the number of index to draw
  13531. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13532. */
  13533. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13534. // Apply states
  13535. this.applyStates();
  13536. this._drawCalls.addCount(1, false);
  13537. // Render
  13538. var drawMode = this._drawMode(fillMode);
  13539. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13540. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13541. if (instancesCount) {
  13542. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13543. }
  13544. else {
  13545. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13546. }
  13547. };
  13548. /**
  13549. * Draw a list of unindexed primitives
  13550. * @param fillMode defines the primitive to use
  13551. * @param verticesStart defines the index of first vertex to draw
  13552. * @param verticesCount defines the count of vertices to draw
  13553. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13554. */
  13555. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13556. // Apply states
  13557. this.applyStates();
  13558. this._drawCalls.addCount(1, false);
  13559. var drawMode = this._drawMode(fillMode);
  13560. if (instancesCount) {
  13561. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13562. }
  13563. else {
  13564. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13565. }
  13566. };
  13567. Engine.prototype._drawMode = function (fillMode) {
  13568. switch (fillMode) {
  13569. // Triangle views
  13570. case BABYLON.Material.TriangleFillMode:
  13571. return this._gl.TRIANGLES;
  13572. case BABYLON.Material.PointFillMode:
  13573. return this._gl.POINTS;
  13574. case BABYLON.Material.WireFrameFillMode:
  13575. return this._gl.LINES;
  13576. // Draw modes
  13577. case BABYLON.Material.PointListDrawMode:
  13578. return this._gl.POINTS;
  13579. case BABYLON.Material.LineListDrawMode:
  13580. return this._gl.LINES;
  13581. case BABYLON.Material.LineLoopDrawMode:
  13582. return this._gl.LINE_LOOP;
  13583. case BABYLON.Material.LineStripDrawMode:
  13584. return this._gl.LINE_STRIP;
  13585. case BABYLON.Material.TriangleStripDrawMode:
  13586. return this._gl.TRIANGLE_STRIP;
  13587. case BABYLON.Material.TriangleFanDrawMode:
  13588. return this._gl.TRIANGLE_FAN;
  13589. default:
  13590. return this._gl.TRIANGLES;
  13591. }
  13592. };
  13593. // Shaders
  13594. /** @hidden */
  13595. Engine.prototype._releaseEffect = function (effect) {
  13596. if (this._compiledEffects[effect._key]) {
  13597. delete this._compiledEffects[effect._key];
  13598. this._deleteProgram(effect.getProgram());
  13599. }
  13600. };
  13601. /** @hidden */
  13602. Engine.prototype._deleteProgram = function (program) {
  13603. if (program) {
  13604. program.__SPECTOR_rebuildProgram = null;
  13605. if (program.transformFeedback) {
  13606. this.deleteTransformFeedback(program.transformFeedback);
  13607. program.transformFeedback = null;
  13608. }
  13609. this._gl.deleteProgram(program);
  13610. }
  13611. };
  13612. /**
  13613. * Create a new effect (used to store vertex/fragment shaders)
  13614. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13615. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13616. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13617. * @param samplers defines an array of string used to represent textures
  13618. * @param defines defines the string containing the defines to use to compile the shaders
  13619. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13620. * @param onCompiled defines a function to call when the effect creation is successful
  13621. * @param onError defines a function to call when the effect creation has failed
  13622. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13623. * @returns the new Effect
  13624. */
  13625. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13626. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13627. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13628. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13629. if (this._compiledEffects[name]) {
  13630. var compiledEffect = this._compiledEffects[name];
  13631. if (onCompiled && compiledEffect.isReady()) {
  13632. onCompiled(compiledEffect);
  13633. }
  13634. return compiledEffect;
  13635. }
  13636. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13637. effect._key = name;
  13638. this._compiledEffects[name] = effect;
  13639. return effect;
  13640. };
  13641. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13642. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13643. };
  13644. ;
  13645. Engine.prototype._compileRawShader = function (source, type) {
  13646. var gl = this._gl;
  13647. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13648. gl.shaderSource(shader, source);
  13649. gl.compileShader(shader);
  13650. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13651. var log = gl.getShaderInfoLog(shader);
  13652. if (log) {
  13653. throw new Error(log);
  13654. }
  13655. }
  13656. if (!shader) {
  13657. throw new Error("Something went wrong while compile the shader.");
  13658. }
  13659. return shader;
  13660. };
  13661. ;
  13662. /**
  13663. * Directly creates a webGL program
  13664. * @param vertexCode defines the vertex shader code to use
  13665. * @param fragmentCode defines the fragment shader code to use
  13666. * @param context defines the webGL context to use (if not set, the current one will be used)
  13667. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13668. * @returns the new webGL program
  13669. */
  13670. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13671. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13672. context = context || this._gl;
  13673. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13674. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13675. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13676. };
  13677. /**
  13678. * Creates a webGL program
  13679. * @param vertexCode defines the vertex shader code to use
  13680. * @param fragmentCode defines the fragment shader code to use
  13681. * @param defines defines the string containing the defines to use to compile the shaders
  13682. * @param context defines the webGL context to use (if not set, the current one will be used)
  13683. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13684. * @returns the new webGL program
  13685. */
  13686. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13687. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13688. context = context || this._gl;
  13689. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13690. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13691. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13692. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13693. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13694. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13695. return program;
  13696. };
  13697. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13698. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13699. var shaderProgram = context.createProgram();
  13700. if (!shaderProgram) {
  13701. throw new Error("Unable to create program");
  13702. }
  13703. context.attachShader(shaderProgram, vertexShader);
  13704. context.attachShader(shaderProgram, fragmentShader);
  13705. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13706. var transformFeedback = this.createTransformFeedback();
  13707. this.bindTransformFeedback(transformFeedback);
  13708. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13709. shaderProgram.transformFeedback = transformFeedback;
  13710. }
  13711. context.linkProgram(shaderProgram);
  13712. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13713. this.bindTransformFeedback(null);
  13714. }
  13715. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13716. if (!linked) {
  13717. var error = context.getProgramInfoLog(shaderProgram);
  13718. if (error) {
  13719. throw new Error(error);
  13720. }
  13721. }
  13722. if (this.validateShaderPrograms) {
  13723. context.validateProgram(shaderProgram);
  13724. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13725. if (!validated) {
  13726. var error = context.getProgramInfoLog(shaderProgram);
  13727. if (error) {
  13728. throw new Error(error);
  13729. }
  13730. }
  13731. }
  13732. context.deleteShader(vertexShader);
  13733. context.deleteShader(fragmentShader);
  13734. return shaderProgram;
  13735. };
  13736. /**
  13737. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13738. * @param shaderProgram defines the webGL program to use
  13739. * @param uniformsNames defines the list of uniform names
  13740. * @returns an array of webGL uniform locations
  13741. */
  13742. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13743. var results = new Array();
  13744. for (var index = 0; index < uniformsNames.length; index++) {
  13745. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13746. }
  13747. return results;
  13748. };
  13749. /**
  13750. * Gets the lsit of active attributes for a given webGL program
  13751. * @param shaderProgram defines the webGL program to use
  13752. * @param attributesNames defines the list of attribute names to get
  13753. * @returns an array of indices indicating the offset of each attribute
  13754. */
  13755. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13756. var results = [];
  13757. for (var index = 0; index < attributesNames.length; index++) {
  13758. try {
  13759. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13760. }
  13761. catch (e) {
  13762. results.push(-1);
  13763. }
  13764. }
  13765. return results;
  13766. };
  13767. /**
  13768. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13769. * @param effect defines the effect to activate
  13770. */
  13771. Engine.prototype.enableEffect = function (effect) {
  13772. if (!effect) {
  13773. return;
  13774. }
  13775. // Use program
  13776. this.bindSamplers(effect);
  13777. this._currentEffect = effect;
  13778. if (effect.onBind) {
  13779. effect.onBind(effect);
  13780. }
  13781. effect.onBindObservable.notifyObservers(effect);
  13782. };
  13783. /**
  13784. * Set the value of an uniform to an array of int32
  13785. * @param uniform defines the webGL uniform location where to store the value
  13786. * @param array defines the array of int32 to store
  13787. */
  13788. Engine.prototype.setIntArray = function (uniform, array) {
  13789. if (!uniform)
  13790. return;
  13791. this._gl.uniform1iv(uniform, array);
  13792. };
  13793. /**
  13794. * Set the value of an uniform to an array of int32 (stored as vec2)
  13795. * @param uniform defines the webGL uniform location where to store the value
  13796. * @param array defines the array of int32 to store
  13797. */
  13798. Engine.prototype.setIntArray2 = function (uniform, array) {
  13799. if (!uniform || array.length % 2 !== 0)
  13800. return;
  13801. this._gl.uniform2iv(uniform, array);
  13802. };
  13803. /**
  13804. * Set the value of an uniform to an array of int32 (stored as vec3)
  13805. * @param uniform defines the webGL uniform location where to store the value
  13806. * @param array defines the array of int32 to store
  13807. */
  13808. Engine.prototype.setIntArray3 = function (uniform, array) {
  13809. if (!uniform || array.length % 3 !== 0)
  13810. return;
  13811. this._gl.uniform3iv(uniform, array);
  13812. };
  13813. /**
  13814. * Set the value of an uniform to an array of int32 (stored as vec4)
  13815. * @param uniform defines the webGL uniform location where to store the value
  13816. * @param array defines the array of int32 to store
  13817. */
  13818. Engine.prototype.setIntArray4 = function (uniform, array) {
  13819. if (!uniform || array.length % 4 !== 0)
  13820. return;
  13821. this._gl.uniform4iv(uniform, array);
  13822. };
  13823. /**
  13824. * Set the value of an uniform to an array of float32
  13825. * @param uniform defines the webGL uniform location where to store the value
  13826. * @param array defines the array of float32 to store
  13827. */
  13828. Engine.prototype.setFloatArray = function (uniform, array) {
  13829. if (!uniform)
  13830. return;
  13831. this._gl.uniform1fv(uniform, array);
  13832. };
  13833. /**
  13834. * Set the value of an uniform to an array of float32 (stored as vec2)
  13835. * @param uniform defines the webGL uniform location where to store the value
  13836. * @param array defines the array of float32 to store
  13837. */
  13838. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13839. if (!uniform || array.length % 2 !== 0)
  13840. return;
  13841. this._gl.uniform2fv(uniform, array);
  13842. };
  13843. /**
  13844. * Set the value of an uniform to an array of float32 (stored as vec3)
  13845. * @param uniform defines the webGL uniform location where to store the value
  13846. * @param array defines the array of float32 to store
  13847. */
  13848. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13849. if (!uniform || array.length % 3 !== 0)
  13850. return;
  13851. this._gl.uniform3fv(uniform, array);
  13852. };
  13853. /**
  13854. * Set the value of an uniform to an array of float32 (stored as vec4)
  13855. * @param uniform defines the webGL uniform location where to store the value
  13856. * @param array defines the array of float32 to store
  13857. */
  13858. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13859. if (!uniform || array.length % 4 !== 0)
  13860. return;
  13861. this._gl.uniform4fv(uniform, array);
  13862. };
  13863. /**
  13864. * Set the value of an uniform to an array of number
  13865. * @param uniform defines the webGL uniform location where to store the value
  13866. * @param array defines the array of number to store
  13867. */
  13868. Engine.prototype.setArray = function (uniform, array) {
  13869. if (!uniform)
  13870. return;
  13871. this._gl.uniform1fv(uniform, array);
  13872. };
  13873. /**
  13874. * Set the value of an uniform to an array of number (stored as vec2)
  13875. * @param uniform defines the webGL uniform location where to store the value
  13876. * @param array defines the array of number to store
  13877. */
  13878. Engine.prototype.setArray2 = function (uniform, array) {
  13879. if (!uniform || array.length % 2 !== 0)
  13880. return;
  13881. this._gl.uniform2fv(uniform, array);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to an array of number (stored as vec3)
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param array defines the array of number to store
  13887. */
  13888. Engine.prototype.setArray3 = function (uniform, array) {
  13889. if (!uniform || array.length % 3 !== 0)
  13890. return;
  13891. this._gl.uniform3fv(uniform, array);
  13892. };
  13893. /**
  13894. * Set the value of an uniform to an array of number (stored as vec4)
  13895. * @param uniform defines the webGL uniform location where to store the value
  13896. * @param array defines the array of number to store
  13897. */
  13898. Engine.prototype.setArray4 = function (uniform, array) {
  13899. if (!uniform || array.length % 4 !== 0)
  13900. return;
  13901. this._gl.uniform4fv(uniform, array);
  13902. };
  13903. /**
  13904. * Set the value of an uniform to an array of float32 (stored as matrices)
  13905. * @param uniform defines the webGL uniform location where to store the value
  13906. * @param matrices defines the array of float32 to store
  13907. */
  13908. Engine.prototype.setMatrices = function (uniform, matrices) {
  13909. if (!uniform)
  13910. return;
  13911. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13912. };
  13913. /**
  13914. * Set the value of an uniform to a matrix
  13915. * @param uniform defines the webGL uniform location where to store the value
  13916. * @param matrix defines the matrix to store
  13917. */
  13918. Engine.prototype.setMatrix = function (uniform, matrix) {
  13919. if (!uniform)
  13920. return;
  13921. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13922. };
  13923. /**
  13924. * Set the value of an uniform to a matrix (3x3)
  13925. * @param uniform defines the webGL uniform location where to store the value
  13926. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13927. */
  13928. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13929. if (!uniform)
  13930. return;
  13931. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13932. };
  13933. /**
  13934. * Set the value of an uniform to a matrix (2x2)
  13935. * @param uniform defines the webGL uniform location where to store the value
  13936. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13937. */
  13938. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13939. if (!uniform)
  13940. return;
  13941. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13942. };
  13943. /**
  13944. * Set the value of an uniform to a number (int)
  13945. * @param uniform defines the webGL uniform location where to store the value
  13946. * @param value defines the int number to store
  13947. */
  13948. Engine.prototype.setInt = function (uniform, value) {
  13949. if (!uniform)
  13950. return;
  13951. this._gl.uniform1i(uniform, value);
  13952. };
  13953. /**
  13954. * Set the value of an uniform to a number (float)
  13955. * @param uniform defines the webGL uniform location where to store the value
  13956. * @param value defines the float number to store
  13957. */
  13958. Engine.prototype.setFloat = function (uniform, value) {
  13959. if (!uniform)
  13960. return;
  13961. this._gl.uniform1f(uniform, value);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to a vec2
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param x defines the 1st component of the value
  13967. * @param y defines the 2nd component of the value
  13968. */
  13969. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13970. if (!uniform)
  13971. return;
  13972. this._gl.uniform2f(uniform, x, y);
  13973. };
  13974. /**
  13975. * Set the value of an uniform to a vec3
  13976. * @param uniform defines the webGL uniform location where to store the value
  13977. * @param x defines the 1st component of the value
  13978. * @param y defines the 2nd component of the value
  13979. * @param z defines the 3rd component of the value
  13980. */
  13981. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13982. if (!uniform)
  13983. return;
  13984. this._gl.uniform3f(uniform, x, y, z);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to a boolean
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param bool defines the boolean to store
  13990. */
  13991. Engine.prototype.setBool = function (uniform, bool) {
  13992. if (!uniform)
  13993. return;
  13994. this._gl.uniform1i(uniform, bool);
  13995. };
  13996. /**
  13997. * Set the value of an uniform to a vec4
  13998. * @param uniform defines the webGL uniform location where to store the value
  13999. * @param x defines the 1st component of the value
  14000. * @param y defines the 2nd component of the value
  14001. * @param z defines the 3rd component of the value
  14002. * @param w defines the 4th component of the value
  14003. */
  14004. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14005. if (!uniform)
  14006. return;
  14007. this._gl.uniform4f(uniform, x, y, z, w);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to a Color3
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param color3 defines the color to store
  14013. */
  14014. Engine.prototype.setColor3 = function (uniform, color3) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to a Color3 and an alpha value
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param color3 defines the color to store
  14023. * @param alpha defines the alpha component to store
  14024. */
  14025. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14026. if (!uniform)
  14027. return;
  14028. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14029. };
  14030. /**
  14031. * Sets a Color4 on a uniform variable
  14032. * @param uniform defines the uniform location
  14033. * @param color4 defines the value to be set
  14034. */
  14035. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14036. if (!uniform)
  14037. return;
  14038. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14039. };
  14040. // States
  14041. /**
  14042. * Set various states to the webGL context
  14043. * @param culling defines backface culling state
  14044. * @param zOffset defines the value to apply to zOffset (0 by default)
  14045. * @param force defines if states must be applied even if cache is up to date
  14046. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14047. */
  14048. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14049. if (zOffset === void 0) { zOffset = 0; }
  14050. if (reverseSide === void 0) { reverseSide = false; }
  14051. // Culling
  14052. if (this._depthCullingState.cull !== culling || force) {
  14053. this._depthCullingState.cull = culling;
  14054. }
  14055. // Cull face
  14056. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14057. if (this._depthCullingState.cullFace !== cullFace || force) {
  14058. this._depthCullingState.cullFace = cullFace;
  14059. }
  14060. // Z offset
  14061. this.setZOffset(zOffset);
  14062. // Front face
  14063. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14064. if (this._depthCullingState.frontFace !== frontFace || force) {
  14065. this._depthCullingState.frontFace = frontFace;
  14066. }
  14067. };
  14068. /**
  14069. * Set the z offset to apply to current rendering
  14070. * @param value defines the offset to apply
  14071. */
  14072. Engine.prototype.setZOffset = function (value) {
  14073. this._depthCullingState.zOffset = value;
  14074. };
  14075. /**
  14076. * Gets the current value of the zOffset
  14077. * @returns the current zOffset state
  14078. */
  14079. Engine.prototype.getZOffset = function () {
  14080. return this._depthCullingState.zOffset;
  14081. };
  14082. /**
  14083. * Enable or disable depth buffering
  14084. * @param enable defines the state to set
  14085. */
  14086. Engine.prototype.setDepthBuffer = function (enable) {
  14087. this._depthCullingState.depthTest = enable;
  14088. };
  14089. /**
  14090. * Gets a boolean indicating if depth writing is enabled
  14091. * @returns the current depth writing state
  14092. */
  14093. Engine.prototype.getDepthWrite = function () {
  14094. return this._depthCullingState.depthMask;
  14095. };
  14096. /**
  14097. * Enable or disable depth writing
  14098. * @param enable defines the state to set
  14099. */
  14100. Engine.prototype.setDepthWrite = function (enable) {
  14101. this._depthCullingState.depthMask = enable;
  14102. };
  14103. /**
  14104. * Enable or disable color writing
  14105. * @param enable defines the state to set
  14106. */
  14107. Engine.prototype.setColorWrite = function (enable) {
  14108. this._gl.colorMask(enable, enable, enable, enable);
  14109. this._colorWrite = enable;
  14110. };
  14111. /**
  14112. * Gets a boolean indicating if color writing is enabled
  14113. * @returns the current color writing state
  14114. */
  14115. Engine.prototype.getColorWrite = function () {
  14116. return this._colorWrite;
  14117. };
  14118. /**
  14119. * Sets alpha constants used by some alpha blending modes
  14120. * @param r defines the red component
  14121. * @param g defines the green component
  14122. * @param b defines the blue component
  14123. * @param a defines the alpha component
  14124. */
  14125. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14126. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14127. };
  14128. /**
  14129. * Sets the current alpha mode
  14130. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14131. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14132. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14133. */
  14134. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14135. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14136. if (this._alphaMode === mode) {
  14137. return;
  14138. }
  14139. switch (mode) {
  14140. case Engine.ALPHA_DISABLE:
  14141. this._alphaState.alphaBlend = false;
  14142. break;
  14143. case Engine.ALPHA_PREMULTIPLIED:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_COMBINE:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_ONEONE:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. case Engine.ALPHA_ADD:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_SUBTRACT:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_MULTIPLY:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_MAXIMIZED:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. case Engine.ALPHA_INTERPOLATE:
  14176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14177. this._alphaState.alphaBlend = true;
  14178. break;
  14179. case Engine.ALPHA_SCREENMODE:
  14180. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14181. this._alphaState.alphaBlend = true;
  14182. break;
  14183. }
  14184. if (!noDepthWriteChange) {
  14185. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14186. }
  14187. this._alphaMode = mode;
  14188. };
  14189. /**
  14190. * Gets the current alpha mode
  14191. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14192. * @returns the current alpha mode
  14193. */
  14194. Engine.prototype.getAlphaMode = function () {
  14195. return this._alphaMode;
  14196. };
  14197. // Textures
  14198. /**
  14199. * Clears the list of texture accessible through engine.
  14200. * This can help preventing texture load conflict due to name collision.
  14201. */
  14202. Engine.prototype.clearInternalTexturesCache = function () {
  14203. this._internalTexturesCache = [];
  14204. };
  14205. /**
  14206. * Force the entire cache to be cleared
  14207. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14208. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14209. */
  14210. Engine.prototype.wipeCaches = function (bruteForce) {
  14211. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14212. return;
  14213. }
  14214. this._currentEffect = null;
  14215. this._unpackFlipYCached = null;
  14216. this._viewportCached.x = 0;
  14217. this._viewportCached.y = 0;
  14218. this._viewportCached.z = 0;
  14219. this._viewportCached.w = 0;
  14220. if (bruteForce) {
  14221. this.resetTextureCache();
  14222. this._currentProgram = null;
  14223. this._stencilState.reset();
  14224. this._depthCullingState.reset();
  14225. this.setDepthFunctionToLessOrEqual();
  14226. this._alphaState.reset();
  14227. }
  14228. this._resetVertexBufferBinding();
  14229. this._cachedIndexBuffer = null;
  14230. this._cachedEffectForVertexBuffers = null;
  14231. this._unbindVertexArrayObject();
  14232. this.bindIndexBuffer(null);
  14233. };
  14234. /**
  14235. * Set the compressed texture format to use, based on the formats you have, and the formats
  14236. * supported by the hardware / browser.
  14237. *
  14238. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14239. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14240. * to API arguments needed to compressed textures. This puts the burden on the container
  14241. * generator to house the arcane code for determining these for current & future formats.
  14242. *
  14243. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14244. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14245. *
  14246. * Note: The result of this call is not taken into account when a texture is base64.
  14247. *
  14248. * @param formatsAvailable defines the list of those format families you have created
  14249. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14250. *
  14251. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14252. * @returns The extension selected.
  14253. */
  14254. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14255. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14256. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14257. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14258. return this._textureFormatInUse = this._texturesSupported[i];
  14259. }
  14260. }
  14261. }
  14262. // actively set format to nothing, to allow this to be called more than once
  14263. // and possibly fail the 2nd time
  14264. this._textureFormatInUse = null;
  14265. return null;
  14266. };
  14267. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14268. var gl = this._gl;
  14269. var magFilter = gl.NEAREST;
  14270. var minFilter = gl.NEAREST;
  14271. switch (samplingMode) {
  14272. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14273. magFilter = gl.LINEAR;
  14274. if (generateMipMaps) {
  14275. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14276. }
  14277. else {
  14278. minFilter = gl.LINEAR;
  14279. }
  14280. break;
  14281. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14282. magFilter = gl.LINEAR;
  14283. if (generateMipMaps) {
  14284. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14285. }
  14286. else {
  14287. minFilter = gl.LINEAR;
  14288. }
  14289. break;
  14290. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14291. magFilter = gl.NEAREST;
  14292. if (generateMipMaps) {
  14293. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14294. }
  14295. else {
  14296. minFilter = gl.NEAREST;
  14297. }
  14298. break;
  14299. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14300. magFilter = gl.NEAREST;
  14301. if (generateMipMaps) {
  14302. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14303. }
  14304. else {
  14305. minFilter = gl.NEAREST;
  14306. }
  14307. break;
  14308. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14309. magFilter = gl.NEAREST;
  14310. if (generateMipMaps) {
  14311. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14312. }
  14313. else {
  14314. minFilter = gl.LINEAR;
  14315. }
  14316. break;
  14317. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14318. magFilter = gl.NEAREST;
  14319. if (generateMipMaps) {
  14320. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14321. }
  14322. else {
  14323. minFilter = gl.LINEAR;
  14324. }
  14325. break;
  14326. case Engine.TEXTURE_NEAREST_LINEAR:
  14327. magFilter = gl.NEAREST;
  14328. minFilter = gl.LINEAR;
  14329. break;
  14330. case Engine.TEXTURE_NEAREST_NEAREST:
  14331. magFilter = gl.NEAREST;
  14332. minFilter = gl.NEAREST;
  14333. break;
  14334. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14335. magFilter = gl.LINEAR;
  14336. if (generateMipMaps) {
  14337. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14338. }
  14339. else {
  14340. minFilter = gl.NEAREST;
  14341. }
  14342. break;
  14343. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14344. magFilter = gl.LINEAR;
  14345. if (generateMipMaps) {
  14346. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14347. }
  14348. else {
  14349. minFilter = gl.NEAREST;
  14350. }
  14351. break;
  14352. case Engine.TEXTURE_LINEAR_LINEAR:
  14353. magFilter = gl.LINEAR;
  14354. minFilter = gl.LINEAR;
  14355. break;
  14356. case Engine.TEXTURE_LINEAR_NEAREST:
  14357. magFilter = gl.LINEAR;
  14358. minFilter = gl.NEAREST;
  14359. break;
  14360. }
  14361. return {
  14362. min: minFilter,
  14363. mag: magFilter
  14364. };
  14365. };
  14366. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14367. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14368. var img;
  14369. var onload = function () {
  14370. loadedImages[index] = img;
  14371. loadedImages._internalCount++;
  14372. if (scene) {
  14373. scene._removePendingData(img);
  14374. }
  14375. if (loadedImages._internalCount === 6) {
  14376. onfinish(loadedImages);
  14377. }
  14378. };
  14379. var onerror = function (message, exception) {
  14380. if (scene) {
  14381. scene._removePendingData(img);
  14382. }
  14383. if (onErrorCallBack) {
  14384. onErrorCallBack(message, exception);
  14385. }
  14386. };
  14387. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14388. if (scene) {
  14389. scene._addPendingData(img);
  14390. }
  14391. };
  14392. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14393. if (onError === void 0) { onError = null; }
  14394. var loadedImages = [];
  14395. loadedImages._internalCount = 0;
  14396. for (var index = 0; index < 6; index++) {
  14397. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14398. }
  14399. };
  14400. ;
  14401. /** @hidden */
  14402. Engine.prototype._createTexture = function () {
  14403. var texture = this._gl.createTexture();
  14404. if (!texture) {
  14405. throw new Error("Unable to create texture");
  14406. }
  14407. return texture;
  14408. };
  14409. /**
  14410. * Usually called from BABYLON.Texture.ts.
  14411. * Passed information to create a WebGLTexture
  14412. * @param urlArg defines a value which contains one of the following:
  14413. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14414. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14415. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14416. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14417. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14418. * @param scene needed for loading to the correct scene
  14419. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14420. * @param onLoad optional callback to be called upon successful completion
  14421. * @param onError optional callback to be called upon failure
  14422. * @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
  14423. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14424. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14425. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14426. */
  14427. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14428. var _this = this;
  14429. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14430. if (onLoad === void 0) { onLoad = null; }
  14431. if (onError === void 0) { onError = null; }
  14432. if (buffer === void 0) { buffer = null; }
  14433. if (fallback === void 0) { fallback = null; }
  14434. if (format === void 0) { format = null; }
  14435. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14436. var fromData = url.substr(0, 5) === "data:";
  14437. var fromBlob = url.substr(0, 5) === "blob:";
  14438. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14439. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14440. // establish the file extension, if possible
  14441. var lastDot = url.lastIndexOf('.');
  14442. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14443. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14444. var isTGA = (extension.indexOf(".tga") === 0);
  14445. // determine if a ktx file should be substituted
  14446. var isKTX = false;
  14447. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14448. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14449. isKTX = true;
  14450. }
  14451. if (scene) {
  14452. scene._addPendingData(texture);
  14453. }
  14454. texture.url = url;
  14455. texture.generateMipMaps = !noMipmap;
  14456. texture.samplingMode = samplingMode;
  14457. texture.invertY = invertY;
  14458. if (!this._doNotHandleContextLost) {
  14459. // Keep a link to the buffer only if we plan to handle context lost
  14460. texture._buffer = buffer;
  14461. }
  14462. var onLoadObserver = null;
  14463. if (onLoad && !fallback) {
  14464. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14465. }
  14466. if (!fallback)
  14467. this._internalTexturesCache.push(texture);
  14468. var onerror = function (message, exception) {
  14469. if (scene) {
  14470. scene._removePendingData(texture);
  14471. }
  14472. if (onLoadObserver && !isKTX) {
  14473. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14474. texture.onLoadedObservable.remove(onLoadObserver);
  14475. }
  14476. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14477. if (isKTX) {
  14478. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14479. }
  14480. else if (BABYLON.Tools.UseFallbackTexture) {
  14481. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14482. }
  14483. if (onError) {
  14484. onError(message || "Unknown error", exception);
  14485. }
  14486. };
  14487. var callback = null;
  14488. // processing for non-image formats
  14489. if (isKTX || isTGA || isDDS) {
  14490. if (isKTX) {
  14491. callback = function (data) {
  14492. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14493. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14494. ktx.uploadLevels(texture, !noMipmap);
  14495. return false;
  14496. }, samplingMode);
  14497. };
  14498. }
  14499. else if (isTGA) {
  14500. callback = function (arrayBuffer) {
  14501. var data = new Uint8Array(arrayBuffer);
  14502. var header = BABYLON.TGATools.GetTGAHeader(data);
  14503. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14504. BABYLON.TGATools.UploadContent(texture, data);
  14505. return false;
  14506. }, samplingMode);
  14507. };
  14508. }
  14509. else if (isDDS) {
  14510. callback = function (data) {
  14511. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14512. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14513. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14514. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14515. return false;
  14516. }, samplingMode);
  14517. };
  14518. }
  14519. if (!buffer) {
  14520. this._loadFile(url, function (data) {
  14521. if (callback) {
  14522. callback(data);
  14523. }
  14524. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14525. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14526. });
  14527. }
  14528. else {
  14529. if (callback) {
  14530. callback(buffer);
  14531. }
  14532. }
  14533. // image format processing
  14534. }
  14535. else {
  14536. var onload = function (img) {
  14537. if (fromBlob && !_this._doNotHandleContextLost) {
  14538. // We need to store the image if we need to rebuild the texture
  14539. // in case of a webgl context lost
  14540. texture._buffer = img;
  14541. }
  14542. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14543. var gl = _this._gl;
  14544. var isPot = (img.width === potWidth && img.height === potHeight);
  14545. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14546. if (isPot) {
  14547. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14548. return false;
  14549. }
  14550. var maxTextureSize = _this._caps.maxTextureSize;
  14551. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14552. _this._prepareWorkingCanvas();
  14553. if (!_this._workingCanvas || !_this._workingContext) {
  14554. return false;
  14555. }
  14556. _this._workingCanvas.width = potWidth;
  14557. _this._workingCanvas.height = potHeight;
  14558. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14559. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14560. texture.width = potWidth;
  14561. texture.height = potHeight;
  14562. return false;
  14563. }
  14564. else {
  14565. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14566. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14567. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14568. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14571. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14573. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14574. _this._releaseTexture(source_1);
  14575. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14576. continuationCallback();
  14577. });
  14578. }
  14579. return true;
  14580. }, samplingMode);
  14581. };
  14582. if (!fromData || isBase64) {
  14583. if (buffer instanceof HTMLImageElement) {
  14584. onload(buffer);
  14585. }
  14586. else {
  14587. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14588. }
  14589. }
  14590. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14592. }
  14593. else {
  14594. onload(buffer);
  14595. }
  14596. }
  14597. return texture;
  14598. };
  14599. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14600. var _this = this;
  14601. var rtt = this.createRenderTargetTexture({
  14602. width: destination.width,
  14603. height: destination.height,
  14604. }, {
  14605. generateMipMaps: false,
  14606. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14607. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14608. generateDepthBuffer: false,
  14609. generateStencilBuffer: false
  14610. });
  14611. if (!this._rescalePostProcess) {
  14612. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14613. }
  14614. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14615. _this._rescalePostProcess.onApply = function (effect) {
  14616. effect._bindTexture("textureSampler", source);
  14617. };
  14618. var hostingScene = scene;
  14619. if (!hostingScene) {
  14620. hostingScene = _this.scenes[_this.scenes.length - 1];
  14621. }
  14622. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14623. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14624. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14625. _this.unBindFramebuffer(rtt);
  14626. _this._releaseTexture(rtt);
  14627. if (onComplete) {
  14628. onComplete();
  14629. }
  14630. });
  14631. };
  14632. /**
  14633. * Update a raw texture
  14634. * @param texture defines the texture to update
  14635. * @param data defines the data to store in the texture
  14636. * @param format defines the format of the data
  14637. * @param invertY defines if data must be stored with Y axis inverted
  14638. * @param compression defines the compression used (null by default)
  14639. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14640. */
  14641. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14642. if (compression === void 0) { compression = null; }
  14643. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14644. if (!texture) {
  14645. return;
  14646. }
  14647. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14648. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14649. // babylon's internalFormat but gl's texImage2D format
  14650. var internalFormat = this._getInternalFormat(format);
  14651. var textureType = this._getWebGLTextureType(type);
  14652. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14653. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14654. if (!this._doNotHandleContextLost) {
  14655. texture._bufferView = data;
  14656. texture.format = format;
  14657. texture.type = type;
  14658. texture.invertY = invertY;
  14659. texture._compression = compression;
  14660. }
  14661. if (texture.width % 4 !== 0) {
  14662. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14663. }
  14664. if (compression && data) {
  14665. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14666. }
  14667. else {
  14668. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14669. }
  14670. if (texture.generateMipMaps) {
  14671. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14672. }
  14673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14674. // this.resetTextureCache();
  14675. texture.isReady = true;
  14676. };
  14677. /**
  14678. * Creates a raw texture
  14679. * @param data defines the data to store in the texture
  14680. * @param width defines the width of the texture
  14681. * @param height defines the height of the texture
  14682. * @param format defines the format of the data
  14683. * @param generateMipMaps defines if the engine should generate the mip levels
  14684. * @param invertY defines if data must be stored with Y axis inverted
  14685. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14686. * @param compression defines the compression used (null by default)
  14687. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14688. * @returns the raw texture inside an InternalTexture
  14689. */
  14690. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14691. if (compression === void 0) { compression = null; }
  14692. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14693. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14694. texture.baseWidth = width;
  14695. texture.baseHeight = height;
  14696. texture.width = width;
  14697. texture.height = height;
  14698. texture.format = format;
  14699. texture.generateMipMaps = generateMipMaps;
  14700. texture.samplingMode = samplingMode;
  14701. texture.invertY = invertY;
  14702. texture._compression = compression;
  14703. texture.type = type;
  14704. if (!this._doNotHandleContextLost) {
  14705. texture._bufferView = data;
  14706. }
  14707. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14709. // Filters
  14710. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14711. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14713. if (generateMipMaps) {
  14714. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14715. }
  14716. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14717. this._internalTexturesCache.push(texture);
  14718. return texture;
  14719. };
  14720. /** @hidden */
  14721. Engine.prototype._unpackFlipY = function (value) {
  14722. if (this._unpackFlipYCached !== value) {
  14723. this._unpackFlipYCached = value;
  14724. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14725. }
  14726. };
  14727. /** @hidden */
  14728. Engine.prototype._getUnpackAlignement = function () {
  14729. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14730. };
  14731. /**
  14732. * Creates a dynamic texture
  14733. * @param width defines the width of the texture
  14734. * @param height defines the height of the texture
  14735. * @param generateMipMaps defines if the engine should generate the mip levels
  14736. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14737. * @returns the dynamic texture inside an InternalTexture
  14738. */
  14739. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14741. texture.baseWidth = width;
  14742. texture.baseHeight = height;
  14743. if (generateMipMaps) {
  14744. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14745. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14746. }
  14747. // this.resetTextureCache();
  14748. texture.width = width;
  14749. texture.height = height;
  14750. texture.isReady = false;
  14751. texture.generateMipMaps = generateMipMaps;
  14752. texture.samplingMode = samplingMode;
  14753. this.updateTextureSamplingMode(samplingMode, texture);
  14754. this._internalTexturesCache.push(texture);
  14755. return texture;
  14756. };
  14757. /**
  14758. * Update the sampling mode of a given texture
  14759. * @param samplingMode defines the required sampling mode
  14760. * @param texture defines the texture to update
  14761. */
  14762. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14763. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14764. if (texture.isCube) {
  14765. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14767. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14768. }
  14769. else if (texture.is3D) {
  14770. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14772. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14773. }
  14774. else {
  14775. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14776. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14778. }
  14779. texture.samplingMode = samplingMode;
  14780. };
  14781. /**
  14782. * Update the content of a dynamic texture
  14783. * @param texture defines the texture to update
  14784. * @param canvas defines the canvas containing the source
  14785. * @param invertY defines if data must be stored with Y axis inverted
  14786. * @param premulAlpha defines if alpha is stored as premultiplied
  14787. * @param format defines the format of the data
  14788. */
  14789. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14790. if (premulAlpha === void 0) { premulAlpha = false; }
  14791. if (!texture) {
  14792. return;
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14795. this._unpackFlipY(invertY);
  14796. if (premulAlpha) {
  14797. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14798. }
  14799. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14800. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14801. if (texture.generateMipMaps) {
  14802. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14803. }
  14804. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14805. if (premulAlpha) {
  14806. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14807. }
  14808. texture.isReady = true;
  14809. };
  14810. /**
  14811. * Update a video texture
  14812. * @param texture defines the texture to update
  14813. * @param video defines the video element to use
  14814. * @param invertY defines if data must be stored with Y axis inverted
  14815. */
  14816. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14817. if (!texture || texture._isDisabled) {
  14818. return;
  14819. }
  14820. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14821. this._unpackFlipY(!invertY); // Video are upside down by default
  14822. try {
  14823. // Testing video texture support
  14824. if (this._videoTextureSupported === undefined) {
  14825. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14826. if (this._gl.getError() !== 0) {
  14827. this._videoTextureSupported = false;
  14828. }
  14829. else {
  14830. this._videoTextureSupported = true;
  14831. }
  14832. }
  14833. // Copy video through the current working canvas if video texture is not supported
  14834. if (!this._videoTextureSupported) {
  14835. if (!texture._workingCanvas) {
  14836. texture._workingCanvas = document.createElement("canvas");
  14837. var context = texture._workingCanvas.getContext("2d");
  14838. if (!context) {
  14839. throw new Error("Unable to get 2d context");
  14840. }
  14841. texture._workingContext = context;
  14842. texture._workingCanvas.width = texture.width;
  14843. texture._workingCanvas.height = texture.height;
  14844. }
  14845. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14846. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14847. }
  14848. else {
  14849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14850. }
  14851. if (texture.generateMipMaps) {
  14852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14853. }
  14854. if (!wasPreviouslyBound) {
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14856. }
  14857. // this.resetTextureCache();
  14858. texture.isReady = true;
  14859. }
  14860. catch (ex) {
  14861. // Something unexpected
  14862. // Let's disable the texture
  14863. texture._isDisabled = true;
  14864. }
  14865. };
  14866. /**
  14867. * Updates a depth texture Comparison Mode and Function.
  14868. * If the comparison Function is equal to 0, the mode will be set to none.
  14869. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14870. * @param texture The texture to set the comparison function for
  14871. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14872. */
  14873. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14874. if (this.webGLVersion === 1) {
  14875. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14876. return;
  14877. }
  14878. var gl = this._gl;
  14879. if (texture.isCube) {
  14880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14881. if (comparisonFunction === 0) {
  14882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14884. }
  14885. else {
  14886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14888. }
  14889. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14890. }
  14891. else {
  14892. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14893. if (comparisonFunction === 0) {
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14896. }
  14897. else {
  14898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14900. }
  14901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14902. }
  14903. texture._comparisonFunction = comparisonFunction;
  14904. };
  14905. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14906. var width = size.width || size;
  14907. var height = size.height || size;
  14908. internalTexture.baseWidth = width;
  14909. internalTexture.baseHeight = height;
  14910. internalTexture.width = width;
  14911. internalTexture.height = height;
  14912. internalTexture.isReady = true;
  14913. internalTexture.samples = 1;
  14914. internalTexture.generateMipMaps = false;
  14915. internalTexture._generateDepthBuffer = true;
  14916. internalTexture._generateStencilBuffer = generateStencil;
  14917. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14918. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14919. internalTexture._comparisonFunction = comparisonFunction;
  14920. var gl = this._gl;
  14921. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14922. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14923. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14924. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14925. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14926. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14927. if (comparisonFunction === 0) {
  14928. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14929. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14930. }
  14931. else {
  14932. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14933. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14934. }
  14935. };
  14936. /**
  14937. * Creates a depth stencil texture.
  14938. * This is only available in WebGL 2 or with the depth texture extension available.
  14939. * @param size The size of face edge in the texture.
  14940. * @param options The options defining the texture.
  14941. * @returns The texture
  14942. */
  14943. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14944. if (options.isCube) {
  14945. var width = size.width || size;
  14946. return this._createDepthStencilCubeTexture(width, options);
  14947. }
  14948. else {
  14949. return this._createDepthStencilTexture(size, options);
  14950. }
  14951. };
  14952. /**
  14953. * Creates a depth stencil texture.
  14954. * This is only available in WebGL 2 or with the depth texture extension available.
  14955. * @param size The size of face edge in the texture.
  14956. * @param options The options defining the texture.
  14957. * @returns The texture
  14958. */
  14959. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14960. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14961. if (!this._caps.depthTextureExtension) {
  14962. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14963. return internalTexture;
  14964. }
  14965. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14966. var gl = this._gl;
  14967. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14968. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14969. if (this.webGLVersion > 1) {
  14970. if (internalOptions.generateStencil) {
  14971. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14972. }
  14973. else {
  14974. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14975. }
  14976. }
  14977. else {
  14978. if (internalOptions.generateStencil) {
  14979. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14980. }
  14981. else {
  14982. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14983. }
  14984. }
  14985. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14986. return internalTexture;
  14987. };
  14988. /**
  14989. * Creates a depth stencil cube texture.
  14990. * This is only available in WebGL 2.
  14991. * @param size The size of face edge in the cube texture.
  14992. * @param options The options defining the cube texture.
  14993. * @returns The cube texture
  14994. */
  14995. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14996. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14997. internalTexture.isCube = true;
  14998. if (this.webGLVersion === 1) {
  14999. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15000. return internalTexture;
  15001. }
  15002. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15003. var gl = this._gl;
  15004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15005. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15006. // Create the depth/stencil buffer
  15007. for (var face = 0; face < 6; face++) {
  15008. if (internalOptions.generateStencil) {
  15009. 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);
  15010. }
  15011. else {
  15012. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15013. }
  15014. }
  15015. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15016. return internalTexture;
  15017. };
  15018. /**
  15019. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15020. * @param renderTarget The render target to set the frame buffer for
  15021. */
  15022. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15023. // Create the framebuffer
  15024. var internalTexture = renderTarget.getInternalTexture();
  15025. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15026. return;
  15027. }
  15028. var gl = this._gl;
  15029. var depthStencilTexture = renderTarget.depthStencilTexture;
  15030. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15031. if (depthStencilTexture.isCube) {
  15032. if (depthStencilTexture._generateStencilBuffer) {
  15033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15034. }
  15035. else {
  15036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15037. }
  15038. }
  15039. else {
  15040. if (depthStencilTexture._generateStencilBuffer) {
  15041. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15042. }
  15043. else {
  15044. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15045. }
  15046. }
  15047. this.bindUnboundFramebuffer(null);
  15048. };
  15049. /**
  15050. * Creates a new render target texture
  15051. * @param size defines the size of the texture
  15052. * @param options defines the options used to create the texture
  15053. * @returns a new render target texture stored in an InternalTexture
  15054. */
  15055. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15056. var fullOptions = new RenderTargetCreationOptions();
  15057. if (options !== undefined && typeof options === "object") {
  15058. fullOptions.generateMipMaps = options.generateMipMaps;
  15059. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15060. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15061. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15062. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15063. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15064. }
  15065. else {
  15066. fullOptions.generateMipMaps = options;
  15067. fullOptions.generateDepthBuffer = true;
  15068. fullOptions.generateStencilBuffer = false;
  15069. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15070. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15071. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15072. }
  15073. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15074. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15075. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15076. }
  15077. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15078. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15079. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15080. }
  15081. var gl = this._gl;
  15082. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15083. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15084. var width = size.width || size;
  15085. var height = size.height || size;
  15086. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15087. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15088. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15089. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15090. }
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15095. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15096. // Create the framebuffer
  15097. var currentFrameBuffer = this._currentFramebuffer;
  15098. var framebuffer = gl.createFramebuffer();
  15099. this.bindUnboundFramebuffer(framebuffer);
  15100. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15101. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15102. if (fullOptions.generateMipMaps) {
  15103. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15104. }
  15105. // Unbind
  15106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15107. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15108. this.bindUnboundFramebuffer(currentFrameBuffer);
  15109. texture._framebuffer = framebuffer;
  15110. texture.baseWidth = width;
  15111. texture.baseHeight = height;
  15112. texture.width = width;
  15113. texture.height = height;
  15114. texture.isReady = true;
  15115. texture.samples = 1;
  15116. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15117. texture.samplingMode = fullOptions.samplingMode;
  15118. texture.type = fullOptions.type;
  15119. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15120. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15121. // this.resetTextureCache();
  15122. this._internalTexturesCache.push(texture);
  15123. return texture;
  15124. };
  15125. /**
  15126. * Create a multi render target texture
  15127. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15128. * @param size defines the size of the texture
  15129. * @param options defines the creation options
  15130. * @returns the cube texture as an InternalTexture
  15131. */
  15132. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15133. var generateMipMaps = false;
  15134. var generateDepthBuffer = true;
  15135. var generateStencilBuffer = false;
  15136. var generateDepthTexture = false;
  15137. var textureCount = 1;
  15138. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15139. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15140. var types = new Array();
  15141. var samplingModes = new Array();
  15142. if (options !== undefined) {
  15143. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15144. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15145. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15146. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15147. textureCount = options.textureCount || 1;
  15148. if (options.types) {
  15149. types = options.types;
  15150. }
  15151. if (options.samplingModes) {
  15152. samplingModes = options.samplingModes;
  15153. }
  15154. }
  15155. var gl = this._gl;
  15156. // Create the framebuffer
  15157. var framebuffer = gl.createFramebuffer();
  15158. this.bindUnboundFramebuffer(framebuffer);
  15159. var width = size.width || size;
  15160. var height = size.height || size;
  15161. var textures = [];
  15162. var attachments = [];
  15163. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15164. for (var i = 0; i < textureCount; i++) {
  15165. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15166. var type = types[i] || defaultType;
  15167. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15168. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15169. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15170. }
  15171. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15172. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15173. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15174. }
  15175. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15176. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15177. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15178. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15179. }
  15180. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15181. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15182. textures.push(texture);
  15183. attachments.push(attachment);
  15184. gl.activeTexture(gl["TEXTURE" + i]);
  15185. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15190. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15191. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15192. if (generateMipMaps) {
  15193. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15194. }
  15195. // Unbind
  15196. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15197. texture._framebuffer = framebuffer;
  15198. texture._depthStencilBuffer = depthStencilBuffer;
  15199. texture.baseWidth = width;
  15200. texture.baseHeight = height;
  15201. texture.width = width;
  15202. texture.height = height;
  15203. texture.isReady = true;
  15204. texture.samples = 1;
  15205. texture.generateMipMaps = generateMipMaps;
  15206. texture.samplingMode = samplingMode;
  15207. texture.type = type;
  15208. texture._generateDepthBuffer = generateDepthBuffer;
  15209. texture._generateStencilBuffer = generateStencilBuffer;
  15210. texture._attachments = attachments;
  15211. this._internalTexturesCache.push(texture);
  15212. }
  15213. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15214. // Depth texture
  15215. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15216. gl.activeTexture(gl.TEXTURE0);
  15217. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15222. 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);
  15223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15224. depthTexture._framebuffer = framebuffer;
  15225. depthTexture.baseWidth = width;
  15226. depthTexture.baseHeight = height;
  15227. depthTexture.width = width;
  15228. depthTexture.height = height;
  15229. depthTexture.isReady = true;
  15230. depthTexture.samples = 1;
  15231. depthTexture.generateMipMaps = generateMipMaps;
  15232. depthTexture.samplingMode = gl.NEAREST;
  15233. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15234. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15235. textures.push(depthTexture);
  15236. this._internalTexturesCache.push(depthTexture);
  15237. }
  15238. gl.drawBuffers(attachments);
  15239. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15240. this.bindUnboundFramebuffer(null);
  15241. this.resetTextureCache();
  15242. return textures;
  15243. };
  15244. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15245. if (samples === void 0) { samples = 1; }
  15246. var depthStencilBuffer = null;
  15247. var gl = this._gl;
  15248. // Create the depth/stencil buffer
  15249. if (generateStencilBuffer) {
  15250. depthStencilBuffer = gl.createRenderbuffer();
  15251. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15252. if (samples > 1) {
  15253. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15254. }
  15255. else {
  15256. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15257. }
  15258. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15259. }
  15260. else if (generateDepthBuffer) {
  15261. depthStencilBuffer = gl.createRenderbuffer();
  15262. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15263. if (samples > 1) {
  15264. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15265. }
  15266. else {
  15267. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15268. }
  15269. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15270. }
  15271. return depthStencilBuffer;
  15272. };
  15273. /**
  15274. * Updates the sample count of a render target texture
  15275. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15276. * @param texture defines the texture to update
  15277. * @param samples defines the sample count to set
  15278. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15279. */
  15280. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15281. if (this.webGLVersion < 2 || !texture) {
  15282. return 1;
  15283. }
  15284. if (texture.samples === samples) {
  15285. return samples;
  15286. }
  15287. var gl = this._gl;
  15288. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15289. // Dispose previous render buffers
  15290. if (texture._depthStencilBuffer) {
  15291. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15292. texture._depthStencilBuffer = null;
  15293. }
  15294. if (texture._MSAAFramebuffer) {
  15295. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15296. texture._MSAAFramebuffer = null;
  15297. }
  15298. if (texture._MSAARenderBuffer) {
  15299. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15300. texture._MSAARenderBuffer = null;
  15301. }
  15302. if (samples > 1) {
  15303. var framebuffer = gl.createFramebuffer();
  15304. if (!framebuffer) {
  15305. throw new Error("Unable to create multi sampled framebuffer");
  15306. }
  15307. texture._MSAAFramebuffer = framebuffer;
  15308. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15309. var colorRenderbuffer = gl.createRenderbuffer();
  15310. if (!colorRenderbuffer) {
  15311. throw new Error("Unable to create multi sampled framebuffer");
  15312. }
  15313. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15314. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15315. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15316. texture._MSAARenderBuffer = colorRenderbuffer;
  15317. }
  15318. else {
  15319. this.bindUnboundFramebuffer(texture._framebuffer);
  15320. }
  15321. texture.samples = samples;
  15322. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15323. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15324. this.bindUnboundFramebuffer(null);
  15325. return samples;
  15326. };
  15327. /**
  15328. * Update the sample count for a given multiple render target texture
  15329. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15330. * @param textures defines the textures to update
  15331. * @param samples defines the sample count to set
  15332. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15333. */
  15334. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15335. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15336. return 1;
  15337. }
  15338. if (textures[0].samples === samples) {
  15339. return samples;
  15340. }
  15341. var gl = this._gl;
  15342. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15343. // Dispose previous render buffers
  15344. if (textures[0]._depthStencilBuffer) {
  15345. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15346. textures[0]._depthStencilBuffer = null;
  15347. }
  15348. if (textures[0]._MSAAFramebuffer) {
  15349. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15350. textures[0]._MSAAFramebuffer = null;
  15351. }
  15352. for (var i = 0; i < textures.length; i++) {
  15353. if (textures[i]._MSAARenderBuffer) {
  15354. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15355. textures[i]._MSAARenderBuffer = null;
  15356. }
  15357. }
  15358. if (samples > 1) {
  15359. var framebuffer = gl.createFramebuffer();
  15360. if (!framebuffer) {
  15361. throw new Error("Unable to create multi sampled framebuffer");
  15362. }
  15363. this.bindUnboundFramebuffer(framebuffer);
  15364. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15365. var attachments = [];
  15366. for (var i = 0; i < textures.length; i++) {
  15367. var texture = textures[i];
  15368. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15369. var colorRenderbuffer = gl.createRenderbuffer();
  15370. if (!colorRenderbuffer) {
  15371. throw new Error("Unable to create multi sampled framebuffer");
  15372. }
  15373. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15374. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15375. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15376. texture._MSAAFramebuffer = framebuffer;
  15377. texture._MSAARenderBuffer = colorRenderbuffer;
  15378. texture.samples = samples;
  15379. texture._depthStencilBuffer = depthStencilBuffer;
  15380. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15381. attachments.push(attachment);
  15382. }
  15383. gl.drawBuffers(attachments);
  15384. }
  15385. else {
  15386. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15387. }
  15388. this.bindUnboundFramebuffer(null);
  15389. return samples;
  15390. };
  15391. /** @hidden */
  15392. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15393. if (faceIndex === void 0) { faceIndex = 0; }
  15394. if (lod === void 0) { lod = 0; }
  15395. var gl = this._gl;
  15396. var target = gl.TEXTURE_2D;
  15397. if (texture.isCube) {
  15398. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15399. }
  15400. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15401. };
  15402. /** @hidden */
  15403. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15404. if (faceIndex === void 0) { faceIndex = 0; }
  15405. if (lod === void 0) { lod = 0; }
  15406. var gl = this._gl;
  15407. var textureType = this._getWebGLTextureType(texture.type);
  15408. var format = this._getInternalFormat(texture.format);
  15409. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15410. this._unpackFlipY(texture.invertY);
  15411. var target = gl.TEXTURE_2D;
  15412. if (texture.isCube) {
  15413. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15414. }
  15415. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15416. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15417. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15418. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15419. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15420. };
  15421. /** @hidden */
  15422. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15423. if (faceIndex === void 0) { faceIndex = 0; }
  15424. if (lod === void 0) { lod = 0; }
  15425. var gl = this._gl;
  15426. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15427. this._bindTextureDirectly(bindTarget, texture, true);
  15428. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15429. this._bindTextureDirectly(bindTarget, null, true);
  15430. };
  15431. /** @hidden */
  15432. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15433. if (faceIndex === void 0) { faceIndex = 0; }
  15434. if (lod === void 0) { lod = 0; }
  15435. var gl = this._gl;
  15436. var textureType = this._getWebGLTextureType(texture.type);
  15437. var format = this._getInternalFormat(texture.format);
  15438. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15439. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15440. this._bindTextureDirectly(bindTarget, texture, true);
  15441. this._unpackFlipY(texture.invertY);
  15442. var target = gl.TEXTURE_2D;
  15443. if (texture.isCube) {
  15444. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15445. }
  15446. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15447. this._bindTextureDirectly(bindTarget, null, true);
  15448. };
  15449. /**
  15450. * Creates a new render target cube texture
  15451. * @param size defines the size of the texture
  15452. * @param options defines the options used to create the texture
  15453. * @returns a new render target cube texture stored in an InternalTexture
  15454. */
  15455. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15456. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15457. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15458. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15459. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15460. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15461. }
  15462. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15463. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15464. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15465. }
  15466. var gl = this._gl;
  15467. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15468. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15469. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15470. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15471. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15472. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15473. }
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15478. for (var face = 0; face < 6; face++) {
  15479. 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);
  15480. }
  15481. // Create the framebuffer
  15482. var framebuffer = gl.createFramebuffer();
  15483. this.bindUnboundFramebuffer(framebuffer);
  15484. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15485. // MipMaps
  15486. if (fullOptions.generateMipMaps) {
  15487. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15488. }
  15489. // Unbind
  15490. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15491. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15492. this.bindUnboundFramebuffer(null);
  15493. texture._framebuffer = framebuffer;
  15494. texture.width = size;
  15495. texture.height = size;
  15496. texture.isReady = true;
  15497. texture.isCube = true;
  15498. texture.samples = 1;
  15499. texture.generateMipMaps = fullOptions.generateMipMaps;
  15500. texture.samplingMode = fullOptions.samplingMode;
  15501. texture.type = fullOptions.type;
  15502. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15503. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15504. this._internalTexturesCache.push(texture);
  15505. return texture;
  15506. };
  15507. /**
  15508. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15509. * @param rootUrl defines the url where the file to load is located
  15510. * @param scene defines the current scene
  15511. * @param lodScale defines scale to apply to the mip map selection
  15512. * @param lodOffset defines offset to apply to the mip map selection
  15513. * @param onLoad defines an optional callback raised when the texture is loaded
  15514. * @param onError defines an optional callback raised if there is an issue to load the texture
  15515. * @param format defines the format of the data
  15516. * @param forcedExtension defines the extension to use to pick the right loader
  15517. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15518. * @returns the cube texture as an InternalTexture
  15519. */
  15520. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15521. var _this = this;
  15522. if (onLoad === void 0) { onLoad = null; }
  15523. if (onError === void 0) { onError = null; }
  15524. if (forcedExtension === void 0) { forcedExtension = null; }
  15525. if (createPolynomials === void 0) { createPolynomials = true; }
  15526. var callback = function (loadData) {
  15527. if (!loadData) {
  15528. if (onLoad) {
  15529. onLoad(null);
  15530. }
  15531. return;
  15532. }
  15533. var texture = loadData.texture;
  15534. if (!createPolynomials) {
  15535. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15536. }
  15537. else if (loadData.info.sphericalPolynomial) {
  15538. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15539. }
  15540. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15541. if (_this._caps.textureLOD) {
  15542. // Do not add extra process if texture lod is supported.
  15543. if (onLoad) {
  15544. onLoad(texture);
  15545. }
  15546. return;
  15547. }
  15548. var mipSlices = 3;
  15549. var gl = _this._gl;
  15550. var width = loadData.width;
  15551. if (!width) {
  15552. return;
  15553. }
  15554. var textures = [];
  15555. for (var i = 0; i < mipSlices; i++) {
  15556. //compute LOD from even spacing in smoothness (matching shader calculation)
  15557. var smoothness = i / (mipSlices - 1);
  15558. var roughness = 1 - smoothness;
  15559. var minLODIndex = lodOffset; // roughness = 0
  15560. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15561. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15562. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15563. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15564. glTextureFromLod.isCube = true;
  15565. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15570. if (loadData.isDDS) {
  15571. var info = loadData.info;
  15572. var data = loadData.data;
  15573. _this._unpackFlipY(info.isCompressed);
  15574. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15575. }
  15576. else {
  15577. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15578. }
  15579. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15580. // Wrap in a base texture for easy binding.
  15581. var lodTexture = new BABYLON.BaseTexture(scene);
  15582. lodTexture.isCube = true;
  15583. lodTexture._texture = glTextureFromLod;
  15584. glTextureFromLod.isReady = true;
  15585. textures.push(lodTexture);
  15586. }
  15587. texture._lodTextureHigh = textures[2];
  15588. texture._lodTextureMid = textures[1];
  15589. texture._lodTextureLow = textures[0];
  15590. if (onLoad) {
  15591. onLoad(texture);
  15592. }
  15593. };
  15594. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15595. };
  15596. /**
  15597. * Creates a cube texture
  15598. * @param rootUrl defines the url where the files to load is located
  15599. * @param scene defines the current scene
  15600. * @param files defines the list of files to load (1 per face)
  15601. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15602. * @param onLoad defines an optional callback raised when the texture is loaded
  15603. * @param onError defines an optional callback raised if there is an issue to load the texture
  15604. * @param format defines the format of the data
  15605. * @param forcedExtension defines the extension to use to pick the right loader
  15606. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15607. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15608. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15609. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15610. * @returns the cube texture as an InternalTexture
  15611. */
  15612. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15613. var _this = this;
  15614. if (onLoad === void 0) { onLoad = null; }
  15615. if (onError === void 0) { onError = null; }
  15616. if (forcedExtension === void 0) { forcedExtension = null; }
  15617. if (createPolynomials === void 0) { createPolynomials = false; }
  15618. if (lodScale === void 0) { lodScale = 0; }
  15619. if (lodOffset === void 0) { lodOffset = 0; }
  15620. if (fallback === void 0) { fallback = null; }
  15621. var gl = this._gl;
  15622. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15623. texture.isCube = true;
  15624. texture.url = rootUrl;
  15625. texture.generateMipMaps = !noMipmap;
  15626. texture._lodGenerationScale = lodScale;
  15627. texture._lodGenerationOffset = lodOffset;
  15628. if (!this._doNotHandleContextLost) {
  15629. texture._extension = forcedExtension;
  15630. texture._files = files;
  15631. }
  15632. var isKTX = false;
  15633. var isDDS = false;
  15634. var isEnv = false;
  15635. var lastDot = rootUrl.lastIndexOf('.');
  15636. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15637. if (this._textureFormatInUse && !fallback) {
  15638. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15639. isKTX = true;
  15640. }
  15641. else {
  15642. isDDS = (extension === ".dds");
  15643. isEnv = (extension === ".env");
  15644. }
  15645. var onerror = function (request, exception) {
  15646. if (isKTX) {
  15647. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15648. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15649. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15650. }
  15651. if (onError && request) {
  15652. onError(request.status + " " + request.statusText, exception);
  15653. }
  15654. };
  15655. if (isKTX) {
  15656. this._loadFile(rootUrl, function (data) {
  15657. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15658. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15659. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15660. _this._unpackFlipY(true);
  15661. ktx.uploadLevels(texture, !noMipmap);
  15662. _this.setCubeMapTextureParams(gl, loadMipmap);
  15663. texture.width = ktx.pixelWidth;
  15664. texture.height = ktx.pixelHeight;
  15665. texture.isReady = true;
  15666. }, undefined, undefined, true, onerror);
  15667. }
  15668. else if (isEnv) {
  15669. this._loadFile(rootUrl, function (data) {
  15670. data = data;
  15671. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15672. if (info) {
  15673. texture.width = info.width;
  15674. texture.height = info.width;
  15675. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15676. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15677. texture.isReady = true;
  15678. if (onLoad) {
  15679. onLoad();
  15680. }
  15681. });
  15682. }
  15683. else if (onError) {
  15684. onError("Can not parse the environment file", null);
  15685. }
  15686. }, undefined, undefined, true, onerror);
  15687. }
  15688. else if (isDDS) {
  15689. if (files && files.length === 6) {
  15690. this._cascadeLoadFiles(scene, function (imgs) {
  15691. var info;
  15692. var loadMipmap = false;
  15693. var width = 0;
  15694. for (var index = 0; index < imgs.length; index++) {
  15695. var data = imgs[index];
  15696. info = BABYLON.DDSTools.GetDDSInfo(data);
  15697. texture.width = info.width;
  15698. texture.height = info.height;
  15699. width = info.width;
  15700. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15701. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15702. _this._unpackFlipY(info.isCompressed);
  15703. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15704. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15705. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15706. }
  15707. }
  15708. _this.setCubeMapTextureParams(gl, loadMipmap);
  15709. texture.isReady = true;
  15710. if (onLoad) {
  15711. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15712. }
  15713. }, files, onError);
  15714. }
  15715. else {
  15716. this._loadFile(rootUrl, function (data) {
  15717. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15718. texture.width = info.width;
  15719. texture.height = info.height;
  15720. if (createPolynomials) {
  15721. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15722. }
  15723. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15724. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15725. _this._unpackFlipY(info.isCompressed);
  15726. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15727. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15728. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15729. }
  15730. _this.setCubeMapTextureParams(gl, loadMipmap);
  15731. texture.isReady = true;
  15732. if (onLoad) {
  15733. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15734. }
  15735. }, undefined, undefined, true, onerror);
  15736. }
  15737. }
  15738. else {
  15739. if (!files) {
  15740. throw new Error("Cannot load cubemap because files were not defined");
  15741. }
  15742. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15743. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15744. var height = width;
  15745. _this._prepareWorkingCanvas();
  15746. if (!_this._workingCanvas || !_this._workingContext) {
  15747. return;
  15748. }
  15749. _this._workingCanvas.width = width;
  15750. _this._workingCanvas.height = height;
  15751. var faces = [
  15752. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15753. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15754. ];
  15755. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15756. _this._unpackFlipY(false);
  15757. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15758. for (var index = 0; index < faces.length; index++) {
  15759. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15760. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15761. }
  15762. if (!noMipmap) {
  15763. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15764. }
  15765. _this.setCubeMapTextureParams(gl, !noMipmap);
  15766. texture.width = width;
  15767. texture.height = height;
  15768. texture.isReady = true;
  15769. if (format) {
  15770. texture.format = format;
  15771. }
  15772. texture.onLoadedObservable.notifyObservers(texture);
  15773. texture.onLoadedObservable.clear();
  15774. if (onLoad) {
  15775. onLoad();
  15776. }
  15777. }, files, onError);
  15778. }
  15779. this._internalTexturesCache.push(texture);
  15780. return texture;
  15781. };
  15782. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  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. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15788. // this.resetTextureCache();
  15789. };
  15790. /**
  15791. * Update a raw cube texture
  15792. * @param texture defines the texture to udpdate
  15793. * @param data defines the data to store
  15794. * @param format defines the data format
  15795. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15796. * @param invertY defines if data must be stored with Y axis inverted
  15797. * @param compression defines the compression used (null by default)
  15798. * @param level defines which level of the texture to update
  15799. */
  15800. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15801. if (compression === void 0) { compression = null; }
  15802. if (level === void 0) { level = 0; }
  15803. texture._bufferViewArray = data;
  15804. texture.format = format;
  15805. texture.type = type;
  15806. texture.invertY = invertY;
  15807. texture._compression = compression;
  15808. var gl = this._gl;
  15809. var textureType = this._getWebGLTextureType(type);
  15810. var internalFormat = this._getInternalFormat(format);
  15811. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15812. var needConversion = false;
  15813. if (internalFormat === gl.RGB) {
  15814. internalFormat = gl.RGBA;
  15815. needConversion = true;
  15816. }
  15817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15818. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15819. if (texture.width % 4 !== 0) {
  15820. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15821. }
  15822. // Data are known to be in +X +Y +Z -X -Y -Z
  15823. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15824. var faceData = data[faceIndex];
  15825. if (compression) {
  15826. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15827. }
  15828. else {
  15829. if (needConversion) {
  15830. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15831. }
  15832. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15833. }
  15834. }
  15835. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15836. if (isPot && texture.generateMipMaps && level === 0) {
  15837. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15838. }
  15839. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15840. // this.resetTextureCache();
  15841. texture.isReady = true;
  15842. };
  15843. /**
  15844. * Creates a new raw cube texture
  15845. * @param data defines the array of data to use to create each face
  15846. * @param size defines the size of the textures
  15847. * @param format defines the format of the data
  15848. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15849. * @param generateMipMaps defines if the engine should generate the mip levels
  15850. * @param invertY defines if data must be stored with Y axis inverted
  15851. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15852. * @param compression defines the compression used (null by default)
  15853. * @returns the cube texture as an InternalTexture
  15854. */
  15855. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15856. if (compression === void 0) { compression = null; }
  15857. var gl = this._gl;
  15858. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15859. texture.isCube = true;
  15860. texture.generateMipMaps = generateMipMaps;
  15861. texture.format = format;
  15862. texture.type = type;
  15863. if (!this._doNotHandleContextLost) {
  15864. texture._bufferViewArray = data;
  15865. }
  15866. var textureType = this._getWebGLTextureType(type);
  15867. var internalFormat = this._getInternalFormat(format);
  15868. if (internalFormat === gl.RGB) {
  15869. internalFormat = gl.RGBA;
  15870. }
  15871. var width = size;
  15872. var height = width;
  15873. texture.width = width;
  15874. texture.height = height;
  15875. // Double check on POT to generate Mips.
  15876. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15877. if (!isPot) {
  15878. generateMipMaps = false;
  15879. }
  15880. // Upload data if needed. The texture won't be ready until then.
  15881. if (data) {
  15882. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15883. }
  15884. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15885. // Filters
  15886. if (data && generateMipMaps) {
  15887. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15888. }
  15889. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15892. }
  15893. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15896. }
  15897. else {
  15898. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15901. }
  15902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15904. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15905. return texture;
  15906. };
  15907. /**
  15908. * Creates a new raw cube texture from a specified url
  15909. * @param url defines the url where the data is located
  15910. * @param scene defines the current scene
  15911. * @param size defines the size of the textures
  15912. * @param format defines the format of the data
  15913. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15914. * @param noMipmap defines if the engine should avoid generating the mip levels
  15915. * @param callback defines a callback used to extract texture data from loaded data
  15916. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15917. * @param onLoad defines a callback called when texture is loaded
  15918. * @param onError defines a callback called if there is an error
  15919. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15920. * @param invertY defines if data must be stored with Y axis inverted
  15921. * @returns the cube texture as an InternalTexture
  15922. */
  15923. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15924. var _this = this;
  15925. if (onLoad === void 0) { onLoad = null; }
  15926. if (onError === void 0) { onError = null; }
  15927. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15928. if (invertY === void 0) { invertY = false; }
  15929. var gl = this._gl;
  15930. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15931. scene._addPendingData(texture);
  15932. texture.url = url;
  15933. this._internalTexturesCache.push(texture);
  15934. var onerror = function (request, exception) {
  15935. scene._removePendingData(texture);
  15936. if (onError && request) {
  15937. onError(request.status + " " + request.statusText, exception);
  15938. }
  15939. };
  15940. var internalCallback = function (data) {
  15941. var width = texture.width;
  15942. var faceDataArrays = callback(data);
  15943. if (!faceDataArrays) {
  15944. return;
  15945. }
  15946. if (mipmapGenerator) {
  15947. var textureType = _this._getWebGLTextureType(type);
  15948. var internalFormat = _this._getInternalFormat(format);
  15949. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15950. var needConversion = false;
  15951. if (internalFormat === gl.RGB) {
  15952. internalFormat = gl.RGBA;
  15953. needConversion = true;
  15954. }
  15955. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15956. _this._unpackFlipY(false);
  15957. var mipData = mipmapGenerator(faceDataArrays);
  15958. for (var level = 0; level < mipData.length; level++) {
  15959. var mipSize = width >> level;
  15960. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15961. var mipFaceData = mipData[level][faceIndex];
  15962. if (needConversion) {
  15963. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15964. }
  15965. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15966. }
  15967. }
  15968. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15969. }
  15970. else {
  15971. texture.generateMipMaps = !noMipmap;
  15972. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15973. texture.generateMipMaps = false;
  15974. }
  15975. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15976. }
  15977. texture.isReady = true;
  15978. // this.resetTextureCache();
  15979. scene._removePendingData(texture);
  15980. if (onLoad) {
  15981. onLoad();
  15982. }
  15983. };
  15984. this._loadFile(url, function (data) {
  15985. internalCallback(data);
  15986. }, undefined, scene.database, true, onerror);
  15987. return texture;
  15988. };
  15989. ;
  15990. /**
  15991. * Update a raw 3D texture
  15992. * @param texture defines the texture to update
  15993. * @param data defines the data to store
  15994. * @param format defines the data format
  15995. * @param invertY defines if data must be stored with Y axis inverted
  15996. * @param compression defines the used compression (can be null)
  15997. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15998. */
  15999. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16000. if (compression === void 0) { compression = null; }
  16001. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16002. var internalType = this._getWebGLTextureType(textureType);
  16003. var internalFormat = this._getInternalFormat(format);
  16004. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16005. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16006. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16007. if (!this._doNotHandleContextLost) {
  16008. texture._bufferView = data;
  16009. texture.format = format;
  16010. texture.invertY = invertY;
  16011. texture._compression = compression;
  16012. }
  16013. if (texture.width % 4 !== 0) {
  16014. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16015. }
  16016. if (compression && data) {
  16017. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16018. }
  16019. else {
  16020. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16021. }
  16022. if (texture.generateMipMaps) {
  16023. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16024. }
  16025. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16026. // this.resetTextureCache();
  16027. texture.isReady = true;
  16028. };
  16029. /**
  16030. * Creates a new raw 3D texture
  16031. * @param data defines the data used to create the texture
  16032. * @param width defines the width of the texture
  16033. * @param height defines the height of the texture
  16034. * @param depth defines the depth of the texture
  16035. * @param format defines the format of the texture
  16036. * @param generateMipMaps defines if the engine must generate mip levels
  16037. * @param invertY defines if data must be stored with Y axis inverted
  16038. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16039. * @param compression defines the compressed used (can be null)
  16040. * @param textureType defines the compressed used (can be null)
  16041. * @returns a new raw 3D texture (stored in an InternalTexture)
  16042. */
  16043. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16044. if (compression === void 0) { compression = null; }
  16045. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16046. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16047. texture.baseWidth = width;
  16048. texture.baseHeight = height;
  16049. texture.baseDepth = depth;
  16050. texture.width = width;
  16051. texture.height = height;
  16052. texture.depth = depth;
  16053. texture.format = format;
  16054. texture.type = textureType;
  16055. texture.generateMipMaps = generateMipMaps;
  16056. texture.samplingMode = samplingMode;
  16057. texture.is3D = true;
  16058. if (!this._doNotHandleContextLost) {
  16059. texture._bufferView = data;
  16060. }
  16061. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16062. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16063. // Filters
  16064. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16065. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16066. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16067. if (generateMipMaps) {
  16068. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16069. }
  16070. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16071. this._internalTexturesCache.push(texture);
  16072. return texture;
  16073. };
  16074. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16075. var gl = this._gl;
  16076. if (!gl) {
  16077. return;
  16078. }
  16079. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16082. if (!noMipmap && !isCompressed) {
  16083. gl.generateMipmap(gl.TEXTURE_2D);
  16084. }
  16085. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16086. // this.resetTextureCache();
  16087. if (scene) {
  16088. scene._removePendingData(texture);
  16089. }
  16090. texture.onLoadedObservable.notifyObservers(texture);
  16091. texture.onLoadedObservable.clear();
  16092. };
  16093. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16094. var _this = this;
  16095. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16096. var maxTextureSize = this.getCaps().maxTextureSize;
  16097. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16098. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16099. var gl = this._gl;
  16100. if (!gl) {
  16101. return;
  16102. }
  16103. if (!texture._webGLTexture) {
  16104. // this.resetTextureCache();
  16105. if (scene) {
  16106. scene._removePendingData(texture);
  16107. }
  16108. return;
  16109. }
  16110. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16111. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16112. texture.baseWidth = width;
  16113. texture.baseHeight = height;
  16114. texture.width = potWidth;
  16115. texture.height = potHeight;
  16116. texture.isReady = true;
  16117. if (processFunction(potWidth, potHeight, function () {
  16118. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16119. })) {
  16120. // Returning as texture needs extra async steps
  16121. return;
  16122. }
  16123. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16124. };
  16125. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16126. // Create new RGBA data container.
  16127. var rgbaData;
  16128. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16129. rgbaData = new Float32Array(width * height * 4);
  16130. }
  16131. else {
  16132. rgbaData = new Uint32Array(width * height * 4);
  16133. }
  16134. // Convert each pixel.
  16135. for (var x = 0; x < width; x++) {
  16136. for (var y = 0; y < height; y++) {
  16137. var index = (y * width + x) * 3;
  16138. var newIndex = (y * width + x) * 4;
  16139. // Map Old Value to new value.
  16140. rgbaData[newIndex + 0] = rgbData[index + 0];
  16141. rgbaData[newIndex + 1] = rgbData[index + 1];
  16142. rgbaData[newIndex + 2] = rgbData[index + 2];
  16143. // Add fully opaque alpha channel.
  16144. rgbaData[newIndex + 3] = 1;
  16145. }
  16146. }
  16147. return rgbaData;
  16148. };
  16149. /** @hidden */
  16150. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16151. var gl = this._gl;
  16152. if (texture._framebuffer) {
  16153. gl.deleteFramebuffer(texture._framebuffer);
  16154. texture._framebuffer = null;
  16155. }
  16156. if (texture._depthStencilBuffer) {
  16157. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16158. texture._depthStencilBuffer = null;
  16159. }
  16160. if (texture._MSAAFramebuffer) {
  16161. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16162. texture._MSAAFramebuffer = null;
  16163. }
  16164. if (texture._MSAARenderBuffer) {
  16165. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16166. texture._MSAARenderBuffer = null;
  16167. }
  16168. };
  16169. /** @hidden */
  16170. Engine.prototype._releaseTexture = function (texture) {
  16171. var gl = this._gl;
  16172. this._releaseFramebufferObjects(texture);
  16173. gl.deleteTexture(texture._webGLTexture);
  16174. // Unbind channels
  16175. this.unbindAllTextures();
  16176. var index = this._internalTexturesCache.indexOf(texture);
  16177. if (index !== -1) {
  16178. this._internalTexturesCache.splice(index, 1);
  16179. }
  16180. // Integrated fixed lod samplers.
  16181. if (texture._lodTextureHigh) {
  16182. texture._lodTextureHigh.dispose();
  16183. }
  16184. if (texture._lodTextureMid) {
  16185. texture._lodTextureMid.dispose();
  16186. }
  16187. if (texture._lodTextureLow) {
  16188. texture._lodTextureLow.dispose();
  16189. }
  16190. // Set output texture of post process to null if the texture has been released/disposed
  16191. this.scenes.forEach(function (scene) {
  16192. scene.postProcesses.forEach(function (postProcess) {
  16193. if (postProcess._outputTexture == texture) {
  16194. postProcess._outputTexture = null;
  16195. }
  16196. });
  16197. scene.cameras.forEach(function (camera) {
  16198. camera._postProcesses.forEach(function (postProcess) {
  16199. if (postProcess) {
  16200. if (postProcess._outputTexture == texture) {
  16201. postProcess._outputTexture = null;
  16202. }
  16203. }
  16204. });
  16205. });
  16206. });
  16207. };
  16208. Engine.prototype.setProgram = function (program) {
  16209. if (this._currentProgram !== program) {
  16210. this._gl.useProgram(program);
  16211. this._currentProgram = program;
  16212. }
  16213. };
  16214. /**
  16215. * Binds an effect to the webGL context
  16216. * @param effect defines the effect to bind
  16217. */
  16218. Engine.prototype.bindSamplers = function (effect) {
  16219. this.setProgram(effect.getProgram());
  16220. var samplers = effect.getSamplers();
  16221. for (var index = 0; index < samplers.length; index++) {
  16222. var uniform = effect.getUniform(samplers[index]);
  16223. if (uniform) {
  16224. this._boundUniforms[index] = uniform;
  16225. }
  16226. }
  16227. this._currentEffect = null;
  16228. };
  16229. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16230. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16231. return;
  16232. }
  16233. // Remove
  16234. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16235. // Bind last to it
  16236. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16237. // Bind to dummy
  16238. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16239. };
  16240. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16241. if (!internalTexture) {
  16242. return -1;
  16243. }
  16244. internalTexture._initialSlot = channel;
  16245. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16246. if (channel !== internalTexture._designatedSlot) {
  16247. this._textureCollisions.addCount(1, false);
  16248. }
  16249. }
  16250. else {
  16251. if (channel !== internalTexture._designatedSlot) {
  16252. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16253. return internalTexture._designatedSlot;
  16254. }
  16255. else {
  16256. // No slot for this texture, let's pick a new one (if we find a free slot)
  16257. if (this._nextFreeTextureSlots.length) {
  16258. return this._nextFreeTextureSlots[0];
  16259. }
  16260. // We need to recycle the oldest bound texture, sorry.
  16261. this._textureCollisions.addCount(1, false);
  16262. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16263. }
  16264. }
  16265. }
  16266. return channel;
  16267. };
  16268. Engine.prototype._linkTrackers = function (previous, next) {
  16269. previous.next = next;
  16270. next.previous = previous;
  16271. };
  16272. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16273. var currentSlot = internalTexture._designatedSlot;
  16274. if (currentSlot === -1) {
  16275. return -1;
  16276. }
  16277. internalTexture._designatedSlot = -1;
  16278. if (this.disableTextureBindingOptimization) {
  16279. return -1;
  16280. }
  16281. // Remove from bound list
  16282. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16283. // Free the slot
  16284. this._boundTexturesCache[currentSlot] = null;
  16285. this._nextFreeTextureSlots.push(currentSlot);
  16286. return currentSlot;
  16287. };
  16288. Engine.prototype._activateCurrentTexture = function () {
  16289. if (this._currentTextureChannel !== this._activeChannel) {
  16290. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16291. this._currentTextureChannel = this._activeChannel;
  16292. }
  16293. };
  16294. /** @hidden */
  16295. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16296. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16297. if (force === void 0) { force = false; }
  16298. var wasPreviouslyBound = false;
  16299. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16300. this._activeChannel = texture._designatedSlot;
  16301. }
  16302. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16303. var isTextureForRendering = texture && texture._initialSlot > -1;
  16304. if (currentTextureBound !== texture || force) {
  16305. if (currentTextureBound) {
  16306. this._removeDesignatedSlot(currentTextureBound);
  16307. }
  16308. this._activateCurrentTexture();
  16309. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16310. this._boundTexturesCache[this._activeChannel] = texture;
  16311. if (texture) {
  16312. if (!this.disableTextureBindingOptimization) {
  16313. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16314. if (slotIndex > -1) {
  16315. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16316. }
  16317. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16318. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16319. }
  16320. texture._designatedSlot = this._activeChannel;
  16321. }
  16322. }
  16323. else if (forTextureDataUpdate) {
  16324. wasPreviouslyBound = true;
  16325. this._activateCurrentTexture();
  16326. }
  16327. if (isTextureForRendering && !forTextureDataUpdate) {
  16328. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16329. }
  16330. return wasPreviouslyBound;
  16331. };
  16332. /** @hidden */
  16333. Engine.prototype._bindTexture = function (channel, texture) {
  16334. if (channel < 0) {
  16335. return;
  16336. }
  16337. if (texture) {
  16338. channel = this._getCorrectTextureChannel(channel, texture);
  16339. }
  16340. this._activeChannel = channel;
  16341. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16342. };
  16343. /**
  16344. * Sets a texture to the webGL context from a postprocess
  16345. * @param channel defines the channel to use
  16346. * @param postProcess defines the source postprocess
  16347. */
  16348. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16349. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16350. };
  16351. /**
  16352. * Binds the output of the passed in post process to the texture channel specified
  16353. * @param channel The channel the texture should be bound to
  16354. * @param postProcess The post process which's output should be bound
  16355. */
  16356. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16357. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16358. };
  16359. /**
  16360. * Unbind all textures from the webGL context
  16361. */
  16362. Engine.prototype.unbindAllTextures = function () {
  16363. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16364. this._activeChannel = channel;
  16365. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16366. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16367. if (this.webGLVersion > 1) {
  16368. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16369. }
  16370. }
  16371. };
  16372. /**
  16373. * Sets a texture to the according uniform.
  16374. * @param channel The texture channel
  16375. * @param uniform The uniform to set
  16376. * @param texture The texture to apply
  16377. */
  16378. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16379. if (channel < 0) {
  16380. return;
  16381. }
  16382. if (uniform) {
  16383. this._boundUniforms[channel] = uniform;
  16384. }
  16385. this._setTexture(channel, texture);
  16386. };
  16387. /**
  16388. * Sets a depth stencil texture from a render target to the according uniform.
  16389. * @param channel The texture channel
  16390. * @param uniform The uniform to set
  16391. * @param texture The render target texture containing the depth stencil texture to apply
  16392. */
  16393. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16394. if (channel < 0) {
  16395. return;
  16396. }
  16397. if (uniform) {
  16398. this._boundUniforms[channel] = uniform;
  16399. }
  16400. if (!texture || !texture.depthStencilTexture) {
  16401. this._setTexture(channel, null);
  16402. }
  16403. else {
  16404. this._setTexture(channel, texture, false, true);
  16405. }
  16406. };
  16407. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16408. var uniform = this._boundUniforms[sourceSlot];
  16409. if (uniform._currentState === destination) {
  16410. return;
  16411. }
  16412. this._gl.uniform1i(uniform, destination);
  16413. uniform._currentState = destination;
  16414. };
  16415. Engine.prototype._getTextureWrapMode = function (mode) {
  16416. switch (mode) {
  16417. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16418. return this._gl.REPEAT;
  16419. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16420. return this._gl.CLAMP_TO_EDGE;
  16421. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16422. return this._gl.MIRRORED_REPEAT;
  16423. }
  16424. return this._gl.REPEAT;
  16425. };
  16426. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16427. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16428. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16429. // Not ready?
  16430. if (!texture) {
  16431. if (this._boundTexturesCache[channel] != null) {
  16432. this._activeChannel = channel;
  16433. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16434. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16435. if (this.webGLVersion > 1) {
  16436. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16437. }
  16438. }
  16439. return false;
  16440. }
  16441. // Video
  16442. if (texture.video) {
  16443. this._activeChannel = channel;
  16444. texture.update();
  16445. }
  16446. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16447. texture.delayLoad();
  16448. return false;
  16449. }
  16450. var internalTexture;
  16451. if (depthStencilTexture) {
  16452. internalTexture = texture.depthStencilTexture;
  16453. }
  16454. else if (texture.isReady()) {
  16455. internalTexture = texture.getInternalTexture();
  16456. }
  16457. else if (texture.isCube) {
  16458. internalTexture = this.emptyCubeTexture;
  16459. }
  16460. else if (texture.is3D) {
  16461. internalTexture = this.emptyTexture3D;
  16462. }
  16463. else {
  16464. internalTexture = this.emptyTexture;
  16465. }
  16466. if (!isPartOfTextureArray) {
  16467. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16468. }
  16469. var needToBind = true;
  16470. if (this._boundTexturesCache[channel] === internalTexture) {
  16471. this._moveBoundTextureOnTop(internalTexture);
  16472. if (!isPartOfTextureArray) {
  16473. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16474. }
  16475. needToBind = false;
  16476. }
  16477. this._activeChannel = channel;
  16478. if (internalTexture && internalTexture.is3D) {
  16479. if (needToBind) {
  16480. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16481. }
  16482. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16483. internalTexture._cachedWrapU = texture.wrapU;
  16484. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16485. }
  16486. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16487. internalTexture._cachedWrapV = texture.wrapV;
  16488. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16489. }
  16490. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16491. internalTexture._cachedWrapR = texture.wrapR;
  16492. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16493. }
  16494. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16495. }
  16496. else if (internalTexture && internalTexture.isCube) {
  16497. if (needToBind) {
  16498. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16499. }
  16500. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16501. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16502. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16503. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16504. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16505. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16506. }
  16507. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16508. }
  16509. else {
  16510. if (needToBind) {
  16511. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16512. }
  16513. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16514. internalTexture._cachedWrapU = texture.wrapU;
  16515. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16516. }
  16517. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16518. internalTexture._cachedWrapV = texture.wrapV;
  16519. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16520. }
  16521. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16522. }
  16523. return true;
  16524. };
  16525. /**
  16526. * Sets an array of texture to the webGL context
  16527. * @param channel defines the channel where the texture array must be set
  16528. * @param uniform defines the associated uniform location
  16529. * @param textures defines the array of textures to bind
  16530. */
  16531. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16532. if (channel < 0 || !uniform) {
  16533. return;
  16534. }
  16535. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16536. this._textureUnits = new Int32Array(textures.length);
  16537. }
  16538. for (var i = 0; i < textures.length; i++) {
  16539. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16540. }
  16541. this._gl.uniform1iv(uniform, this._textureUnits);
  16542. for (var index = 0; index < textures.length; index++) {
  16543. this._setTexture(this._textureUnits[index], textures[index], true);
  16544. }
  16545. };
  16546. /** @hidden */
  16547. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16548. var internalTexture = texture.getInternalTexture();
  16549. if (!internalTexture) {
  16550. return;
  16551. }
  16552. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16553. var value = texture.anisotropicFilteringLevel;
  16554. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16555. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16556. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16557. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16558. }
  16559. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16560. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16561. internalTexture._cachedAnisotropicFilteringLevel = value;
  16562. }
  16563. };
  16564. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16565. this._bindTextureDirectly(target, texture, true, true);
  16566. this._gl.texParameterf(target, parameter, value);
  16567. };
  16568. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16569. if (texture) {
  16570. this._bindTextureDirectly(target, texture, true, true);
  16571. }
  16572. this._gl.texParameteri(target, parameter, value);
  16573. };
  16574. /**
  16575. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16576. * @param x defines the x coordinate of the rectangle where pixels must be read
  16577. * @param y defines the y coordinate of the rectangle where pixels must be read
  16578. * @param width defines the width of the rectangle where pixels must be read
  16579. * @param height defines the height of the rectangle where pixels must be read
  16580. * @returns a Uint8Array containing RGBA colors
  16581. */
  16582. Engine.prototype.readPixels = function (x, y, width, height) {
  16583. var data = new Uint8Array(height * width * 4);
  16584. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16585. return data;
  16586. };
  16587. /**
  16588. * Add an externaly attached data from its key.
  16589. * This method call will fail and return false, if such key already exists.
  16590. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16591. * @param key the unique key that identifies the data
  16592. * @param data the data object to associate to the key for this Engine instance
  16593. * @return true if no such key were already present and the data was added successfully, false otherwise
  16594. */
  16595. Engine.prototype.addExternalData = function (key, data) {
  16596. if (!this._externalData) {
  16597. this._externalData = new BABYLON.StringDictionary();
  16598. }
  16599. return this._externalData.add(key, data);
  16600. };
  16601. /**
  16602. * Get an externaly attached data from its key
  16603. * @param key the unique key that identifies the data
  16604. * @return the associated data, if present (can be null), or undefined if not present
  16605. */
  16606. Engine.prototype.getExternalData = function (key) {
  16607. if (!this._externalData) {
  16608. this._externalData = new BABYLON.StringDictionary();
  16609. }
  16610. return this._externalData.get(key);
  16611. };
  16612. /**
  16613. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16614. * @param key the unique key that identifies the data
  16615. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16616. * @return the associated data, can be null if the factory returned null.
  16617. */
  16618. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16619. if (!this._externalData) {
  16620. this._externalData = new BABYLON.StringDictionary();
  16621. }
  16622. return this._externalData.getOrAddWithFactory(key, factory);
  16623. };
  16624. /**
  16625. * Remove an externaly attached data from the Engine instance
  16626. * @param key the unique key that identifies the data
  16627. * @return true if the data was successfully removed, false if it doesn't exist
  16628. */
  16629. Engine.prototype.removeExternalData = function (key) {
  16630. if (!this._externalData) {
  16631. this._externalData = new BABYLON.StringDictionary();
  16632. }
  16633. return this._externalData.remove(key);
  16634. };
  16635. /**
  16636. * Unbind all vertex attributes from the webGL context
  16637. */
  16638. Engine.prototype.unbindAllAttributes = function () {
  16639. if (this._mustWipeVertexAttributes) {
  16640. this._mustWipeVertexAttributes = false;
  16641. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16642. this._gl.disableVertexAttribArray(i);
  16643. this._vertexAttribArraysEnabled[i] = false;
  16644. this._currentBufferPointers[i].active = false;
  16645. }
  16646. return;
  16647. }
  16648. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16649. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16650. continue;
  16651. }
  16652. this._gl.disableVertexAttribArray(i);
  16653. this._vertexAttribArraysEnabled[i] = false;
  16654. this._currentBufferPointers[i].active = false;
  16655. }
  16656. };
  16657. /**
  16658. * 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
  16659. */
  16660. Engine.prototype.releaseEffects = function () {
  16661. for (var name in this._compiledEffects) {
  16662. this._deleteProgram(this._compiledEffects[name]._program);
  16663. }
  16664. this._compiledEffects = {};
  16665. };
  16666. /**
  16667. * Dispose and release all associated resources
  16668. */
  16669. Engine.prototype.dispose = function () {
  16670. this.hideLoadingUI();
  16671. this.stopRenderLoop();
  16672. // Release postProcesses
  16673. while (this.postProcesses.length) {
  16674. this.postProcesses[0].dispose();
  16675. }
  16676. // Empty texture
  16677. if (this._emptyTexture) {
  16678. this._releaseTexture(this._emptyTexture);
  16679. this._emptyTexture = null;
  16680. }
  16681. if (this._emptyCubeTexture) {
  16682. this._releaseTexture(this._emptyCubeTexture);
  16683. this._emptyCubeTexture = null;
  16684. }
  16685. // Rescale PP
  16686. if (this._rescalePostProcess) {
  16687. this._rescalePostProcess.dispose();
  16688. }
  16689. // Release scenes
  16690. while (this.scenes.length) {
  16691. this.scenes[0].dispose();
  16692. }
  16693. // Release audio engine
  16694. if (Engine.audioEngine) {
  16695. Engine.audioEngine.dispose();
  16696. }
  16697. // Release effects
  16698. this.releaseEffects();
  16699. // Unbind
  16700. this.unbindAllAttributes();
  16701. this._boundUniforms = [];
  16702. if (this._dummyFramebuffer) {
  16703. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16704. }
  16705. //WebVR
  16706. this.disableVR();
  16707. // Events
  16708. if (BABYLON.Tools.IsWindowObjectExist()) {
  16709. window.removeEventListener("blur", this._onBlur);
  16710. window.removeEventListener("focus", this._onFocus);
  16711. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16712. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16713. if (this._renderingCanvas) {
  16714. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16715. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16716. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16717. if (!this._doNotHandleContextLost) {
  16718. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16719. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16720. }
  16721. }
  16722. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16723. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16724. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16725. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16726. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16727. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16728. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16729. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16730. if (this._onVrDisplayConnect) {
  16731. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16732. if (this._onVrDisplayDisconnect) {
  16733. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16734. }
  16735. if (this._onVrDisplayPresentChange) {
  16736. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16737. }
  16738. this._onVrDisplayConnect = null;
  16739. this._onVrDisplayDisconnect = null;
  16740. }
  16741. }
  16742. // Remove from Instances
  16743. var index = Engine.Instances.indexOf(this);
  16744. if (index >= 0) {
  16745. Engine.Instances.splice(index, 1);
  16746. }
  16747. this._workingCanvas = null;
  16748. this._workingContext = null;
  16749. this._currentBufferPointers = [];
  16750. this._renderingCanvas = null;
  16751. this._currentProgram = null;
  16752. this._bindedRenderFunction = null;
  16753. this.onResizeObservable.clear();
  16754. this.onCanvasBlurObservable.clear();
  16755. this.onCanvasFocusObservable.clear();
  16756. this.onCanvasPointerOutObservable.clear();
  16757. this.onBeginFrameObservable.clear();
  16758. this.onEndFrameObservable.clear();
  16759. BABYLON.Effect.ResetCache();
  16760. // Abort active requests
  16761. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16762. var request = _a[_i];
  16763. request.abort();
  16764. }
  16765. };
  16766. // Loading screen
  16767. /**
  16768. * Display the loading screen
  16769. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16770. */
  16771. Engine.prototype.displayLoadingUI = function () {
  16772. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16773. return;
  16774. }
  16775. var loadingScreen = this.loadingScreen;
  16776. if (loadingScreen) {
  16777. loadingScreen.displayLoadingUI();
  16778. }
  16779. };
  16780. /**
  16781. * Hide the loading screen
  16782. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16783. */
  16784. Engine.prototype.hideLoadingUI = function () {
  16785. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16786. return;
  16787. }
  16788. var loadingScreen = this.loadingScreen;
  16789. if (loadingScreen) {
  16790. loadingScreen.hideLoadingUI();
  16791. }
  16792. };
  16793. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16794. /**
  16795. * Gets the current loading screen object
  16796. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16797. */
  16798. get: function () {
  16799. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16800. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16801. return this._loadingScreen;
  16802. },
  16803. /**
  16804. * Sets the current loading screen object
  16805. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16806. */
  16807. set: function (loadingScreen) {
  16808. this._loadingScreen = loadingScreen;
  16809. },
  16810. enumerable: true,
  16811. configurable: true
  16812. });
  16813. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16814. /**
  16815. * Sets the current loading screen text
  16816. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16817. */
  16818. set: function (text) {
  16819. this.loadingScreen.loadingUIText = text;
  16820. },
  16821. enumerable: true,
  16822. configurable: true
  16823. });
  16824. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16825. /**
  16826. * Sets the current loading screen background color
  16827. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16828. */
  16829. set: function (color) {
  16830. this.loadingScreen.loadingUIBackgroundColor = color;
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. /**
  16836. * Attach a new callback raised when context lost event is fired
  16837. * @param callback defines the callback to call
  16838. */
  16839. Engine.prototype.attachContextLostEvent = function (callback) {
  16840. if (this._renderingCanvas) {
  16841. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16842. }
  16843. };
  16844. /**
  16845. * Attach a new callback raised when context restored event is fired
  16846. * @param callback defines the callback to call
  16847. */
  16848. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16849. if (this._renderingCanvas) {
  16850. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16851. }
  16852. };
  16853. /**
  16854. * Gets the source code of the vertex shader associated with a specific webGL program
  16855. * @param program defines the program to use
  16856. * @returns a string containing the source code of the vertex shader associated with the program
  16857. */
  16858. Engine.prototype.getVertexShaderSource = function (program) {
  16859. var shaders = this._gl.getAttachedShaders(program);
  16860. if (!shaders) {
  16861. return null;
  16862. }
  16863. return this._gl.getShaderSource(shaders[0]);
  16864. };
  16865. /**
  16866. * Gets the source code of the fragment shader associated with a specific webGL program
  16867. * @param program defines the program to use
  16868. * @returns a string containing the source code of the fragment shader associated with the program
  16869. */
  16870. Engine.prototype.getFragmentShaderSource = function (program) {
  16871. var shaders = this._gl.getAttachedShaders(program);
  16872. if (!shaders) {
  16873. return null;
  16874. }
  16875. return this._gl.getShaderSource(shaders[1]);
  16876. };
  16877. /**
  16878. * Get the current error code of the webGL context
  16879. * @returns the error code
  16880. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16881. */
  16882. Engine.prototype.getError = function () {
  16883. return this._gl.getError();
  16884. };
  16885. // FPS
  16886. /**
  16887. * Gets the current framerate
  16888. * @returns a number representing the framerate
  16889. */
  16890. Engine.prototype.getFps = function () {
  16891. return this._fps;
  16892. };
  16893. /**
  16894. * Gets the time spent between current and previous frame
  16895. * @returns a number representing the delta time in ms
  16896. */
  16897. Engine.prototype.getDeltaTime = function () {
  16898. return this._deltaTime;
  16899. };
  16900. Engine.prototype._measureFps = function () {
  16901. this._performanceMonitor.sampleFrame();
  16902. this._fps = this._performanceMonitor.averageFPS;
  16903. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16904. };
  16905. /** @hidden */
  16906. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16907. if (faceIndex === void 0) { faceIndex = -1; }
  16908. if (level === void 0) { level = 0; }
  16909. var gl = this._gl;
  16910. if (!this._dummyFramebuffer) {
  16911. var dummy = gl.createFramebuffer();
  16912. if (!dummy) {
  16913. throw new Error("Unable to create dummy framebuffer");
  16914. }
  16915. this._dummyFramebuffer = dummy;
  16916. }
  16917. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16918. if (faceIndex > -1) {
  16919. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16920. }
  16921. else {
  16922. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16923. }
  16924. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16925. var buffer;
  16926. switch (readType) {
  16927. case gl.UNSIGNED_BYTE:
  16928. buffer = new Uint8Array(4 * width * height);
  16929. readType = gl.UNSIGNED_BYTE;
  16930. break;
  16931. default:
  16932. buffer = new Float32Array(4 * width * height);
  16933. readType = gl.FLOAT;
  16934. break;
  16935. }
  16936. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16937. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16938. return buffer;
  16939. };
  16940. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16941. if (this._webGLVersion > 1) {
  16942. return this._caps.colorBufferFloat;
  16943. }
  16944. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16945. };
  16946. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16947. if (this._webGLVersion > 1) {
  16948. return this._caps.colorBufferFloat;
  16949. }
  16950. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16951. };
  16952. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16953. Engine.prototype._canRenderToFramebuffer = function (type) {
  16954. var gl = this._gl;
  16955. //clear existing errors
  16956. while (gl.getError() !== gl.NO_ERROR) { }
  16957. var successful = true;
  16958. var texture = gl.createTexture();
  16959. gl.bindTexture(gl.TEXTURE_2D, texture);
  16960. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16963. var fb = gl.createFramebuffer();
  16964. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16965. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16966. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16967. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16968. successful = successful && (gl.getError() === gl.NO_ERROR);
  16969. //try render by clearing frame buffer's color buffer
  16970. if (successful) {
  16971. gl.clear(gl.COLOR_BUFFER_BIT);
  16972. successful = successful && (gl.getError() === gl.NO_ERROR);
  16973. }
  16974. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16975. if (successful) {
  16976. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16977. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16978. var readFormat = gl.RGBA;
  16979. var readType = gl.UNSIGNED_BYTE;
  16980. var buffer = new Uint8Array(4);
  16981. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16982. successful = successful && (gl.getError() === gl.NO_ERROR);
  16983. }
  16984. //clean up
  16985. gl.deleteTexture(texture);
  16986. gl.deleteFramebuffer(fb);
  16987. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16988. //clear accumulated errors
  16989. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16990. return successful;
  16991. };
  16992. /** @hidden */
  16993. Engine.prototype._getWebGLTextureType = function (type) {
  16994. if (type === Engine.TEXTURETYPE_FLOAT) {
  16995. return this._gl.FLOAT;
  16996. }
  16997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16998. // Add Half Float Constant.
  16999. return this._gl.HALF_FLOAT_OES;
  17000. }
  17001. return this._gl.UNSIGNED_BYTE;
  17002. };
  17003. ;
  17004. Engine.prototype._getInternalFormat = function (format) {
  17005. var internalFormat = this._gl.RGBA;
  17006. switch (format) {
  17007. case Engine.TEXTUREFORMAT_ALPHA:
  17008. internalFormat = this._gl.ALPHA;
  17009. break;
  17010. case Engine.TEXTUREFORMAT_LUMINANCE:
  17011. internalFormat = this._gl.LUMINANCE;
  17012. break;
  17013. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17014. internalFormat = this._gl.LUMINANCE_ALPHA;
  17015. break;
  17016. case Engine.TEXTUREFORMAT_RGB:
  17017. internalFormat = this._gl.RGB;
  17018. break;
  17019. case Engine.TEXTUREFORMAT_RGBA:
  17020. internalFormat = this._gl.RGBA;
  17021. break;
  17022. case Engine.TEXTUREFORMAT_R:
  17023. internalFormat = this._gl.RED;
  17024. break;
  17025. case Engine.TEXTUREFORMAT_RG:
  17026. internalFormat = this._gl.RG;
  17027. break;
  17028. }
  17029. return internalFormat;
  17030. };
  17031. /** @hidden */
  17032. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17033. if (this._webGLVersion === 1) {
  17034. if (format !== undefined) {
  17035. switch (format) {
  17036. case Engine.TEXTUREFORMAT_LUMINANCE:
  17037. return this._gl.LUMINANCE;
  17038. case Engine.TEXTUREFORMAT_ALPHA:
  17039. return this._gl.ALPHA;
  17040. }
  17041. }
  17042. return this._gl.RGBA;
  17043. }
  17044. if (type === Engine.TEXTURETYPE_FLOAT) {
  17045. if (format !== undefined) {
  17046. switch (format) {
  17047. case Engine.TEXTUREFORMAT_R:
  17048. return this._gl.R32F;
  17049. case Engine.TEXTUREFORMAT_RG:
  17050. return this._gl.RG32F;
  17051. case Engine.TEXTUREFORMAT_RGB:
  17052. return this._gl.RGB32F;
  17053. }
  17054. }
  17055. return this._gl.RGBA32F;
  17056. }
  17057. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17058. if (format) {
  17059. switch (format) {
  17060. case Engine.TEXTUREFORMAT_R:
  17061. return this._gl.R16F;
  17062. case Engine.TEXTUREFORMAT_RG:
  17063. return this._gl.RG16F;
  17064. case Engine.TEXTUREFORMAT_RGB:
  17065. return this._gl.RGB16F;
  17066. }
  17067. }
  17068. return this._gl.RGBA16F;
  17069. }
  17070. if (format !== undefined) {
  17071. switch (format) {
  17072. case Engine.TEXTUREFORMAT_LUMINANCE:
  17073. return this._gl.LUMINANCE;
  17074. case Engine.TEXTUREFORMAT_RGB:
  17075. return this._gl.RGB;
  17076. case Engine.TEXTUREFORMAT_R:
  17077. return this._gl.R8;
  17078. case Engine.TEXTUREFORMAT_RG:
  17079. return this._gl.RG8;
  17080. case Engine.TEXTUREFORMAT_ALPHA:
  17081. return this._gl.ALPHA;
  17082. }
  17083. }
  17084. return this._gl.RGBA;
  17085. };
  17086. ;
  17087. /** @hidden */
  17088. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17089. if (type === Engine.TEXTURETYPE_FLOAT) {
  17090. return this._gl.RGBA32F;
  17091. }
  17092. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17093. return this._gl.RGBA16F;
  17094. }
  17095. return this._gl.RGBA8;
  17096. };
  17097. ;
  17098. /** @hidden */
  17099. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17100. var _this = this;
  17101. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17102. this._activeRequests.push(request);
  17103. request.onCompleteObservable.add(function (request) {
  17104. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17105. });
  17106. return request;
  17107. };
  17108. /** @hidden */
  17109. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17110. var _this = this;
  17111. return new Promise(function (resolve, reject) {
  17112. _this._loadFile(url, function (data) {
  17113. resolve(data);
  17114. }, undefined, database, useArrayBuffer, function (request, exception) {
  17115. reject(exception);
  17116. });
  17117. });
  17118. };
  17119. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17120. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17121. var onload = function (data) {
  17122. loadedFiles[index] = data;
  17123. loadedFiles._internalCount++;
  17124. if (loadedFiles._internalCount === 6) {
  17125. onfinish(loadedFiles);
  17126. }
  17127. };
  17128. var onerror = function (request, exception) {
  17129. if (onErrorCallBack && request) {
  17130. onErrorCallBack(request.status + " " + request.statusText, exception);
  17131. }
  17132. };
  17133. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17134. };
  17135. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17136. if (onError === void 0) { onError = null; }
  17137. var loadedFiles = [];
  17138. loadedFiles._internalCount = 0;
  17139. for (var index = 0; index < 6; index++) {
  17140. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17141. }
  17142. };
  17143. // Statics
  17144. /**
  17145. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17146. * @returns true if the engine can be created
  17147. * @ignorenaming
  17148. */
  17149. Engine.isSupported = function () {
  17150. try {
  17151. var tempcanvas = document.createElement("canvas");
  17152. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17153. return gl != null && !!window.WebGLRenderingContext;
  17154. }
  17155. catch (e) {
  17156. return false;
  17157. }
  17158. };
  17159. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17160. Engine.ExceptionList = [
  17161. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17162. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17163. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17164. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17165. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17166. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17167. ];
  17168. /** Gets the list of created engines */
  17169. Engine.Instances = new Array();
  17170. // Const statics
  17171. /** Defines that alpha blending is disabled */
  17172. Engine.ALPHA_DISABLE = 0;
  17173. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17174. Engine.ALPHA_ADD = 1;
  17175. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17176. Engine.ALPHA_COMBINE = 2;
  17177. /** Defines that alpha blending to DEST - SRC * DEST */
  17178. Engine.ALPHA_SUBTRACT = 3;
  17179. /** Defines that alpha blending to SRC * DEST */
  17180. Engine.ALPHA_MULTIPLY = 4;
  17181. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17182. Engine.ALPHA_MAXIMIZED = 5;
  17183. /** Defines that alpha blending to SRC + DEST */
  17184. Engine.ALPHA_ONEONE = 6;
  17185. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17186. Engine.ALPHA_PREMULTIPLIED = 7;
  17187. /**
  17188. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17189. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17190. */
  17191. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17192. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17193. Engine.ALPHA_INTERPOLATE = 9;
  17194. /**
  17195. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17196. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17197. */
  17198. Engine.ALPHA_SCREENMODE = 10;
  17199. /** Defines that the ressource is not delayed*/
  17200. Engine.DELAYLOADSTATE_NONE = 0;
  17201. /** Defines that the ressource was successfully delay loaded */
  17202. Engine.DELAYLOADSTATE_LOADED = 1;
  17203. /** Defines that the ressource is currently delay loading */
  17204. Engine.DELAYLOADSTATE_LOADING = 2;
  17205. /** Defines that the ressource is delayed and has not started loading */
  17206. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17207. // Depht or Stencil test Constants.
  17208. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17209. Engine.NEVER = 0x0200;
  17210. /** 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 */
  17211. Engine.ALWAYS = 0x0207;
  17212. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17213. Engine.LESS = 0x0201;
  17214. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17215. Engine.EQUAL = 0x0202;
  17216. /** 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 */
  17217. Engine.LEQUAL = 0x0203;
  17218. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17219. Engine.GREATER = 0x0204;
  17220. /** 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 */
  17221. Engine.GEQUAL = 0x0206;
  17222. /** 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 */
  17223. Engine.NOTEQUAL = 0x0205;
  17224. // Stencil Actions Constants.
  17225. /** Passed to stencilOperation to specify that stencil value must be kept */
  17226. Engine.KEEP = 0x1E00;
  17227. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17228. Engine.REPLACE = 0x1E01;
  17229. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17230. Engine.INCR = 0x1E02;
  17231. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17232. Engine.DECR = 0x1E03;
  17233. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17234. Engine.INVERT = 0x150A;
  17235. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17236. Engine.INCR_WRAP = 0x8507;
  17237. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17238. Engine.DECR_WRAP = 0x8508;
  17239. /** Texture is not repeating outside of 0..1 UVs */
  17240. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17241. /** Texture is repeating outside of 0..1 UVs */
  17242. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17243. /** Texture is repeating and mirrored */
  17244. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17245. /** ALPHA */
  17246. Engine.TEXTUREFORMAT_ALPHA = 0;
  17247. /** LUMINANCE */
  17248. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17249. /** LUMINANCE_ALPHA */
  17250. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17251. /** RGB */
  17252. Engine.TEXTUREFORMAT_RGB = 4;
  17253. /** RGBA */
  17254. Engine.TEXTUREFORMAT_RGBA = 5;
  17255. /** R */
  17256. Engine.TEXTUREFORMAT_R = 6;
  17257. /** RG */
  17258. Engine.TEXTUREFORMAT_RG = 7;
  17259. /** UNSIGNED_INT */
  17260. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17261. /** FLOAT */
  17262. Engine.TEXTURETYPE_FLOAT = 1;
  17263. /** HALF_FLOAT */
  17264. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17265. /** nearest is mag = nearest and min = nearest and mip = linear */
  17266. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17267. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17268. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17269. /** Trilinear is mag = linear and min = linear and mip = linear */
  17270. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17271. /** nearest is mag = nearest and min = nearest and mip = linear */
  17272. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17273. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17274. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17275. /** Trilinear is mag = linear and min = linear and mip = linear */
  17276. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17277. /** mag = nearest and min = nearest and mip = nearest */
  17278. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17279. /** mag = nearest and min = linear and mip = nearest */
  17280. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17281. /** mag = nearest and min = linear and mip = linear */
  17282. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17283. /** mag = nearest and min = linear and mip = none */
  17284. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17285. /** mag = nearest and min = nearest and mip = none */
  17286. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17287. /** mag = linear and min = nearest and mip = nearest */
  17288. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17289. /** mag = linear and min = nearest and mip = linear */
  17290. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17291. /** mag = linear and min = linear and mip = none */
  17292. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17293. /** mag = linear and min = nearest and mip = none */
  17294. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17295. /** Explicit coordinates mode */
  17296. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17297. /** Spherical coordinates mode */
  17298. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17299. /** Planar coordinates mode */
  17300. Engine.TEXTURE_PLANAR_MODE = 2;
  17301. /** Cubic coordinates mode */
  17302. Engine.TEXTURE_CUBIC_MODE = 3;
  17303. /** Projection coordinates mode */
  17304. Engine.TEXTURE_PROJECTION_MODE = 4;
  17305. /** Skybox coordinates mode */
  17306. Engine.TEXTURE_SKYBOX_MODE = 5;
  17307. /** Inverse Cubic coordinates mode */
  17308. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17309. /** Equirectangular coordinates mode */
  17310. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17311. /** Equirectangular Fixed coordinates mode */
  17312. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17313. /** Equirectangular Fixed Mirrored coordinates mode */
  17314. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17315. // Texture rescaling mode
  17316. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17317. Engine.SCALEMODE_FLOOR = 1;
  17318. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17319. Engine.SCALEMODE_NEAREST = 2;
  17320. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17321. Engine.SCALEMODE_CEILING = 3;
  17322. // Updatable statics so stick with vars here
  17323. /**
  17324. * Gets or sets the epsilon value used by collision engine
  17325. */
  17326. Engine.CollisionsEpsilon = 0.001;
  17327. /**
  17328. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17329. */
  17330. Engine.CodeRepository = "src/";
  17331. /**
  17332. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17333. */
  17334. Engine.ShadersRepository = "src/Shaders/";
  17335. return Engine;
  17336. }());
  17337. BABYLON.Engine = Engine;
  17338. })(BABYLON || (BABYLON = {}));
  17339. //# sourceMappingURL=babylon.engine.js.map
  17340. var BABYLON;
  17341. (function (BABYLON) {
  17342. /**
  17343. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17344. */
  17345. var Node = /** @class */ (function () {
  17346. /**
  17347. * Creates a new Node
  17348. * @param {string} name - the name and id to be given to this node
  17349. * @param {BABYLON.Scene} the scene this node will be added to
  17350. */
  17351. function Node(name, scene) {
  17352. if (scene === void 0) { scene = null; }
  17353. /**
  17354. * Gets or sets a string used to store user defined state for the node
  17355. */
  17356. this.state = "";
  17357. /**
  17358. * Gets or sets an object used to store user defined information for the node
  17359. */
  17360. this.metadata = null;
  17361. /**
  17362. * Gets or sets a boolean used to define if the node must be serialized
  17363. */
  17364. this.doNotSerialize = false;
  17365. /** @hidden */
  17366. this._isDisposed = false;
  17367. /**
  17368. * Gets a list of Animations associated with the node
  17369. */
  17370. this.animations = new Array();
  17371. this._ranges = {};
  17372. this._isEnabled = true;
  17373. this._isReady = true;
  17374. /** @hidden */
  17375. this._currentRenderId = -1;
  17376. this._parentRenderId = -1;
  17377. this._childRenderId = -1;
  17378. this._animationPropertiesOverride = null;
  17379. /**
  17380. * An event triggered when the mesh is disposed
  17381. */
  17382. this.onDisposeObservable = new BABYLON.Observable();
  17383. // Behaviors
  17384. this._behaviors = new Array();
  17385. this.name = name;
  17386. this.id = name;
  17387. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17388. this.uniqueId = this._scene.getUniqueId();
  17389. this._initCache();
  17390. }
  17391. /**
  17392. * Add a new node constructor
  17393. * @param type defines the type name of the node to construct
  17394. * @param constructorFunc defines the constructor function
  17395. */
  17396. Node.AddNodeConstructor = function (type, constructorFunc) {
  17397. this._NodeConstructors[type] = constructorFunc;
  17398. };
  17399. /**
  17400. * Returns a node constructor based on type name
  17401. * @param type defines the type name
  17402. * @param name defines the new node name
  17403. * @param scene defines the hosting scene
  17404. * @param options defines optional options to transmit to constructors
  17405. * @returns the new constructor or null
  17406. */
  17407. Node.Construct = function (type, name, scene, options) {
  17408. var constructorFunc = this._NodeConstructors[type];
  17409. if (!constructorFunc) {
  17410. return null;
  17411. }
  17412. return constructorFunc(name, scene, options);
  17413. };
  17414. /**
  17415. * Gets a boolean indicating if the node has been disposed
  17416. * @returns true if the node was disposed
  17417. */
  17418. Node.prototype.isDisposed = function () {
  17419. return this._isDisposed;
  17420. };
  17421. Object.defineProperty(Node.prototype, "parent", {
  17422. get: function () {
  17423. return this._parentNode;
  17424. },
  17425. /**
  17426. * Gets or sets the parent of the node
  17427. */
  17428. set: function (parent) {
  17429. if (this._parentNode === parent) {
  17430. return;
  17431. }
  17432. // Remove self from list of children of parent
  17433. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17434. var index = this._parentNode._children.indexOf(this);
  17435. if (index !== -1) {
  17436. this._parentNode._children.splice(index, 1);
  17437. }
  17438. }
  17439. // Store new parent
  17440. this._parentNode = parent;
  17441. // Add as child to new parent
  17442. if (this._parentNode) {
  17443. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17444. this._parentNode._children = new Array();
  17445. }
  17446. this._parentNode._children.push(this);
  17447. }
  17448. },
  17449. enumerable: true,
  17450. configurable: true
  17451. });
  17452. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17453. /**
  17454. * Gets or sets the animation properties override
  17455. */
  17456. get: function () {
  17457. if (!this._animationPropertiesOverride) {
  17458. return this._scene.animationPropertiesOverride;
  17459. }
  17460. return this._animationPropertiesOverride;
  17461. },
  17462. set: function (value) {
  17463. this._animationPropertiesOverride = value;
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. /**
  17469. * Gets a string idenfifying the name of the class
  17470. * @returns "Node" string
  17471. */
  17472. Node.prototype.getClassName = function () {
  17473. return "Node";
  17474. };
  17475. Object.defineProperty(Node.prototype, "onDispose", {
  17476. /**
  17477. * Sets a callback that will be raised when the node will be disposed
  17478. */
  17479. set: function (callback) {
  17480. if (this._onDisposeObserver) {
  17481. this.onDisposeObservable.remove(this._onDisposeObserver);
  17482. }
  17483. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. /**
  17489. * Gets the scene of the node
  17490. * @returns a {BABYLON.Scene}
  17491. */
  17492. Node.prototype.getScene = function () {
  17493. return this._scene;
  17494. };
  17495. /**
  17496. * Gets the engine of the node
  17497. * @returns a {BABYLON.Engine}
  17498. */
  17499. Node.prototype.getEngine = function () {
  17500. return this._scene.getEngine();
  17501. };
  17502. /**
  17503. * Attach a behavior to the node
  17504. * @see http://doc.babylonjs.com/features/behaviour
  17505. * @param behavior defines the behavior to attach
  17506. * @returns the current Node
  17507. */
  17508. Node.prototype.addBehavior = function (behavior) {
  17509. var _this = this;
  17510. var index = this._behaviors.indexOf(behavior);
  17511. if (index !== -1) {
  17512. return this;
  17513. }
  17514. behavior.init();
  17515. if (this._scene.isLoading) {
  17516. // We defer the attach when the scene will be loaded
  17517. this._scene.onDataLoadedObservable.addOnce(function () {
  17518. behavior.attach(_this);
  17519. });
  17520. }
  17521. else {
  17522. behavior.attach(this);
  17523. }
  17524. this._behaviors.push(behavior);
  17525. return this;
  17526. };
  17527. /**
  17528. * Remove an attached behavior
  17529. * @see http://doc.babylonjs.com/features/behaviour
  17530. * @param behavior defines the behavior to attach
  17531. * @returns the current Node
  17532. */
  17533. Node.prototype.removeBehavior = function (behavior) {
  17534. var index = this._behaviors.indexOf(behavior);
  17535. if (index === -1) {
  17536. return this;
  17537. }
  17538. this._behaviors[index].detach();
  17539. this._behaviors.splice(index, 1);
  17540. return this;
  17541. };
  17542. Object.defineProperty(Node.prototype, "behaviors", {
  17543. /**
  17544. * Gets the list of attached behaviors
  17545. * @see http://doc.babylonjs.com/features/behaviour
  17546. */
  17547. get: function () {
  17548. return this._behaviors;
  17549. },
  17550. enumerable: true,
  17551. configurable: true
  17552. });
  17553. /**
  17554. * Gets an attached behavior by name
  17555. * @param name defines the name of the behavior to look for
  17556. * @see http://doc.babylonjs.com/features/behaviour
  17557. * @returns null if behavior was not found else the requested behavior
  17558. */
  17559. Node.prototype.getBehaviorByName = function (name) {
  17560. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17561. var behavior = _a[_i];
  17562. if (behavior.name === name) {
  17563. return behavior;
  17564. }
  17565. }
  17566. return null;
  17567. };
  17568. /**
  17569. * Returns the world matrix of the node
  17570. * @returns a matrix containing the node's world matrix
  17571. */
  17572. Node.prototype.getWorldMatrix = function () {
  17573. return BABYLON.Matrix.Identity();
  17574. };
  17575. /** @hidden */
  17576. Node.prototype._getWorldMatrixDeterminant = function () {
  17577. return 1;
  17578. };
  17579. // override it in derived class if you add new variables to the cache
  17580. // and call the parent class method
  17581. /** @hidden */
  17582. Node.prototype._initCache = function () {
  17583. this._cache = {};
  17584. this._cache.parent = undefined;
  17585. };
  17586. /** @hidden */
  17587. Node.prototype.updateCache = function (force) {
  17588. if (!force && this.isSynchronized())
  17589. return;
  17590. this._cache.parent = this.parent;
  17591. this._updateCache();
  17592. };
  17593. // override it in derived class if you add new variables to the cache
  17594. // and call the parent class method if !ignoreParentClass
  17595. /** @hidden */
  17596. Node.prototype._updateCache = function (ignoreParentClass) {
  17597. };
  17598. // override it in derived class if you add new variables to the cache
  17599. /** @hidden */
  17600. Node.prototype._isSynchronized = function () {
  17601. return true;
  17602. };
  17603. /** @hidden */
  17604. Node.prototype._markSyncedWithParent = function () {
  17605. if (this.parent) {
  17606. this._parentRenderId = this.parent._childRenderId;
  17607. }
  17608. };
  17609. /** @hidden */
  17610. Node.prototype.isSynchronizedWithParent = function () {
  17611. if (!this.parent) {
  17612. return true;
  17613. }
  17614. if (this._parentRenderId !== this.parent._childRenderId) {
  17615. return false;
  17616. }
  17617. return this.parent.isSynchronized();
  17618. };
  17619. /** @hidden */
  17620. Node.prototype.isSynchronized = function (updateCache) {
  17621. var check = this.hasNewParent();
  17622. check = check || !this.isSynchronizedWithParent();
  17623. check = check || !this._isSynchronized();
  17624. if (updateCache)
  17625. this.updateCache(true);
  17626. return !check;
  17627. };
  17628. /** @hidden */
  17629. Node.prototype.hasNewParent = function (update) {
  17630. if (this._cache.parent === this.parent)
  17631. return false;
  17632. if (update)
  17633. this._cache.parent = this.parent;
  17634. return true;
  17635. };
  17636. /**
  17637. * Is this node ready to be used/rendered
  17638. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17639. * @return true if the node is ready
  17640. */
  17641. Node.prototype.isReady = function (completeCheck) {
  17642. if (completeCheck === void 0) { completeCheck = false; }
  17643. return this._isReady;
  17644. };
  17645. /**
  17646. * Is this node enabled?
  17647. * 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
  17648. * @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
  17649. * @return whether this node (and its parent) is enabled
  17650. */
  17651. Node.prototype.isEnabled = function (checkAncestors) {
  17652. if (checkAncestors === void 0) { checkAncestors = true; }
  17653. if (checkAncestors === false) {
  17654. return this._isEnabled;
  17655. }
  17656. if (this._isEnabled === false) {
  17657. return false;
  17658. }
  17659. if (this.parent !== undefined && this.parent !== null) {
  17660. return this.parent.isEnabled(checkAncestors);
  17661. }
  17662. return true;
  17663. };
  17664. /**
  17665. * Set the enabled state of this node
  17666. * @param value defines the new enabled state
  17667. */
  17668. Node.prototype.setEnabled = function (value) {
  17669. this._isEnabled = value;
  17670. };
  17671. /**
  17672. * Is this node a descendant of the given node?
  17673. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17674. * @param ancestor defines the parent node to inspect
  17675. * @returns a boolean indicating if this node is a descendant of the given node
  17676. */
  17677. Node.prototype.isDescendantOf = function (ancestor) {
  17678. if (this.parent) {
  17679. if (this.parent === ancestor) {
  17680. return true;
  17681. }
  17682. return this.parent.isDescendantOf(ancestor);
  17683. }
  17684. return false;
  17685. };
  17686. /** @hidden */
  17687. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17688. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17689. if (!this._children) {
  17690. return;
  17691. }
  17692. for (var index = 0; index < this._children.length; index++) {
  17693. var item = this._children[index];
  17694. if (!predicate || predicate(item)) {
  17695. results.push(item);
  17696. }
  17697. if (!directDescendantsOnly) {
  17698. item._getDescendants(results, false, predicate);
  17699. }
  17700. }
  17701. };
  17702. /**
  17703. * Will return all nodes that have this node as ascendant
  17704. * @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
  17705. * @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
  17706. * @return all children nodes of all types
  17707. */
  17708. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17709. var results = new Array();
  17710. this._getDescendants(results, directDescendantsOnly, predicate);
  17711. return results;
  17712. };
  17713. /**
  17714. * Get all child-meshes of this node
  17715. * @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
  17716. * @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
  17717. * @returns an array of {BABYLON.AbstractMesh}
  17718. */
  17719. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17720. var results = [];
  17721. this._getDescendants(results, directDescendantsOnly, function (node) {
  17722. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17723. });
  17724. return results;
  17725. };
  17726. /**
  17727. * Get all child-transformNodes of this node
  17728. * @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
  17729. * @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
  17730. * @returns an array of {BABYLON.TransformNode}
  17731. */
  17732. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17733. var results = [];
  17734. this._getDescendants(results, directDescendantsOnly, function (node) {
  17735. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17736. });
  17737. return results;
  17738. };
  17739. /**
  17740. * Get all direct children of this node
  17741. * @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
  17742. * @returns an array of {BABYLON.Node}
  17743. */
  17744. Node.prototype.getChildren = function (predicate) {
  17745. return this.getDescendants(true, predicate);
  17746. };
  17747. /** @hidden */
  17748. Node.prototype._setReady = function (state) {
  17749. if (state === this._isReady) {
  17750. return;
  17751. }
  17752. if (!state) {
  17753. this._isReady = false;
  17754. return;
  17755. }
  17756. if (this.onReady) {
  17757. this.onReady(this);
  17758. }
  17759. this._isReady = true;
  17760. };
  17761. /**
  17762. * Get an animation by name
  17763. * @param name defines the name of the animation to look for
  17764. * @returns null if not found else the requested animation
  17765. */
  17766. Node.prototype.getAnimationByName = function (name) {
  17767. for (var i = 0; i < this.animations.length; i++) {
  17768. var animation = this.animations[i];
  17769. if (animation.name === name) {
  17770. return animation;
  17771. }
  17772. }
  17773. return null;
  17774. };
  17775. /**
  17776. * Creates an animation range for this node
  17777. * @param name defines the name of the range
  17778. * @param from defines the starting key
  17779. * @param to defines the end key
  17780. */
  17781. Node.prototype.createAnimationRange = function (name, from, to) {
  17782. // check name not already in use
  17783. if (!this._ranges[name]) {
  17784. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17785. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17786. if (this.animations[i]) {
  17787. this.animations[i].createRange(name, from, to);
  17788. }
  17789. }
  17790. }
  17791. };
  17792. /**
  17793. * Delete a specific animation range
  17794. * @param name defines the name of the range to delete
  17795. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17796. */
  17797. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17798. if (deleteFrames === void 0) { deleteFrames = true; }
  17799. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17800. if (this.animations[i]) {
  17801. this.animations[i].deleteRange(name, deleteFrames);
  17802. }
  17803. }
  17804. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17805. };
  17806. /**
  17807. * Get an animation range by name
  17808. * @param name defines the name of the animation range to look for
  17809. * @returns null if not found else the requested animation range
  17810. */
  17811. Node.prototype.getAnimationRange = function (name) {
  17812. return this._ranges[name];
  17813. };
  17814. /**
  17815. * Will start the animation sequence
  17816. * @param name defines the range frames for animation sequence
  17817. * @param loop defines if the animation should loop (false by default)
  17818. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17819. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17820. * @returns the object created for this animation. If range does not exist, it will return null
  17821. */
  17822. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17823. var range = this.getAnimationRange(name);
  17824. if (!range) {
  17825. return null;
  17826. }
  17827. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17828. };
  17829. /**
  17830. * Serialize animation ranges into a JSON compatible object
  17831. * @returns serialization object
  17832. */
  17833. Node.prototype.serializeAnimationRanges = function () {
  17834. var serializationRanges = [];
  17835. for (var name in this._ranges) {
  17836. var localRange = this._ranges[name];
  17837. if (!localRange) {
  17838. continue;
  17839. }
  17840. var range = {};
  17841. range.name = name;
  17842. range.from = localRange.from;
  17843. range.to = localRange.to;
  17844. serializationRanges.push(range);
  17845. }
  17846. return serializationRanges;
  17847. };
  17848. /**
  17849. * Computes the world matrix of the node
  17850. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17851. * @returns the world matrix
  17852. */
  17853. Node.prototype.computeWorldMatrix = function (force) {
  17854. return BABYLON.Matrix.Identity();
  17855. };
  17856. /**
  17857. * Releases resources associated with this node.
  17858. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17859. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17860. */
  17861. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17863. if (!doNotRecurse) {
  17864. var nodes = this.getDescendants(true);
  17865. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17866. var node = nodes_1[_i];
  17867. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17868. }
  17869. }
  17870. else {
  17871. var transformNodes = this.getChildTransformNodes(true);
  17872. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17873. var transformNode = transformNodes_1[_a];
  17874. transformNode.parent = null;
  17875. transformNode.computeWorldMatrix(true);
  17876. }
  17877. }
  17878. this.parent = null;
  17879. // Callback
  17880. this.onDisposeObservable.notifyObservers(this);
  17881. this.onDisposeObservable.clear();
  17882. // Behaviors
  17883. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17884. var behavior = _c[_b];
  17885. behavior.detach();
  17886. }
  17887. this._behaviors = [];
  17888. this._isDisposed = true;
  17889. };
  17890. /**
  17891. * Parse animation range data from a serialization object and store them into a given node
  17892. * @param node defines where to store the animation ranges
  17893. * @param parsedNode defines the serialization object to read data from
  17894. * @param scene defines the hosting scene
  17895. */
  17896. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17897. if (parsedNode.ranges) {
  17898. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17899. var data = parsedNode.ranges[index];
  17900. node.createAnimationRange(data.name, data.from, data.to);
  17901. }
  17902. }
  17903. };
  17904. Node._NodeConstructors = {};
  17905. __decorate([
  17906. BABYLON.serialize()
  17907. ], Node.prototype, "name", void 0);
  17908. __decorate([
  17909. BABYLON.serialize()
  17910. ], Node.prototype, "id", void 0);
  17911. __decorate([
  17912. BABYLON.serialize()
  17913. ], Node.prototype, "uniqueId", void 0);
  17914. __decorate([
  17915. BABYLON.serialize()
  17916. ], Node.prototype, "state", void 0);
  17917. __decorate([
  17918. BABYLON.serialize()
  17919. ], Node.prototype, "metadata", void 0);
  17920. return Node;
  17921. }());
  17922. BABYLON.Node = Node;
  17923. })(BABYLON || (BABYLON = {}));
  17924. //# sourceMappingURL=babylon.node.js.map
  17925. var BABYLON;
  17926. (function (BABYLON) {
  17927. var BoundingSphere = /** @class */ (function () {
  17928. /**
  17929. * Creates a new bounding sphere
  17930. * @param min defines the minimum vector (in local space)
  17931. * @param max defines the maximum vector (in local space)
  17932. */
  17933. function BoundingSphere(min, max) {
  17934. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17935. this.reConstruct(min, max);
  17936. }
  17937. /**
  17938. * Recreates the entire bounding sphere from scratch
  17939. * @param min defines the new minimum vector (in local space)
  17940. * @param max defines the new maximum vector (in local space)
  17941. */
  17942. BoundingSphere.prototype.reConstruct = function (min, max) {
  17943. this.minimum = min.clone();
  17944. this.maximum = max.clone();
  17945. var distance = BABYLON.Vector3.Distance(min, max);
  17946. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17947. this.radius = distance * 0.5;
  17948. this.centerWorld = BABYLON.Vector3.Zero();
  17949. this._update(BABYLON.Matrix.Identity());
  17950. };
  17951. /**
  17952. * Scale the current bounding sphere by applying a scale factor
  17953. * @param factor defines the scale factor to apply
  17954. * @returns the current bounding box
  17955. */
  17956. BoundingSphere.prototype.scale = function (factor) {
  17957. var newRadius = this.radius * factor;
  17958. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17959. var min = this.center.subtract(newRadiusVector);
  17960. var max = this.center.add(newRadiusVector);
  17961. this.reConstruct(min, max);
  17962. return this;
  17963. };
  17964. // Methods
  17965. BoundingSphere.prototype._update = function (world) {
  17966. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17967. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17968. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17969. };
  17970. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17971. for (var i = 0; i < 6; i++) {
  17972. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17973. return false;
  17974. }
  17975. return true;
  17976. };
  17977. BoundingSphere.prototype.intersectsPoint = function (point) {
  17978. var x = this.centerWorld.x - point.x;
  17979. var y = this.centerWorld.y - point.y;
  17980. var z = this.centerWorld.z - point.z;
  17981. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17982. if (this.radiusWorld < distance)
  17983. return false;
  17984. return true;
  17985. };
  17986. // Statics
  17987. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17988. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17989. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17990. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17991. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17992. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17993. return false;
  17994. return true;
  17995. };
  17996. return BoundingSphere;
  17997. }());
  17998. BABYLON.BoundingSphere = BoundingSphere;
  17999. })(BABYLON || (BABYLON = {}));
  18000. //# sourceMappingURL=babylon.boundingSphere.js.map
  18001. var BABYLON;
  18002. (function (BABYLON) {
  18003. var BoundingBox = /** @class */ (function () {
  18004. /**
  18005. * Creates a new bounding box
  18006. * @param min defines the minimum vector (in local space)
  18007. * @param max defines the maximum vector (in local space)
  18008. */
  18009. function BoundingBox(min, max) {
  18010. this.vectorsWorld = new Array();
  18011. this.reConstruct(min, max);
  18012. }
  18013. // Methods
  18014. /**
  18015. * Recreates the entire bounding box from scratch
  18016. * @param min defines the new minimum vector (in local space)
  18017. * @param max defines the new maximum vector (in local space)
  18018. */
  18019. BoundingBox.prototype.reConstruct = function (min, max) {
  18020. this.minimum = min.clone();
  18021. this.maximum = max.clone();
  18022. // Bounding vectors
  18023. this.vectors = new Array();
  18024. this.vectors.push(this.minimum.clone());
  18025. this.vectors.push(this.maximum.clone());
  18026. this.vectors.push(this.minimum.clone());
  18027. this.vectors[2].x = this.maximum.x;
  18028. this.vectors.push(this.minimum.clone());
  18029. this.vectors[3].y = this.maximum.y;
  18030. this.vectors.push(this.minimum.clone());
  18031. this.vectors[4].z = this.maximum.z;
  18032. this.vectors.push(this.maximum.clone());
  18033. this.vectors[5].z = this.minimum.z;
  18034. this.vectors.push(this.maximum.clone());
  18035. this.vectors[6].x = this.minimum.x;
  18036. this.vectors.push(this.maximum.clone());
  18037. this.vectors[7].y = this.minimum.y;
  18038. // OBB
  18039. this.center = this.maximum.add(this.minimum).scale(0.5);
  18040. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18041. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18042. // World
  18043. for (var index = 0; index < this.vectors.length; index++) {
  18044. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18045. }
  18046. this.minimumWorld = BABYLON.Vector3.Zero();
  18047. this.maximumWorld = BABYLON.Vector3.Zero();
  18048. this.centerWorld = BABYLON.Vector3.Zero();
  18049. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18050. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18051. };
  18052. /**
  18053. * Scale the current bounding box by applying a scale factor
  18054. * @param factor defines the scale factor to apply
  18055. * @returns the current bounding box
  18056. */
  18057. BoundingBox.prototype.scale = function (factor) {
  18058. var diff = this.maximum.subtract(this.minimum);
  18059. var distance = diff.length() * factor;
  18060. diff.normalize();
  18061. var newRadius = diff.scale(distance / 2);
  18062. var min = this.center.subtract(newRadius);
  18063. var max = this.center.add(newRadius);
  18064. this.reConstruct(min, max);
  18065. return this;
  18066. };
  18067. BoundingBox.prototype.getWorldMatrix = function () {
  18068. return this._worldMatrix;
  18069. };
  18070. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18071. this._worldMatrix.copyFrom(matrix);
  18072. return this;
  18073. };
  18074. BoundingBox.prototype._update = function (world) {
  18075. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18076. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18077. for (var index = 0; index < this.vectors.length; index++) {
  18078. var v = this.vectorsWorld[index];
  18079. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18080. if (v.x < this.minimumWorld.x)
  18081. this.minimumWorld.x = v.x;
  18082. if (v.y < this.minimumWorld.y)
  18083. this.minimumWorld.y = v.y;
  18084. if (v.z < this.minimumWorld.z)
  18085. this.minimumWorld.z = v.z;
  18086. if (v.x > this.maximumWorld.x)
  18087. this.maximumWorld.x = v.x;
  18088. if (v.y > this.maximumWorld.y)
  18089. this.maximumWorld.y = v.y;
  18090. if (v.z > this.maximumWorld.z)
  18091. this.maximumWorld.z = v.z;
  18092. }
  18093. // Extend
  18094. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18095. this.extendSizeWorld.scaleInPlace(0.5);
  18096. // OBB
  18097. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18098. this.centerWorld.scaleInPlace(0.5);
  18099. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18100. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18101. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18102. this._worldMatrix = world;
  18103. };
  18104. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18105. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18106. };
  18107. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18108. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18109. };
  18110. BoundingBox.prototype.intersectsPoint = function (point) {
  18111. var delta = -BABYLON.Epsilon;
  18112. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18113. return false;
  18114. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18115. return false;
  18116. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18117. return false;
  18118. return true;
  18119. };
  18120. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18121. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18122. };
  18123. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18124. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18125. return false;
  18126. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18127. return false;
  18128. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18129. return false;
  18130. return true;
  18131. };
  18132. // Statics
  18133. BoundingBox.Intersects = function (box0, box1) {
  18134. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18135. return false;
  18136. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18137. return false;
  18138. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18139. return false;
  18140. return true;
  18141. };
  18142. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18143. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18144. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18145. return (num <= (sphereRadius * sphereRadius));
  18146. };
  18147. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18148. for (var p = 0; p < 6; p++) {
  18149. for (var i = 0; i < 8; i++) {
  18150. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18151. return false;
  18152. }
  18153. }
  18154. }
  18155. return true;
  18156. };
  18157. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18158. for (var p = 0; p < 6; p++) {
  18159. var inCount = 8;
  18160. for (var i = 0; i < 8; i++) {
  18161. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18162. --inCount;
  18163. }
  18164. else {
  18165. break;
  18166. }
  18167. }
  18168. if (inCount === 0)
  18169. return false;
  18170. }
  18171. return true;
  18172. };
  18173. return BoundingBox;
  18174. }());
  18175. BABYLON.BoundingBox = BoundingBox;
  18176. })(BABYLON || (BABYLON = {}));
  18177. //# sourceMappingURL=babylon.boundingBox.js.map
  18178. var BABYLON;
  18179. (function (BABYLON) {
  18180. var computeBoxExtents = function (axis, box) {
  18181. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18182. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18183. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18184. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18185. var r = r0 + r1 + r2;
  18186. return {
  18187. min: p - r,
  18188. max: p + r
  18189. };
  18190. };
  18191. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18192. var axisOverlap = function (axis, box0, box1) {
  18193. var result0 = computeBoxExtents(axis, box0);
  18194. var result1 = computeBoxExtents(axis, box1);
  18195. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18196. };
  18197. var BoundingInfo = /** @class */ (function () {
  18198. function BoundingInfo(minimum, maximum) {
  18199. this.minimum = minimum;
  18200. this.maximum = maximum;
  18201. this._isLocked = false;
  18202. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18203. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18204. }
  18205. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18206. get: function () {
  18207. return this._isLocked;
  18208. },
  18209. set: function (value) {
  18210. this._isLocked = value;
  18211. },
  18212. enumerable: true,
  18213. configurable: true
  18214. });
  18215. // Methods
  18216. BoundingInfo.prototype.update = function (world) {
  18217. if (this._isLocked) {
  18218. return;
  18219. }
  18220. this.boundingBox._update(world);
  18221. this.boundingSphere._update(world);
  18222. };
  18223. /**
  18224. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18225. * @param center New center of the bounding info
  18226. * @param extend New extend of the bounding info
  18227. */
  18228. BoundingInfo.prototype.centerOn = function (center, extend) {
  18229. this.minimum = center.subtract(extend);
  18230. this.maximum = center.add(extend);
  18231. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18232. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18233. return this;
  18234. };
  18235. /**
  18236. * Scale the current bounding info by applying a scale factor
  18237. * @param factor defines the scale factor to apply
  18238. * @returns the current bounding info
  18239. */
  18240. BoundingInfo.prototype.scale = function (factor) {
  18241. this.boundingBox.scale(factor);
  18242. this.boundingSphere.scale(factor);
  18243. return this;
  18244. };
  18245. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18246. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18247. return false;
  18248. return this.boundingBox.isInFrustum(frustumPlanes);
  18249. };
  18250. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18251. /**
  18252. * Gets the world distance between the min and max points of the bounding box
  18253. */
  18254. get: function () {
  18255. var boundingBox = this.boundingBox;
  18256. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18257. return size.length();
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18263. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18264. };
  18265. BoundingInfo.prototype._checkCollision = function (collider) {
  18266. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18267. };
  18268. BoundingInfo.prototype.intersectsPoint = function (point) {
  18269. if (!this.boundingSphere.centerWorld) {
  18270. return false;
  18271. }
  18272. if (!this.boundingSphere.intersectsPoint(point)) {
  18273. return false;
  18274. }
  18275. if (!this.boundingBox.intersectsPoint(point)) {
  18276. return false;
  18277. }
  18278. return true;
  18279. };
  18280. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18281. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18282. return false;
  18283. }
  18284. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18285. return false;
  18286. }
  18287. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18288. return false;
  18289. }
  18290. if (!precise) {
  18291. return true;
  18292. }
  18293. var box0 = this.boundingBox;
  18294. var box1 = boundingInfo.boundingBox;
  18295. if (!axisOverlap(box0.directions[0], box0, box1))
  18296. return false;
  18297. if (!axisOverlap(box0.directions[1], box0, box1))
  18298. return false;
  18299. if (!axisOverlap(box0.directions[2], box0, box1))
  18300. return false;
  18301. if (!axisOverlap(box1.directions[0], box0, box1))
  18302. return false;
  18303. if (!axisOverlap(box1.directions[1], box0, box1))
  18304. return false;
  18305. if (!axisOverlap(box1.directions[2], box0, box1))
  18306. return false;
  18307. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18308. return false;
  18309. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18310. return false;
  18311. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18312. return false;
  18313. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18314. return false;
  18315. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18316. return false;
  18317. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18318. return false;
  18319. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18320. return false;
  18321. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18322. return false;
  18323. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18324. return false;
  18325. return true;
  18326. };
  18327. return BoundingInfo;
  18328. }());
  18329. BABYLON.BoundingInfo = BoundingInfo;
  18330. })(BABYLON || (BABYLON = {}));
  18331. //# sourceMappingURL=babylon.boundingInfo.js.map
  18332. var BABYLON;
  18333. (function (BABYLON) {
  18334. var TransformNode = /** @class */ (function (_super) {
  18335. __extends(TransformNode, _super);
  18336. function TransformNode(name, scene, isPure) {
  18337. if (scene === void 0) { scene = null; }
  18338. if (isPure === void 0) { isPure = true; }
  18339. var _this = _super.call(this, name, scene) || this;
  18340. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18341. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18342. _this._up = new BABYLON.Vector3(0, 1, 0);
  18343. _this._right = new BABYLON.Vector3(1, 0, 0);
  18344. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18345. // Properties
  18346. _this._rotation = BABYLON.Vector3.Zero();
  18347. _this._scaling = BABYLON.Vector3.One();
  18348. _this._isDirty = false;
  18349. /**
  18350. * Set the billboard mode. Default is 0.
  18351. *
  18352. * | Value | Type | Description |
  18353. * | --- | --- | --- |
  18354. * | 0 | BILLBOARDMODE_NONE | |
  18355. * | 1 | BILLBOARDMODE_X | |
  18356. * | 2 | BILLBOARDMODE_Y | |
  18357. * | 4 | BILLBOARDMODE_Z | |
  18358. * | 7 | BILLBOARDMODE_ALL | |
  18359. *
  18360. */
  18361. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18362. _this.scalingDeterminant = 1;
  18363. _this.infiniteDistance = false;
  18364. /**
  18365. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18366. * By default the system will update normals to compensate
  18367. */
  18368. _this.ignoreNonUniformScaling = false;
  18369. _this.position = BABYLON.Vector3.Zero();
  18370. _this._localWorld = BABYLON.Matrix.Zero();
  18371. _this._worldMatrix = BABYLON.Matrix.Zero();
  18372. _this._worldMatrixDeterminant = 0;
  18373. _this._absolutePosition = BABYLON.Vector3.Zero();
  18374. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18375. _this._postMultiplyPivotMatrix = false;
  18376. _this._isWorldMatrixFrozen = false;
  18377. /**
  18378. * An event triggered after the world matrix is updated
  18379. */
  18380. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18381. _this._nonUniformScaling = false;
  18382. if (isPure) {
  18383. _this.getScene().addTransformNode(_this);
  18384. }
  18385. return _this;
  18386. }
  18387. /**
  18388. * Gets a string idenfifying the name of the class
  18389. * @returns "TransformNode" string
  18390. */
  18391. TransformNode.prototype.getClassName = function () {
  18392. return "TransformNode";
  18393. };
  18394. Object.defineProperty(TransformNode.prototype, "rotation", {
  18395. /**
  18396. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18397. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18398. * Default : (0.0, 0.0, 0.0)
  18399. */
  18400. get: function () {
  18401. return this._rotation;
  18402. },
  18403. set: function (newRotation) {
  18404. this._rotation = newRotation;
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. Object.defineProperty(TransformNode.prototype, "scaling", {
  18410. /**
  18411. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18412. * Default : (1.0, 1.0, 1.0)
  18413. */
  18414. get: function () {
  18415. return this._scaling;
  18416. },
  18417. /**
  18418. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18419. * Default : (1.0, 1.0, 1.0)
  18420. */
  18421. set: function (newScaling) {
  18422. this._scaling = newScaling;
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18428. /**
  18429. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18430. * It's null by default.
  18431. * 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)
  18432. */
  18433. get: function () {
  18434. return this._rotationQuaternion;
  18435. },
  18436. set: function (quaternion) {
  18437. this._rotationQuaternion = quaternion;
  18438. //reset the rotation vector.
  18439. if (quaternion && this.rotation.length()) {
  18440. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18441. }
  18442. },
  18443. enumerable: true,
  18444. configurable: true
  18445. });
  18446. Object.defineProperty(TransformNode.prototype, "forward", {
  18447. /**
  18448. * The forward direction of that transform in world space.
  18449. */
  18450. get: function () {
  18451. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. Object.defineProperty(TransformNode.prototype, "up", {
  18457. /**
  18458. * The up direction of that transform in world space.
  18459. */
  18460. get: function () {
  18461. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(TransformNode.prototype, "right", {
  18467. /**
  18468. * The right direction of that transform in world space.
  18469. */
  18470. get: function () {
  18471. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. /**
  18477. * Returns the latest update of the World matrix
  18478. * Returns a Matrix.
  18479. */
  18480. TransformNode.prototype.getWorldMatrix = function () {
  18481. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18482. this.computeWorldMatrix();
  18483. }
  18484. return this._worldMatrix;
  18485. };
  18486. /** @hidden */
  18487. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18488. return this._worldMatrixDeterminant;
  18489. };
  18490. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18491. /**
  18492. * Returns directly the latest state of the mesh World matrix.
  18493. * A Matrix is returned.
  18494. */
  18495. get: function () {
  18496. return this._worldMatrix;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. /**
  18502. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18503. * Returns the TransformNode.
  18504. */
  18505. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18506. this._poseMatrix.copyFrom(matrix);
  18507. return this;
  18508. };
  18509. /**
  18510. * Returns the mesh Pose matrix.
  18511. * Returned object : Matrix
  18512. */
  18513. TransformNode.prototype.getPoseMatrix = function () {
  18514. return this._poseMatrix;
  18515. };
  18516. TransformNode.prototype._isSynchronized = function () {
  18517. if (this._isDirty) {
  18518. return false;
  18519. }
  18520. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18521. return false;
  18522. if (this._cache.pivotMatrixUpdated) {
  18523. return false;
  18524. }
  18525. if (this.infiniteDistance) {
  18526. return false;
  18527. }
  18528. if (!this._cache.position.equals(this.position))
  18529. return false;
  18530. if (this.rotationQuaternion) {
  18531. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18532. return false;
  18533. }
  18534. if (!this._cache.rotation.equals(this.rotation))
  18535. return false;
  18536. if (!this._cache.scaling.equals(this.scaling))
  18537. return false;
  18538. return true;
  18539. };
  18540. TransformNode.prototype._initCache = function () {
  18541. _super.prototype._initCache.call(this);
  18542. this._cache.localMatrixUpdated = false;
  18543. this._cache.position = BABYLON.Vector3.Zero();
  18544. this._cache.scaling = BABYLON.Vector3.Zero();
  18545. this._cache.rotation = BABYLON.Vector3.Zero();
  18546. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18547. this._cache.billboardMode = -1;
  18548. };
  18549. TransformNode.prototype.markAsDirty = function (property) {
  18550. if (property === "rotation") {
  18551. this.rotationQuaternion = null;
  18552. }
  18553. this._currentRenderId = Number.MAX_VALUE;
  18554. this._isDirty = true;
  18555. return this;
  18556. };
  18557. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18558. /**
  18559. * Returns the current mesh absolute position.
  18560. * Retuns a Vector3.
  18561. */
  18562. get: function () {
  18563. return this._absolutePosition;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. /**
  18569. * Sets a new matrix to apply before all other transformation
  18570. * @param matrix defines the transform matrix
  18571. * @returns the current TransformNode
  18572. */
  18573. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18574. return this.setPivotMatrix(matrix, false);
  18575. };
  18576. /**
  18577. * Sets a new pivot matrix to the current node
  18578. * @param matrix defines the new pivot matrix to use
  18579. * @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
  18580. * @returns the current TransformNode
  18581. */
  18582. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18583. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18584. this._pivotMatrix = matrix.clone();
  18585. this._cache.pivotMatrixUpdated = true;
  18586. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18587. if (this._postMultiplyPivotMatrix) {
  18588. if (!this._pivotMatrixInverse) {
  18589. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18590. }
  18591. else {
  18592. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18593. }
  18594. }
  18595. return this;
  18596. };
  18597. /**
  18598. * Returns the mesh pivot matrix.
  18599. * Default : Identity.
  18600. * A Matrix is returned.
  18601. */
  18602. TransformNode.prototype.getPivotMatrix = function () {
  18603. return this._pivotMatrix;
  18604. };
  18605. /**
  18606. * Prevents the World matrix to be computed any longer.
  18607. * Returns the TransformNode.
  18608. */
  18609. TransformNode.prototype.freezeWorldMatrix = function () {
  18610. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18611. this.computeWorldMatrix(true);
  18612. this._isWorldMatrixFrozen = true;
  18613. return this;
  18614. };
  18615. /**
  18616. * Allows back the World matrix computation.
  18617. * Returns the TransformNode.
  18618. */
  18619. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18620. this._isWorldMatrixFrozen = false;
  18621. this.computeWorldMatrix(true);
  18622. return this;
  18623. };
  18624. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18625. /**
  18626. * True if the World matrix has been frozen.
  18627. * Returns a boolean.
  18628. */
  18629. get: function () {
  18630. return this._isWorldMatrixFrozen;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. /**
  18636. * Retuns the mesh absolute position in the World.
  18637. * Returns a Vector3.
  18638. */
  18639. TransformNode.prototype.getAbsolutePosition = function () {
  18640. this.computeWorldMatrix();
  18641. return this._absolutePosition;
  18642. };
  18643. /**
  18644. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18645. * Returns the TransformNode.
  18646. */
  18647. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18648. if (!absolutePosition) {
  18649. return this;
  18650. }
  18651. var absolutePositionX;
  18652. var absolutePositionY;
  18653. var absolutePositionZ;
  18654. if (absolutePosition.x === undefined) {
  18655. if (arguments.length < 3) {
  18656. return this;
  18657. }
  18658. absolutePositionX = arguments[0];
  18659. absolutePositionY = arguments[1];
  18660. absolutePositionZ = arguments[2];
  18661. }
  18662. else {
  18663. absolutePositionX = absolutePosition.x;
  18664. absolutePositionY = absolutePosition.y;
  18665. absolutePositionZ = absolutePosition.z;
  18666. }
  18667. if (this.parent) {
  18668. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18669. invertParentWorldMatrix.invert();
  18670. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18671. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18672. }
  18673. else {
  18674. this.position.x = absolutePositionX;
  18675. this.position.y = absolutePositionY;
  18676. this.position.z = absolutePositionZ;
  18677. }
  18678. return this;
  18679. };
  18680. /**
  18681. * Sets the mesh position in its local space.
  18682. * Returns the TransformNode.
  18683. */
  18684. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18685. this.computeWorldMatrix();
  18686. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18687. return this;
  18688. };
  18689. /**
  18690. * Returns the mesh position in the local space from the current World matrix values.
  18691. * Returns a new Vector3.
  18692. */
  18693. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18694. this.computeWorldMatrix();
  18695. var invLocalWorldMatrix = this._localWorld.clone();
  18696. invLocalWorldMatrix.invert();
  18697. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18698. };
  18699. /**
  18700. * Translates the mesh along the passed Vector3 in its local space.
  18701. * Returns the TransformNode.
  18702. */
  18703. TransformNode.prototype.locallyTranslate = function (vector3) {
  18704. this.computeWorldMatrix(true);
  18705. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18706. return this;
  18707. };
  18708. /**
  18709. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18710. * @param targetPoint the position (must be in same space as current mesh) to look at
  18711. * @param yawCor optional yaw (y-axis) correction in radians
  18712. * @param pitchCor optional pitch (x-axis) correction in radians
  18713. * @param rollCor optional roll (z-axis) correction in radians
  18714. * @param space the choosen space of the target
  18715. * @returns the TransformNode.
  18716. */
  18717. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18718. if (yawCor === void 0) { yawCor = 0; }
  18719. if (pitchCor === void 0) { pitchCor = 0; }
  18720. if (rollCor === void 0) { rollCor = 0; }
  18721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18722. var dv = TransformNode._lookAtVectorCache;
  18723. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18724. targetPoint.subtractToRef(pos, dv);
  18725. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18726. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18727. var pitch = Math.atan2(dv.y, len);
  18728. if (this.rotationQuaternion) {
  18729. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18730. }
  18731. else {
  18732. this.rotation.x = pitch + pitchCor;
  18733. this.rotation.y = yaw + yawCor;
  18734. this.rotation.z = rollCor;
  18735. }
  18736. return this;
  18737. };
  18738. /**
  18739. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18740. * This Vector3 is expressed in the World space.
  18741. */
  18742. TransformNode.prototype.getDirection = function (localAxis) {
  18743. var result = BABYLON.Vector3.Zero();
  18744. this.getDirectionToRef(localAxis, result);
  18745. return result;
  18746. };
  18747. /**
  18748. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18749. * localAxis is expressed in the mesh local space.
  18750. * result is computed in the Wordl space from the mesh World matrix.
  18751. * Returns the TransformNode.
  18752. */
  18753. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18754. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18755. return this;
  18756. };
  18757. /**
  18758. * Sets a new pivot point to the current node
  18759. * @param point defines the new pivot point to use
  18760. * @param space defines if the point is in world or local space (local by default)
  18761. * @returns the current TransformNode
  18762. */
  18763. TransformNode.prototype.setPivotPoint = function (point, space) {
  18764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18765. if (this.getScene().getRenderId() == 0) {
  18766. this.computeWorldMatrix(true);
  18767. }
  18768. var wm = this.getWorldMatrix();
  18769. if (space == BABYLON.Space.WORLD) {
  18770. var tmat = BABYLON.Tmp.Matrix[0];
  18771. wm.invertToRef(tmat);
  18772. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18773. }
  18774. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18775. };
  18776. /**
  18777. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18778. */
  18779. TransformNode.prototype.getPivotPoint = function () {
  18780. var point = BABYLON.Vector3.Zero();
  18781. this.getPivotPointToRef(point);
  18782. return point;
  18783. };
  18784. /**
  18785. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18786. * Returns the TransformNode.
  18787. */
  18788. TransformNode.prototype.getPivotPointToRef = function (result) {
  18789. result.x = -this._pivotMatrix.m[12];
  18790. result.y = -this._pivotMatrix.m[13];
  18791. result.z = -this._pivotMatrix.m[14];
  18792. return this;
  18793. };
  18794. /**
  18795. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18796. */
  18797. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18798. var point = BABYLON.Vector3.Zero();
  18799. this.getAbsolutePivotPointToRef(point);
  18800. return point;
  18801. };
  18802. /**
  18803. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18804. * Returns the TransformNode.
  18805. */
  18806. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18807. result.x = this._pivotMatrix.m[12];
  18808. result.y = this._pivotMatrix.m[13];
  18809. result.z = this._pivotMatrix.m[14];
  18810. this.getPivotPointToRef(result);
  18811. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18812. return this;
  18813. };
  18814. /**
  18815. * Defines the passed node as the parent of the current node.
  18816. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18817. * Returns the TransformNode.
  18818. */
  18819. TransformNode.prototype.setParent = function (node) {
  18820. if (!node && !this.parent) {
  18821. return this;
  18822. }
  18823. if (!node) {
  18824. var rotation = BABYLON.Tmp.Quaternion[0];
  18825. var position = BABYLON.Tmp.Vector3[0];
  18826. var scale = BABYLON.Tmp.Vector3[1];
  18827. if (this.parent && this.parent.computeWorldMatrix) {
  18828. this.parent.computeWorldMatrix(true);
  18829. }
  18830. this.computeWorldMatrix(true);
  18831. this.getWorldMatrix().decompose(scale, rotation, position);
  18832. if (this.rotationQuaternion) {
  18833. this.rotationQuaternion.copyFrom(rotation);
  18834. }
  18835. else {
  18836. rotation.toEulerAnglesToRef(this.rotation);
  18837. }
  18838. this.scaling.x = scale.x;
  18839. this.scaling.y = scale.y;
  18840. this.scaling.z = scale.z;
  18841. this.position.x = position.x;
  18842. this.position.y = position.y;
  18843. this.position.z = position.z;
  18844. }
  18845. else {
  18846. var rotation = BABYLON.Tmp.Quaternion[0];
  18847. var position = BABYLON.Tmp.Vector3[0];
  18848. var scale = BABYLON.Tmp.Vector3[1];
  18849. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18850. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18851. this.computeWorldMatrix(true);
  18852. node.computeWorldMatrix(true);
  18853. node.getWorldMatrix().invertToRef(invParentMatrix);
  18854. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18855. diffMatrix.decompose(scale, rotation, position);
  18856. if (this.rotationQuaternion) {
  18857. this.rotationQuaternion.copyFrom(rotation);
  18858. }
  18859. else {
  18860. rotation.toEulerAnglesToRef(this.rotation);
  18861. }
  18862. this.position.x = position.x;
  18863. this.position.y = position.y;
  18864. this.position.z = position.z;
  18865. this.scaling.x = scale.x;
  18866. this.scaling.y = scale.y;
  18867. this.scaling.z = scale.z;
  18868. }
  18869. this.parent = node;
  18870. return this;
  18871. };
  18872. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18873. get: function () {
  18874. return this._nonUniformScaling;
  18875. },
  18876. enumerable: true,
  18877. configurable: true
  18878. });
  18879. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18880. if (this._nonUniformScaling === value) {
  18881. return false;
  18882. }
  18883. this._nonUniformScaling = value;
  18884. return true;
  18885. };
  18886. /**
  18887. * Attach the current TransformNode to another TransformNode associated with a bone
  18888. * @param bone Bone affecting the TransformNode
  18889. * @param affectedTransformNode TransformNode associated with the bone
  18890. */
  18891. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18892. this._transformToBoneReferal = affectedTransformNode;
  18893. this.parent = bone;
  18894. if (bone.getWorldMatrix().determinant() < 0) {
  18895. this.scalingDeterminant *= -1;
  18896. }
  18897. return this;
  18898. };
  18899. TransformNode.prototype.detachFromBone = function () {
  18900. if (!this.parent) {
  18901. return this;
  18902. }
  18903. if (this.parent.getWorldMatrix().determinant() < 0) {
  18904. this.scalingDeterminant *= -1;
  18905. }
  18906. this._transformToBoneReferal = null;
  18907. this.parent = null;
  18908. return this;
  18909. };
  18910. /**
  18911. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18912. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18913. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18914. * The passed axis is also normalized.
  18915. * Returns the TransformNode.
  18916. */
  18917. TransformNode.prototype.rotate = function (axis, amount, space) {
  18918. axis.normalize();
  18919. if (!this.rotationQuaternion) {
  18920. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18921. this.rotation = BABYLON.Vector3.Zero();
  18922. }
  18923. var rotationQuaternion;
  18924. if (!space || space === BABYLON.Space.LOCAL) {
  18925. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18926. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18927. }
  18928. else {
  18929. if (this.parent) {
  18930. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18931. invertParentWorldMatrix.invert();
  18932. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18933. }
  18934. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18935. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18936. }
  18937. return this;
  18938. };
  18939. /**
  18940. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18941. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18942. * The passed axis is also normalized.
  18943. * Returns the TransformNode.
  18944. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18945. */
  18946. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18947. axis.normalize();
  18948. if (!this.rotationQuaternion) {
  18949. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18950. this.rotation.copyFromFloats(0, 0, 0);
  18951. }
  18952. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18953. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18954. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18955. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18956. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18957. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18958. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18959. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18960. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18961. return this;
  18962. };
  18963. /**
  18964. * Translates the mesh along the axis vector for the passed distance in the given space.
  18965. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18966. * Returns the TransformNode.
  18967. */
  18968. TransformNode.prototype.translate = function (axis, distance, space) {
  18969. var displacementVector = axis.scale(distance);
  18970. if (!space || space === BABYLON.Space.LOCAL) {
  18971. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18972. this.setPositionWithLocalVector(tempV3);
  18973. }
  18974. else {
  18975. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18976. }
  18977. return this;
  18978. };
  18979. /**
  18980. * Adds a rotation step to the mesh current rotation.
  18981. * x, y, z are Euler angles expressed in radians.
  18982. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18983. * This means this rotation is made in the mesh local space only.
  18984. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18985. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18986. * ```javascript
  18987. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18988. * ```
  18989. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18990. * 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.
  18991. * Returns the TransformNode.
  18992. */
  18993. TransformNode.prototype.addRotation = function (x, y, z) {
  18994. var rotationQuaternion;
  18995. if (this.rotationQuaternion) {
  18996. rotationQuaternion = this.rotationQuaternion;
  18997. }
  18998. else {
  18999. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19000. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19001. }
  19002. var accumulation = BABYLON.Tmp.Quaternion[0];
  19003. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19004. rotationQuaternion.multiplyInPlace(accumulation);
  19005. if (!this.rotationQuaternion) {
  19006. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19007. }
  19008. return this;
  19009. };
  19010. /**
  19011. * Computes the mesh World matrix and returns it.
  19012. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19013. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19014. * If the parameter `force`is set to `true`, the actual computation is done.
  19015. * Returns the mesh World Matrix.
  19016. */
  19017. TransformNode.prototype.computeWorldMatrix = function (force) {
  19018. if (this._isWorldMatrixFrozen) {
  19019. return this._worldMatrix;
  19020. }
  19021. if (!force && this.isSynchronized(true)) {
  19022. this._currentRenderId = this.getScene().getRenderId();
  19023. return this._worldMatrix;
  19024. }
  19025. this._cache.position.copyFrom(this.position);
  19026. this._cache.scaling.copyFrom(this.scaling);
  19027. this._cache.pivotMatrixUpdated = false;
  19028. this._cache.billboardMode = this.billboardMode;
  19029. this._currentRenderId = this.getScene().getRenderId();
  19030. this._childRenderId = this.getScene().getRenderId();
  19031. this._isDirty = false;
  19032. // Scaling
  19033. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19034. // Rotation
  19035. //rotate, if quaternion is set and rotation was used
  19036. if (this.rotationQuaternion) {
  19037. var len = this.rotation.length();
  19038. if (len) {
  19039. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19040. this.rotation.copyFromFloats(0, 0, 0);
  19041. }
  19042. }
  19043. if (this.rotationQuaternion) {
  19044. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19045. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19046. }
  19047. else {
  19048. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19049. this._cache.rotation.copyFrom(this.rotation);
  19050. }
  19051. // Translation
  19052. var camera = this.getScene().activeCamera;
  19053. if (this.infiniteDistance && !this.parent && camera) {
  19054. var cameraWorldMatrix = camera.getWorldMatrix();
  19055. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19056. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19057. }
  19058. else {
  19059. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19060. }
  19061. // Composing transformations
  19062. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19063. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19064. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19065. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19066. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19067. // Need to decompose each rotation here
  19068. var currentPosition = BABYLON.Tmp.Vector3[3];
  19069. if (this.parent && this.parent.getWorldMatrix) {
  19070. if (this._transformToBoneReferal) {
  19071. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19072. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19073. }
  19074. else {
  19075. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19076. }
  19077. }
  19078. else {
  19079. currentPosition.copyFrom(this.position);
  19080. }
  19081. currentPosition.subtractInPlace(camera.globalPosition);
  19082. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19083. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19084. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19085. }
  19086. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19087. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19088. }
  19089. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19090. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19091. }
  19092. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19093. }
  19094. else {
  19095. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19096. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19097. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19098. }
  19099. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19100. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19101. }
  19102. // Post multiply inverse of pivotMatrix
  19103. if (this._postMultiplyPivotMatrix) {
  19104. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19105. }
  19106. // Local world
  19107. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19108. // Parent
  19109. if (this.parent && this.parent.getWorldMatrix) {
  19110. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19111. if (this._transformToBoneReferal) {
  19112. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19113. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19114. }
  19115. else {
  19116. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19117. }
  19118. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19119. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19120. this._worldMatrix.copyFrom(this._localWorld);
  19121. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19122. }
  19123. else {
  19124. if (this._transformToBoneReferal) {
  19125. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19126. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19127. }
  19128. else {
  19129. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19130. }
  19131. }
  19132. this._markSyncedWithParent();
  19133. }
  19134. else {
  19135. this._worldMatrix.copyFrom(this._localWorld);
  19136. }
  19137. // Normal matrix
  19138. if (!this.ignoreNonUniformScaling) {
  19139. if (this.scaling.isNonUniform) {
  19140. this._updateNonUniformScalingState(true);
  19141. }
  19142. else if (this.parent && this.parent._nonUniformScaling) {
  19143. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19144. }
  19145. else {
  19146. this._updateNonUniformScalingState(false);
  19147. }
  19148. }
  19149. else {
  19150. this._updateNonUniformScalingState(false);
  19151. }
  19152. this._afterComputeWorldMatrix();
  19153. // Absolute position
  19154. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19155. // Callbacks
  19156. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19157. if (!this._poseMatrix) {
  19158. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19159. }
  19160. // Cache the determinant
  19161. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19162. return this._worldMatrix;
  19163. };
  19164. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19165. };
  19166. /**
  19167. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19168. * @param func: callback function to add
  19169. *
  19170. * Returns the TransformNode.
  19171. */
  19172. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19173. this.onAfterWorldMatrixUpdateObservable.add(func);
  19174. return this;
  19175. };
  19176. /**
  19177. * Removes a registered callback function.
  19178. * Returns the TransformNode.
  19179. */
  19180. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19181. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19182. return this;
  19183. };
  19184. /**
  19185. * Clone the current transform node
  19186. * Returns the new transform node
  19187. * @param name Name of the new clone
  19188. * @param newParent New parent for the clone
  19189. * @param doNotCloneChildren Do not clone children hierarchy
  19190. */
  19191. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19192. var _this = this;
  19193. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19194. result.name = name;
  19195. result.id = name;
  19196. if (newParent) {
  19197. result.parent = newParent;
  19198. }
  19199. if (!doNotCloneChildren) {
  19200. // Children
  19201. var directDescendants = this.getDescendants(true);
  19202. for (var index = 0; index < directDescendants.length; index++) {
  19203. var child = directDescendants[index];
  19204. if (child.clone) {
  19205. child.clone(name + "." + child.name, result);
  19206. }
  19207. }
  19208. }
  19209. return result;
  19210. };
  19211. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19212. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19213. serializationObject.type = this.getClassName();
  19214. // Parent
  19215. if (this.parent) {
  19216. serializationObject.parentId = this.parent.id;
  19217. }
  19218. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19219. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19220. }
  19221. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19222. serializationObject.isEnabled = this.isEnabled();
  19223. // Parent
  19224. if (this.parent) {
  19225. serializationObject.parentId = this.parent.id;
  19226. }
  19227. return serializationObject;
  19228. };
  19229. // Statics
  19230. /**
  19231. * Returns a new TransformNode object parsed from the source provided.
  19232. * The parameter `parsedMesh` is the source.
  19233. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19234. */
  19235. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19236. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19237. if (BABYLON.Tags) {
  19238. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19239. }
  19240. if (parsedTransformNode.localMatrix) {
  19241. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19242. }
  19243. else if (parsedTransformNode.pivotMatrix) {
  19244. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19245. }
  19246. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19247. // Parent
  19248. if (parsedTransformNode.parentId) {
  19249. transformNode._waitingParentId = parsedTransformNode.parentId;
  19250. }
  19251. return transformNode;
  19252. };
  19253. /**
  19254. * Releases resources associated with this transform node.
  19255. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19256. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19257. */
  19258. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19260. // Animations
  19261. this.getScene().stopAnimation(this);
  19262. // Remove from scene
  19263. this.getScene().removeTransformNode(this);
  19264. this.onAfterWorldMatrixUpdateObservable.clear();
  19265. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19266. };
  19267. // Statics
  19268. TransformNode.BILLBOARDMODE_NONE = 0;
  19269. TransformNode.BILLBOARDMODE_X = 1;
  19270. TransformNode.BILLBOARDMODE_Y = 2;
  19271. TransformNode.BILLBOARDMODE_Z = 4;
  19272. TransformNode.BILLBOARDMODE_ALL = 7;
  19273. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19274. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19275. __decorate([
  19276. BABYLON.serializeAsVector3()
  19277. ], TransformNode.prototype, "_rotation", void 0);
  19278. __decorate([
  19279. BABYLON.serializeAsQuaternion()
  19280. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19281. __decorate([
  19282. BABYLON.serializeAsVector3()
  19283. ], TransformNode.prototype, "_scaling", void 0);
  19284. __decorate([
  19285. BABYLON.serialize()
  19286. ], TransformNode.prototype, "billboardMode", void 0);
  19287. __decorate([
  19288. BABYLON.serialize()
  19289. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19290. __decorate([
  19291. BABYLON.serialize()
  19292. ], TransformNode.prototype, "infiniteDistance", void 0);
  19293. __decorate([
  19294. BABYLON.serialize()
  19295. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19296. __decorate([
  19297. BABYLON.serializeAsVector3()
  19298. ], TransformNode.prototype, "position", void 0);
  19299. return TransformNode;
  19300. }(BABYLON.Node));
  19301. BABYLON.TransformNode = TransformNode;
  19302. })(BABYLON || (BABYLON = {}));
  19303. //# sourceMappingURL=babylon.transformNode.js.map
  19304. var BABYLON;
  19305. (function (BABYLON) {
  19306. /**
  19307. * Class used to store all common mesh properties
  19308. */
  19309. var AbstractMesh = /** @class */ (function (_super) {
  19310. __extends(AbstractMesh, _super);
  19311. // Constructor
  19312. /**
  19313. * Creates a new AbstractMesh
  19314. * @param name defines the name of the mesh
  19315. * @param scene defines the hosting scene
  19316. */
  19317. function AbstractMesh(name, scene) {
  19318. if (scene === void 0) { scene = null; }
  19319. var _this = _super.call(this, name, scene, false) || this;
  19320. _this._facetNb = 0; // facet number
  19321. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19322. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19323. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19324. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19325. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19326. _this._subDiv = {
  19327. max: 1,
  19328. X: 1,
  19329. Y: 1,
  19330. Z: 1
  19331. };
  19332. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19333. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19334. // Events
  19335. /**
  19336. * An event triggered when this mesh collides with another one
  19337. */
  19338. _this.onCollideObservable = new BABYLON.Observable();
  19339. /**
  19340. * An event triggered when the collision's position changes
  19341. */
  19342. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19343. /**
  19344. * An event triggered when material is changed
  19345. */
  19346. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19347. // Properties
  19348. /**
  19349. * Gets or sets the orientation for POV movement & rotation
  19350. */
  19351. _this.definedFacingForward = true;
  19352. /**
  19353. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19354. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19355. * * 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.
  19356. * @see http://doc.babylonjs.com/features/occlusionquery
  19357. */
  19358. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19359. /**
  19360. * 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:
  19361. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19362. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19363. * * 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.
  19364. * @see http://doc.babylonjs.com/features/occlusionquery
  19365. */
  19366. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19367. /**
  19368. * 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.
  19369. * The default value is -1 which means don't break the query and wait till the result
  19370. * @see http://doc.babylonjs.com/features/occlusionquery
  19371. */
  19372. _this.occlusionRetryCount = -1;
  19373. /** @hidden */
  19374. _this._occlusionInternalRetryCounter = 0;
  19375. /** @hidden */
  19376. _this._isOccluded = false;
  19377. /** @hidden */
  19378. _this._isOcclusionQueryInProgress = false;
  19379. _this._visibility = 1.0;
  19380. /** Gets or sets the alpha index used to sort transparent meshes
  19381. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19382. */
  19383. _this.alphaIndex = Number.MAX_VALUE;
  19384. /**
  19385. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19386. */
  19387. _this.isVisible = true;
  19388. /**
  19389. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19390. */
  19391. _this.isPickable = true;
  19392. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19393. _this.showSubMeshesBoundingBox = false;
  19394. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19395. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19396. */
  19397. _this.isBlocker = false;
  19398. /**
  19399. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19400. */
  19401. _this.enablePointerMoveEvents = false;
  19402. /**
  19403. * Specifies the rendering group id for this mesh (0 by default)
  19404. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19405. */
  19406. _this.renderingGroupId = 0;
  19407. _this._receiveShadows = false;
  19408. /**
  19409. * Gets or sets a boolean indicating if the outline must be rendered as well
  19410. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19411. */
  19412. _this.renderOutline = false;
  19413. /** Defines color to use when rendering outline */
  19414. _this.outlineColor = BABYLON.Color3.Red();
  19415. /** Define width to use when rendering outline */
  19416. _this.outlineWidth = 0.02;
  19417. /**
  19418. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19419. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19420. */
  19421. _this.renderOverlay = false;
  19422. /** Defines color to use when rendering overlay */
  19423. _this.overlayColor = BABYLON.Color3.Red();
  19424. /** Defines alpha to use when rendering overlay */
  19425. _this.overlayAlpha = 0.5;
  19426. _this._hasVertexAlpha = false;
  19427. _this._useVertexColors = true;
  19428. _this._computeBonesUsingShaders = true;
  19429. _this._numBoneInfluencers = 4;
  19430. _this._applyFog = true;
  19431. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19432. _this.useOctreeForRenderingSelection = true;
  19433. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19434. _this.useOctreeForPicking = true;
  19435. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19436. _this.useOctreeForCollisions = true;
  19437. _this._layerMask = 0x0FFFFFFF;
  19438. /**
  19439. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19440. */
  19441. _this.alwaysSelectAsActiveMesh = false;
  19442. /**
  19443. * Gets or sets the current action manager
  19444. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19445. */
  19446. _this.actionManager = null;
  19447. /**
  19448. * Gets or sets impostor used for physic simulation
  19449. * @see http://doc.babylonjs.com/features/physics_engine
  19450. */
  19451. _this.physicsImpostor = null;
  19452. // Collisions
  19453. _this._checkCollisions = false;
  19454. _this._collisionMask = -1;
  19455. _this._collisionGroup = -1;
  19456. /**
  19457. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19458. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19459. */
  19460. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19461. /**
  19462. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19463. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19464. */
  19465. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19466. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19467. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19468. // Edges
  19469. /**
  19470. * Defines edge width used when edgesRenderer is enabled
  19471. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19472. */
  19473. _this.edgesWidth = 1;
  19474. /**
  19475. * Defines edge color used when edgesRenderer is enabled
  19476. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19477. */
  19478. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19479. // Cache
  19480. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19481. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19482. /** @hidden */
  19483. _this._renderId = 0;
  19484. /** @hidden */
  19485. _this._intersectionsInProgress = new Array();
  19486. /** @hidden */
  19487. _this._unIndexed = false;
  19488. /** @hidden */
  19489. _this._lightSources = new Array();
  19490. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19491. if (collidedMesh === void 0) { collidedMesh = null; }
  19492. //TODO move this to the collision coordinator!
  19493. if (_this.getScene().workerCollisions)
  19494. newPosition.multiplyInPlace(_this._collider._radius);
  19495. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19496. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19497. _this.position.addInPlace(_this._diffPositionForCollisions);
  19498. }
  19499. if (collidedMesh) {
  19500. _this.onCollideObservable.notifyObservers(collidedMesh);
  19501. }
  19502. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19503. };
  19504. _this.getScene().addMesh(_this);
  19505. _this._resyncLightSources();
  19506. return _this;
  19507. }
  19508. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19509. /**
  19510. * No billboard
  19511. */
  19512. get: function () {
  19513. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19519. /** Billboard on X axis */
  19520. get: function () {
  19521. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19527. /** Billboard on Y axis */
  19528. get: function () {
  19529. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19530. },
  19531. enumerable: true,
  19532. configurable: true
  19533. });
  19534. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19535. /** Billboard on Z axis */
  19536. get: function () {
  19537. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19543. /** Billboard on all axes */
  19544. get: function () {
  19545. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19551. /**
  19552. * Gets the number of facets in the mesh
  19553. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19554. */
  19555. get: function () {
  19556. return this._facetNb;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19562. /**
  19563. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19564. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19565. */
  19566. get: function () {
  19567. return this._partitioningSubdivisions;
  19568. },
  19569. set: function (nb) {
  19570. this._partitioningSubdivisions = nb;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19576. /**
  19577. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19578. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19579. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19580. */
  19581. get: function () {
  19582. return this._partitioningBBoxRatio;
  19583. },
  19584. set: function (ratio) {
  19585. this._partitioningBBoxRatio = ratio;
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19591. /**
  19592. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19593. * Works only for updatable meshes.
  19594. * Doesn't work with multi-materials
  19595. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19596. */
  19597. get: function () {
  19598. return this._facetDepthSort;
  19599. },
  19600. set: function (sort) {
  19601. this._facetDepthSort = sort;
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19607. /**
  19608. * The location (Vector3) where the facet depth sort must be computed from.
  19609. * By default, the active camera position.
  19610. * Used only when facet depth sort is enabled
  19611. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19612. */
  19613. get: function () {
  19614. return this._facetDepthSortFrom;
  19615. },
  19616. set: function (location) {
  19617. this._facetDepthSortFrom = location;
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19623. /**
  19624. * gets a boolean indicating if facetData is enabled
  19625. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19626. */
  19627. get: function () {
  19628. return this._facetDataEnabled;
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. /** @hidden */
  19634. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19635. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19636. return false;
  19637. }
  19638. this._markSubMeshesAsMiscDirty();
  19639. return true;
  19640. };
  19641. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19642. /** Set a function to call when this mesh collides with another one */
  19643. set: function (callback) {
  19644. if (this._onCollideObserver) {
  19645. this.onCollideObservable.remove(this._onCollideObserver);
  19646. }
  19647. this._onCollideObserver = this.onCollideObservable.add(callback);
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19653. /** Set a function to call when the collision's position changes */
  19654. set: function (callback) {
  19655. if (this._onCollisionPositionChangeObserver) {
  19656. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19657. }
  19658. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19659. },
  19660. enumerable: true,
  19661. configurable: true
  19662. });
  19663. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19664. /**
  19665. * 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
  19666. * @see http://doc.babylonjs.com/features/occlusionquery
  19667. */
  19668. get: function () {
  19669. return this._isOccluded;
  19670. },
  19671. set: function (value) {
  19672. this._isOccluded = value;
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19678. /**
  19679. * Flag to check the progress status of the query
  19680. * @see http://doc.babylonjs.com/features/occlusionquery
  19681. */
  19682. get: function () {
  19683. return this._isOcclusionQueryInProgress;
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19689. /**
  19690. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19691. */
  19692. get: function () {
  19693. return this._visibility;
  19694. },
  19695. /**
  19696. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19697. */
  19698. set: function (value) {
  19699. if (this._visibility === value) {
  19700. return;
  19701. }
  19702. this._visibility = value;
  19703. this._markSubMeshesAsMiscDirty();
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh.prototype, "material", {
  19709. /** Gets or sets current material */
  19710. get: function () {
  19711. return this._material;
  19712. },
  19713. set: function (value) {
  19714. if (this._material === value) {
  19715. return;
  19716. }
  19717. this._material = value;
  19718. if (this.onMaterialChangedObservable.hasObservers) {
  19719. this.onMaterialChangedObservable.notifyObservers(this);
  19720. }
  19721. if (!this.subMeshes) {
  19722. return;
  19723. }
  19724. this._unBindEffect();
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19730. /**
  19731. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19732. * @see http://doc.babylonjs.com/babylon101/shadows
  19733. */
  19734. get: function () {
  19735. return this._receiveShadows;
  19736. },
  19737. set: function (value) {
  19738. if (this._receiveShadows === value) {
  19739. return;
  19740. }
  19741. this._receiveShadows = value;
  19742. this._markSubMeshesAsLightDirty();
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19748. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19749. get: function () {
  19750. return this._hasVertexAlpha;
  19751. },
  19752. set: function (value) {
  19753. if (this._hasVertexAlpha === value) {
  19754. return;
  19755. }
  19756. this._hasVertexAlpha = value;
  19757. this._markSubMeshesAsAttributesDirty();
  19758. this._markSubMeshesAsMiscDirty();
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19764. /** 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) */
  19765. get: function () {
  19766. return this._useVertexColors;
  19767. },
  19768. set: function (value) {
  19769. if (this._useVertexColors === value) {
  19770. return;
  19771. }
  19772. this._useVertexColors = value;
  19773. this._markSubMeshesAsAttributesDirty();
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19779. /**
  19780. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19781. */
  19782. get: function () {
  19783. return this._computeBonesUsingShaders;
  19784. },
  19785. set: function (value) {
  19786. if (this._computeBonesUsingShaders === value) {
  19787. return;
  19788. }
  19789. this._computeBonesUsingShaders = value;
  19790. this._markSubMeshesAsAttributesDirty();
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19796. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19797. get: function () {
  19798. return this._numBoneInfluencers;
  19799. },
  19800. set: function (value) {
  19801. if (this._numBoneInfluencers === value) {
  19802. return;
  19803. }
  19804. this._numBoneInfluencers = value;
  19805. this._markSubMeshesAsAttributesDirty();
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19811. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19812. get: function () {
  19813. return this._applyFog;
  19814. },
  19815. set: function (value) {
  19816. if (this._applyFog === value) {
  19817. return;
  19818. }
  19819. this._applyFog = value;
  19820. this._markSubMeshesAsMiscDirty();
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19826. /**
  19827. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19828. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19829. */
  19830. get: function () {
  19831. return this._layerMask;
  19832. },
  19833. set: function (value) {
  19834. if (value === this._layerMask) {
  19835. return;
  19836. }
  19837. this._layerMask = value;
  19838. this._resyncLightSources();
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19844. /**
  19845. * Gets or sets a collision mask used to mask collisions (default is -1).
  19846. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19847. */
  19848. get: function () {
  19849. return this._collisionMask;
  19850. },
  19851. set: function (mask) {
  19852. this._collisionMask = !isNaN(mask) ? mask : -1;
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19858. /**
  19859. * Gets or sets the current collision group mask (-1 by default).
  19860. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19861. */
  19862. get: function () {
  19863. return this._collisionGroup;
  19864. },
  19865. set: function (mask) {
  19866. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19872. /** @hidden */
  19873. get: function () {
  19874. return null;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19880. get: function () {
  19881. return this._skeleton;
  19882. },
  19883. /**
  19884. * Gets or sets a skeleton to apply skining transformations
  19885. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19886. */
  19887. set: function (value) {
  19888. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19889. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19890. }
  19891. if (value && value.needInitialSkinMatrix) {
  19892. value._registerMeshWithPoseMatrix(this);
  19893. }
  19894. this._skeleton = value;
  19895. if (!this._skeleton) {
  19896. this._bonesTransformMatrices = null;
  19897. }
  19898. this._markSubMeshesAsAttributesDirty();
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. /**
  19904. * Returns the string "AbstractMesh"
  19905. * @returns "AbstractMesh"
  19906. */
  19907. AbstractMesh.prototype.getClassName = function () {
  19908. return "AbstractMesh";
  19909. };
  19910. /**
  19911. * Gets a string representation of the current mesh
  19912. * @param fullDetails defines a boolean indicating if full details must be included
  19913. * @returns a string representation of the current mesh
  19914. */
  19915. AbstractMesh.prototype.toString = function (fullDetails) {
  19916. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19917. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19918. if (this._skeleton) {
  19919. ret += ", skeleton: " + this._skeleton.name;
  19920. }
  19921. if (fullDetails) {
  19922. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19923. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19924. }
  19925. return ret;
  19926. };
  19927. /** @hidden */
  19928. AbstractMesh.prototype._rebuild = function () {
  19929. if (this._occlusionQuery) {
  19930. this._occlusionQuery = null;
  19931. }
  19932. if (this._edgesRenderer) {
  19933. this._edgesRenderer._rebuild();
  19934. }
  19935. if (!this.subMeshes) {
  19936. return;
  19937. }
  19938. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19939. var subMesh = _a[_i];
  19940. subMesh._rebuild();
  19941. }
  19942. };
  19943. /** @hidden */
  19944. AbstractMesh.prototype._resyncLightSources = function () {
  19945. this._lightSources.length = 0;
  19946. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19947. var light = _a[_i];
  19948. if (!light.isEnabled()) {
  19949. continue;
  19950. }
  19951. if (light.canAffectMesh(this)) {
  19952. this._lightSources.push(light);
  19953. }
  19954. }
  19955. this._markSubMeshesAsLightDirty();
  19956. };
  19957. /** @hidden */
  19958. AbstractMesh.prototype._resyncLighSource = function (light) {
  19959. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19960. var index = this._lightSources.indexOf(light);
  19961. if (index === -1) {
  19962. if (!isIn) {
  19963. return;
  19964. }
  19965. this._lightSources.push(light);
  19966. }
  19967. else {
  19968. if (isIn) {
  19969. return;
  19970. }
  19971. this._lightSources.splice(index, 1);
  19972. }
  19973. this._markSubMeshesAsLightDirty();
  19974. };
  19975. /** @hidden */
  19976. AbstractMesh.prototype._unBindEffect = function () {
  19977. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19978. var subMesh = _a[_i];
  19979. subMesh.setEffect(null);
  19980. }
  19981. };
  19982. /** @hidden */
  19983. AbstractMesh.prototype._removeLightSource = function (light) {
  19984. var index = this._lightSources.indexOf(light);
  19985. if (index === -1) {
  19986. return;
  19987. }
  19988. this._lightSources.splice(index, 1);
  19989. this._markSubMeshesAsLightDirty();
  19990. };
  19991. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19992. if (!this.subMeshes) {
  19993. return;
  19994. }
  19995. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19996. var subMesh = _a[_i];
  19997. if (subMesh._materialDefines) {
  19998. func(subMesh._materialDefines);
  19999. }
  20000. }
  20001. };
  20002. /** @hidden */
  20003. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20004. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20005. };
  20006. /** @hidden */
  20007. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20008. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20009. };
  20010. /** @hidden */
  20011. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20012. if (!this.subMeshes) {
  20013. return;
  20014. }
  20015. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20016. var subMesh = _a[_i];
  20017. var material = subMesh.getMaterial();
  20018. if (material) {
  20019. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20020. }
  20021. }
  20022. };
  20023. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20024. /**
  20025. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20026. */
  20027. get: function () {
  20028. return this._scaling;
  20029. },
  20030. set: function (newScaling) {
  20031. this._scaling = newScaling;
  20032. if (this.physicsImpostor) {
  20033. this.physicsImpostor.forceUpdate();
  20034. }
  20035. },
  20036. enumerable: true,
  20037. configurable: true
  20038. });
  20039. // Methods
  20040. /**
  20041. * Disables the mesh edge rendering mode
  20042. * @returns the currentAbstractMesh
  20043. */
  20044. AbstractMesh.prototype.disableEdgesRendering = function () {
  20045. if (this._edgesRenderer) {
  20046. this._edgesRenderer.dispose();
  20047. this._edgesRenderer = null;
  20048. }
  20049. return this;
  20050. };
  20051. /**
  20052. * Enables the edge rendering mode on the mesh.
  20053. * This mode makes the mesh edges visible
  20054. * @param epsilon defines the maximal distance between two angles to detect a face
  20055. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20056. * @returns the currentAbstractMesh
  20057. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20058. */
  20059. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20060. if (epsilon === void 0) { epsilon = 0.95; }
  20061. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20062. this.disableEdgesRendering();
  20063. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20064. return this;
  20065. };
  20066. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20067. /**
  20068. * Gets the edgesRenderer associated with the mesh
  20069. */
  20070. get: function () {
  20071. return this._edgesRenderer;
  20072. },
  20073. enumerable: true,
  20074. configurable: true
  20075. });
  20076. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20077. /**
  20078. * Returns true if the mesh is blocked. Implemented by child classes
  20079. */
  20080. get: function () {
  20081. return false;
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. /**
  20087. * Returns the mesh itself by default. Implemented by child classes
  20088. * @param camera defines the camera to use to pick the right LOD level
  20089. * @returns the currentAbstractMesh
  20090. */
  20091. AbstractMesh.prototype.getLOD = function (camera) {
  20092. return this;
  20093. };
  20094. /**
  20095. * Returns 0 by default. Implemented by child classes
  20096. * @returns an integer
  20097. */
  20098. AbstractMesh.prototype.getTotalVertices = function () {
  20099. return 0;
  20100. };
  20101. /**
  20102. * Returns null by default. Implemented by child classes
  20103. * @returns null
  20104. */
  20105. AbstractMesh.prototype.getIndices = function () {
  20106. return null;
  20107. };
  20108. /**
  20109. * Returns the array of the requested vertex data kind. Implemented by child classes
  20110. * @param kind defines the vertex data kind to use
  20111. * @returns null
  20112. */
  20113. AbstractMesh.prototype.getVerticesData = function (kind) {
  20114. return null;
  20115. };
  20116. /**
  20117. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20118. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20119. * Note that a new underlying VertexBuffer object is created each call.
  20120. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20121. * @param kind defines vertex data kind:
  20122. * * BABYLON.VertexBuffer.PositionKind
  20123. * * BABYLON.VertexBuffer.UVKind
  20124. * * BABYLON.VertexBuffer.UV2Kind
  20125. * * BABYLON.VertexBuffer.UV3Kind
  20126. * * BABYLON.VertexBuffer.UV4Kind
  20127. * * BABYLON.VertexBuffer.UV5Kind
  20128. * * BABYLON.VertexBuffer.UV6Kind
  20129. * * BABYLON.VertexBuffer.ColorKind
  20130. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20131. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20132. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20133. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20134. * @param data defines the data source
  20135. * @param updatable defines if the data must be flagged as updatable (or static)
  20136. * @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
  20137. * @returns the current mesh
  20138. */
  20139. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20140. return this;
  20141. };
  20142. /**
  20143. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20144. * If the mesh has no geometry, it is simply returned as it is.
  20145. * @param kind defines vertex data kind:
  20146. * * BABYLON.VertexBuffer.PositionKind
  20147. * * BABYLON.VertexBuffer.UVKind
  20148. * * BABYLON.VertexBuffer.UV2Kind
  20149. * * BABYLON.VertexBuffer.UV3Kind
  20150. * * BABYLON.VertexBuffer.UV4Kind
  20151. * * BABYLON.VertexBuffer.UV5Kind
  20152. * * BABYLON.VertexBuffer.UV6Kind
  20153. * * BABYLON.VertexBuffer.ColorKind
  20154. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20155. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20156. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20157. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20158. * @param data defines the data source
  20159. * @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
  20160. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20161. * @returns the current mesh
  20162. */
  20163. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20164. return this;
  20165. };
  20166. /**
  20167. * Sets the mesh indices,
  20168. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20169. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20170. * @param totalVertices Defines the total number of vertices
  20171. * @returns the current mesh
  20172. */
  20173. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20174. return this;
  20175. };
  20176. /**
  20177. * Gets a boolean indicating if specific vertex data is present
  20178. * @param kind defines the vertex data kind to use
  20179. * @returns true is data kind is present
  20180. */
  20181. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20182. return false;
  20183. };
  20184. /**
  20185. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20186. * @returns a BoundingInfo
  20187. */
  20188. AbstractMesh.prototype.getBoundingInfo = function () {
  20189. if (this._masterMesh) {
  20190. return this._masterMesh.getBoundingInfo();
  20191. }
  20192. if (!this._boundingInfo) {
  20193. // this._boundingInfo is being created here
  20194. this._updateBoundingInfo();
  20195. }
  20196. // cannot be null.
  20197. return this._boundingInfo;
  20198. };
  20199. /**
  20200. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20201. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20202. * @returns the current mesh
  20203. */
  20204. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20205. if (includeDescendants === void 0) { includeDescendants = true; }
  20206. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20207. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20208. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20209. if (maxDimension === 0) {
  20210. return this;
  20211. }
  20212. var scale = 1 / maxDimension;
  20213. this.scaling.scaleInPlace(scale);
  20214. return this;
  20215. };
  20216. /**
  20217. * Overwrite the current bounding info
  20218. * @param boundingInfo defines the new bounding info
  20219. * @returns the current mesh
  20220. */
  20221. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20222. this._boundingInfo = boundingInfo;
  20223. return this;
  20224. };
  20225. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20226. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20227. get: function () {
  20228. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20229. },
  20230. enumerable: true,
  20231. configurable: true
  20232. });
  20233. /** @hidden */
  20234. AbstractMesh.prototype._preActivate = function () {
  20235. };
  20236. /** @hidden */
  20237. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20238. };
  20239. /** @hidden */
  20240. AbstractMesh.prototype._activate = function (renderId) {
  20241. this._renderId = renderId;
  20242. };
  20243. /**
  20244. * Gets the current world matrix
  20245. * @returns a Matrix
  20246. */
  20247. AbstractMesh.prototype.getWorldMatrix = function () {
  20248. if (this._masterMesh) {
  20249. return this._masterMesh.getWorldMatrix();
  20250. }
  20251. return _super.prototype.getWorldMatrix.call(this);
  20252. };
  20253. /** @hidden */
  20254. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20255. if (this._masterMesh) {
  20256. return this._masterMesh._getWorldMatrixDeterminant();
  20257. }
  20258. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20259. };
  20260. // ================================== Point of View Movement =================================
  20261. /**
  20262. * Perform relative position change from the point of view of behind the front of the mesh.
  20263. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20264. * Supports definition of mesh facing forward or backward
  20265. * @param amountRight defines the distance on the right axis
  20266. * @param amountUp defines the distance on the up axis
  20267. * @param amountForward defines the distance on the forward axis
  20268. * @returns the current mesh
  20269. */
  20270. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20271. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20272. return this;
  20273. };
  20274. /**
  20275. * Calculate relative position change from the point of view of behind the front of the mesh.
  20276. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20277. * Supports definition of mesh facing forward or backward
  20278. * @param amountRight defines the distance on the right axis
  20279. * @param amountUp defines the distance on the up axis
  20280. * @param amountForward defines the distance on the forward axis
  20281. * @returns the new displacement vector
  20282. */
  20283. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20284. var rotMatrix = new BABYLON.Matrix();
  20285. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20286. rotQuaternion.toRotationMatrix(rotMatrix);
  20287. var translationDelta = BABYLON.Vector3.Zero();
  20288. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20290. return translationDelta;
  20291. };
  20292. // ================================== Point of View Rotation =================================
  20293. /**
  20294. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20295. * Supports definition of mesh facing forward or backward
  20296. * @param flipBack defines the flip
  20297. * @param twirlClockwise defines the twirl
  20298. * @param tiltRight defines the tilt
  20299. * @returns the current mesh
  20300. */
  20301. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20302. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20303. return this;
  20304. };
  20305. /**
  20306. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20307. * Supports definition of mesh facing forward or backward.
  20308. * @param flipBack defines the flip
  20309. * @param twirlClockwise defines the twirl
  20310. * @param tiltRight defines the tilt
  20311. * @returns the new rotation vector
  20312. */
  20313. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20314. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20315. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20316. };
  20317. /**
  20318. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20319. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20320. * @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
  20321. * @returns the new bounding vectors
  20322. */
  20323. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20324. if (includeDescendants === void 0) { includeDescendants = true; }
  20325. if (predicate === void 0) { predicate = null; }
  20326. // Ensures that all world matrix will be recomputed.
  20327. this.getScene().incrementRenderId();
  20328. this.computeWorldMatrix(true);
  20329. var min;
  20330. var max;
  20331. var boundingInfo = this.getBoundingInfo();
  20332. if (!this.subMeshes) {
  20333. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20334. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20335. }
  20336. else {
  20337. min = boundingInfo.boundingBox.minimumWorld;
  20338. max = boundingInfo.boundingBox.maximumWorld;
  20339. }
  20340. if (includeDescendants) {
  20341. var descendants = this.getDescendants(false);
  20342. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20343. var descendant = descendants_1[_i];
  20344. var childMesh = descendant;
  20345. childMesh.computeWorldMatrix(true);
  20346. // Filters meshes based on custom predicate function.
  20347. if (predicate && !predicate(childMesh)) {
  20348. continue;
  20349. }
  20350. //make sure we have the needed params to get mix and max
  20351. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20352. continue;
  20353. }
  20354. var childBoundingInfo = childMesh.getBoundingInfo();
  20355. var boundingBox = childBoundingInfo.boundingBox;
  20356. var minBox = boundingBox.minimumWorld;
  20357. var maxBox = boundingBox.maximumWorld;
  20358. BABYLON.Tools.CheckExtends(minBox, min, max);
  20359. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20360. }
  20361. }
  20362. return {
  20363. min: min,
  20364. max: max
  20365. };
  20366. };
  20367. /** @hidden */
  20368. AbstractMesh.prototype._updateBoundingInfo = function () {
  20369. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20370. this._boundingInfo.update(this.worldMatrixFromCache);
  20371. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20372. return this;
  20373. };
  20374. /** @hidden */
  20375. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20376. if (!this.subMeshes) {
  20377. return this;
  20378. }
  20379. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20380. var subMesh = this.subMeshes[subIndex];
  20381. if (!subMesh.IsGlobal) {
  20382. subMesh.updateBoundingInfo(matrix);
  20383. }
  20384. }
  20385. return this;
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20389. // Bounding info
  20390. this._updateBoundingInfo();
  20391. };
  20392. /**
  20393. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20394. * A mesh is in the frustum if its bounding box intersects the frustum
  20395. * @param frustumPlanes defines the frustum to test
  20396. * @returns true if the mesh is in the frustum planes
  20397. */
  20398. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20399. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20400. };
  20401. /**
  20402. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20403. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20404. * @param frustumPlanes defines the frustum to test
  20405. * @returns true if the mesh is completely in the frustum planes
  20406. */
  20407. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20408. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20409. };
  20410. /**
  20411. * True if the mesh intersects another mesh or a SolidParticle object
  20412. * @param mesh defines a target mesh or SolidParticle to test
  20413. * @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)
  20414. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20415. * @returns true if there is an intersection
  20416. */
  20417. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20418. if (precise === void 0) { precise = false; }
  20419. if (!this._boundingInfo || !mesh._boundingInfo) {
  20420. return false;
  20421. }
  20422. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20423. return true;
  20424. }
  20425. if (includeDescendants) {
  20426. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20427. var child = _a[_i];
  20428. if (child.intersectsMesh(mesh, precise, true)) {
  20429. return true;
  20430. }
  20431. }
  20432. }
  20433. return false;
  20434. };
  20435. /**
  20436. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20437. * @param point defines the point to test
  20438. * @returns true if there is an intersection
  20439. */
  20440. AbstractMesh.prototype.intersectsPoint = function (point) {
  20441. if (!this._boundingInfo) {
  20442. return false;
  20443. }
  20444. return this._boundingInfo.intersectsPoint(point);
  20445. };
  20446. /**
  20447. * Gets the current physics impostor
  20448. * @see http://doc.babylonjs.com/features/physics_engine
  20449. * @returns a physics impostor or null
  20450. */
  20451. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20452. return this.physicsImpostor;
  20453. };
  20454. /**
  20455. * Gets the position of the current mesh in camera space
  20456. * @param camera defines the camera to use
  20457. * @returns a position
  20458. */
  20459. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20460. if (camera === void 0) { camera = null; }
  20461. if (!camera) {
  20462. camera = this.getScene().activeCamera;
  20463. }
  20464. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20465. };
  20466. /**
  20467. * Returns the distance from the mesh to the active camera
  20468. * @param camera defines the camera to use
  20469. * @returns the distance
  20470. */
  20471. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20472. if (camera === void 0) { camera = null; }
  20473. if (!camera) {
  20474. camera = this.getScene().activeCamera;
  20475. }
  20476. return this.absolutePosition.subtract(camera.position).length();
  20477. };
  20478. /**
  20479. * Apply a physic impulse to the mesh
  20480. * @param force defines the force to apply
  20481. * @param contactPoint defines where to apply the force
  20482. * @returns the current mesh
  20483. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20484. */
  20485. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20486. if (!this.physicsImpostor) {
  20487. return this;
  20488. }
  20489. this.physicsImpostor.applyImpulse(force, contactPoint);
  20490. return this;
  20491. };
  20492. /**
  20493. * Creates a physic joint between two meshes
  20494. * @param otherMesh defines the other mesh to use
  20495. * @param pivot1 defines the pivot to use on this mesh
  20496. * @param pivot2 defines the pivot to use on the other mesh
  20497. * @param options defines additional options (can be plugin dependent)
  20498. * @returns the current mesh
  20499. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20500. */
  20501. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20502. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20503. return this;
  20504. }
  20505. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20506. mainPivot: pivot1,
  20507. connectedPivot: pivot2,
  20508. nativeParams: options
  20509. });
  20510. return this;
  20511. };
  20512. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20513. // Collisions
  20514. /**
  20515. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20516. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20517. */
  20518. get: function () {
  20519. return this._checkCollisions;
  20520. },
  20521. set: function (collisionEnabled) {
  20522. this._checkCollisions = collisionEnabled;
  20523. if (this.getScene().workerCollisions) {
  20524. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20525. }
  20526. },
  20527. enumerable: true,
  20528. configurable: true
  20529. });
  20530. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20531. /**
  20532. * Gets Collider object used to compute collisions (not physics)
  20533. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20534. */
  20535. get: function () {
  20536. return this._collider;
  20537. },
  20538. enumerable: true,
  20539. configurable: true
  20540. });
  20541. /**
  20542. * Move the mesh using collision engine
  20543. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20544. * @param displacement defines the requested displacement vector
  20545. * @returns the current mesh
  20546. */
  20547. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20548. var globalPosition = this.getAbsolutePosition();
  20549. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20550. if (!this._collider) {
  20551. this._collider = new BABYLON.Collider();
  20552. }
  20553. this._collider._radius = this.ellipsoid;
  20554. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20555. return this;
  20556. };
  20557. // Submeshes octree
  20558. /**
  20559. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20560. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20561. * @param maxCapacity defines the maximum size of each block (64 by default)
  20562. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20563. * @returns the new octree
  20564. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20565. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20566. */
  20567. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20568. if (maxCapacity === void 0) { maxCapacity = 64; }
  20569. if (maxDepth === void 0) { maxDepth = 2; }
  20570. if (!this._submeshesOctree) {
  20571. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20572. }
  20573. this.computeWorldMatrix(true);
  20574. var boundingInfo = this.getBoundingInfo();
  20575. // Update octree
  20576. var bbox = boundingInfo.boundingBox;
  20577. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20578. return this._submeshesOctree;
  20579. };
  20580. // Collisions
  20581. /** @hidden */
  20582. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20583. this._generatePointsArray();
  20584. if (!this._positions) {
  20585. return this;
  20586. }
  20587. // Transformation
  20588. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20589. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20590. subMesh._lastColliderWorldVertices = [];
  20591. subMesh._trianglePlanes = [];
  20592. var start = subMesh.verticesStart;
  20593. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20594. for (var i = start; i < end; i++) {
  20595. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20596. }
  20597. }
  20598. // Collide
  20599. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20600. if (collider.collisionFound) {
  20601. collider.collidedMesh = this;
  20602. }
  20603. return this;
  20604. };
  20605. /** @hidden */
  20606. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20607. var subMeshes;
  20608. var len;
  20609. // Octrees
  20610. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20611. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20612. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20613. len = intersections.length;
  20614. subMeshes = intersections.data;
  20615. }
  20616. else {
  20617. subMeshes = this.subMeshes;
  20618. len = subMeshes.length;
  20619. }
  20620. for (var index = 0; index < len; index++) {
  20621. var subMesh = subMeshes[index];
  20622. // Bounding test
  20623. if (len > 1 && !subMesh._checkCollision(collider))
  20624. continue;
  20625. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20626. }
  20627. return this;
  20628. };
  20629. /** @hidden */
  20630. AbstractMesh.prototype._checkCollision = function (collider) {
  20631. // Bounding box test
  20632. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20633. return this;
  20634. // Transformation matrix
  20635. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20636. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20637. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20638. return this;
  20639. };
  20640. // Picking
  20641. /** @hidden */
  20642. AbstractMesh.prototype._generatePointsArray = function () {
  20643. return false;
  20644. };
  20645. /**
  20646. * Checks if the passed Ray intersects with the mesh
  20647. * @param ray defines the ray to use
  20648. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20649. * @returns the picking info
  20650. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20651. */
  20652. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20653. var pickingInfo = new BABYLON.PickingInfo();
  20654. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20655. return pickingInfo;
  20656. }
  20657. if (!this._generatePointsArray()) {
  20658. return pickingInfo;
  20659. }
  20660. var intersectInfo = null;
  20661. // Octrees
  20662. var subMeshes;
  20663. var len;
  20664. if (this._submeshesOctree && this.useOctreeForPicking) {
  20665. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20666. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20667. len = intersections.length;
  20668. subMeshes = intersections.data;
  20669. }
  20670. else {
  20671. subMeshes = this.subMeshes;
  20672. len = subMeshes.length;
  20673. }
  20674. for (var index = 0; index < len; index++) {
  20675. var subMesh = subMeshes[index];
  20676. // Bounding test
  20677. if (len > 1 && !subMesh.canIntersects(ray))
  20678. continue;
  20679. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20680. if (currentIntersectInfo) {
  20681. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20682. intersectInfo = currentIntersectInfo;
  20683. intersectInfo.subMeshId = index;
  20684. if (fastCheck) {
  20685. break;
  20686. }
  20687. }
  20688. }
  20689. }
  20690. if (intersectInfo) {
  20691. // Get picked point
  20692. var world = this.getWorldMatrix();
  20693. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20694. var direction = ray.direction.clone();
  20695. direction = direction.scale(intersectInfo.distance);
  20696. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20697. var pickedPoint = worldOrigin.add(worldDirection);
  20698. // Return result
  20699. pickingInfo.hit = true;
  20700. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20701. pickingInfo.pickedPoint = pickedPoint;
  20702. pickingInfo.pickedMesh = this;
  20703. pickingInfo.bu = intersectInfo.bu || 0;
  20704. pickingInfo.bv = intersectInfo.bv || 0;
  20705. pickingInfo.faceId = intersectInfo.faceId;
  20706. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20707. return pickingInfo;
  20708. }
  20709. return pickingInfo;
  20710. };
  20711. /**
  20712. * Clones the current mesh
  20713. * @param name defines the mesh name
  20714. * @param newParent defines the new mesh parent
  20715. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20716. * @returns the new mesh
  20717. */
  20718. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20719. return null;
  20720. };
  20721. /**
  20722. * Disposes all the submeshes of the current meshnp
  20723. * @returns the current mesh
  20724. */
  20725. AbstractMesh.prototype.releaseSubMeshes = function () {
  20726. if (this.subMeshes) {
  20727. while (this.subMeshes.length) {
  20728. this.subMeshes[0].dispose();
  20729. }
  20730. }
  20731. else {
  20732. this.subMeshes = new Array();
  20733. }
  20734. return this;
  20735. };
  20736. /**
  20737. * Releases resources associated with this abstract mesh.
  20738. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20739. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20740. */
  20741. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20742. var _this = this;
  20743. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20744. var index;
  20745. // Smart Array Retainers.
  20746. this.getScene().freeActiveMeshes();
  20747. this.getScene().freeRenderingGroups();
  20748. // Action manager
  20749. if (this.actionManager !== undefined && this.actionManager !== null) {
  20750. this.actionManager.dispose();
  20751. this.actionManager = null;
  20752. }
  20753. // Skeleton
  20754. this._skeleton = null;
  20755. // Physics
  20756. if (this.physicsImpostor) {
  20757. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20758. }
  20759. // Intersections in progress
  20760. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20761. var other = this._intersectionsInProgress[index];
  20762. var pos = other._intersectionsInProgress.indexOf(this);
  20763. other._intersectionsInProgress.splice(pos, 1);
  20764. }
  20765. this._intersectionsInProgress = [];
  20766. // Lights
  20767. var lights = this.getScene().lights;
  20768. lights.forEach(function (light) {
  20769. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20770. if (meshIndex !== -1) {
  20771. light.includedOnlyMeshes.splice(meshIndex, 1);
  20772. }
  20773. meshIndex = light.excludedMeshes.indexOf(_this);
  20774. if (meshIndex !== -1) {
  20775. light.excludedMeshes.splice(meshIndex, 1);
  20776. }
  20777. // Shadow generators
  20778. var generator = light.getShadowGenerator();
  20779. if (generator) {
  20780. var shadowMap = generator.getShadowMap();
  20781. if (shadowMap && shadowMap.renderList) {
  20782. meshIndex = shadowMap.renderList.indexOf(_this);
  20783. if (meshIndex !== -1) {
  20784. shadowMap.renderList.splice(meshIndex, 1);
  20785. }
  20786. }
  20787. }
  20788. });
  20789. // Edges
  20790. if (this._edgesRenderer) {
  20791. this._edgesRenderer.dispose();
  20792. this._edgesRenderer = null;
  20793. }
  20794. // SubMeshes
  20795. if (this.getClassName() !== "InstancedMesh") {
  20796. this.releaseSubMeshes();
  20797. }
  20798. // Octree
  20799. var sceneOctree = this.getScene().selectionOctree;
  20800. if (sceneOctree !== undefined && sceneOctree !== null) {
  20801. var index = sceneOctree.dynamicContent.indexOf(this);
  20802. if (index !== -1) {
  20803. sceneOctree.dynamicContent.splice(index, 1);
  20804. }
  20805. }
  20806. // Query
  20807. var engine = this.getScene().getEngine();
  20808. if (this._occlusionQuery) {
  20809. this._isOcclusionQueryInProgress = false;
  20810. engine.deleteQuery(this._occlusionQuery);
  20811. this._occlusionQuery = null;
  20812. }
  20813. // Engine
  20814. engine.wipeCaches();
  20815. // Remove from scene
  20816. this.getScene().removeMesh(this);
  20817. if (disposeMaterialAndTextures) {
  20818. if (this.material) {
  20819. this.material.dispose(false, true);
  20820. }
  20821. }
  20822. if (!doNotRecurse) {
  20823. // Particles
  20824. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20825. if (this.getScene().particleSystems[index].emitter === this) {
  20826. this.getScene().particleSystems[index].dispose();
  20827. index--;
  20828. }
  20829. }
  20830. }
  20831. // facet data
  20832. if (this._facetDataEnabled) {
  20833. this.disableFacetData();
  20834. }
  20835. this.onAfterWorldMatrixUpdateObservable.clear();
  20836. this.onCollideObservable.clear();
  20837. this.onCollisionPositionChangeObservable.clear();
  20838. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20839. };
  20840. /**
  20841. * Adds the passed mesh as a child to the current mesh
  20842. * @param mesh defines the child mesh
  20843. * @returns the current mesh
  20844. */
  20845. AbstractMesh.prototype.addChild = function (mesh) {
  20846. mesh.setParent(this);
  20847. return this;
  20848. };
  20849. /**
  20850. * Removes the passed mesh from the current mesh children list
  20851. * @param mesh defines the child mesh
  20852. * @returns the current mesh
  20853. */
  20854. AbstractMesh.prototype.removeChild = function (mesh) {
  20855. mesh.setParent(null);
  20856. return this;
  20857. };
  20858. // Facet data
  20859. /** @hidden */
  20860. AbstractMesh.prototype._initFacetData = function () {
  20861. if (!this._facetNormals) {
  20862. this._facetNormals = new Array();
  20863. }
  20864. if (!this._facetPositions) {
  20865. this._facetPositions = new Array();
  20866. }
  20867. if (!this._facetPartitioning) {
  20868. this._facetPartitioning = new Array();
  20869. }
  20870. this._facetNb = (this.getIndices().length / 3) | 0;
  20871. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20872. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20873. for (var f = 0; f < this._facetNb; f++) {
  20874. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20875. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20876. }
  20877. this._facetDataEnabled = true;
  20878. return this;
  20879. };
  20880. /**
  20881. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20882. * This method can be called within the render loop.
  20883. * 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
  20884. * @returns the current mesh
  20885. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20886. */
  20887. AbstractMesh.prototype.updateFacetData = function () {
  20888. if (!this._facetDataEnabled) {
  20889. this._initFacetData();
  20890. }
  20891. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20892. var indices = this.getIndices();
  20893. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20894. var bInfo = this.getBoundingInfo();
  20895. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20896. // init arrays, matrix and sort function on first call
  20897. this._facetDepthSortEnabled = true;
  20898. if (indices instanceof Uint16Array) {
  20899. this._depthSortedIndices = new Uint16Array(indices);
  20900. }
  20901. else if (indices instanceof Uint32Array) {
  20902. this._depthSortedIndices = new Uint32Array(indices);
  20903. }
  20904. else {
  20905. var needs32bits = false;
  20906. for (var i = 0; i < indices.length; i++) {
  20907. if (indices[i] > 65535) {
  20908. needs32bits = true;
  20909. break;
  20910. }
  20911. }
  20912. if (needs32bits) {
  20913. this._depthSortedIndices = new Uint32Array(indices);
  20914. }
  20915. else {
  20916. this._depthSortedIndices = new Uint16Array(indices);
  20917. }
  20918. }
  20919. this._facetDepthSortFunction = function (f1, f2) {
  20920. return (f2.sqDistance - f1.sqDistance);
  20921. };
  20922. if (!this._facetDepthSortFrom) {
  20923. var camera = this.getScene().activeCamera;
  20924. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20925. }
  20926. this._depthSortedFacets = [];
  20927. for (var f = 0; f < this._facetNb; f++) {
  20928. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20929. this._depthSortedFacets.push(depthSortedFacet);
  20930. }
  20931. this._invertedMatrix = BABYLON.Matrix.Identity();
  20932. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20933. }
  20934. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20935. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20936. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20937. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20938. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20939. this._subDiv.max = this._partitioningSubdivisions;
  20940. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20941. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20942. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20943. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20944. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20945. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20946. // set the parameters for ComputeNormals()
  20947. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20948. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20949. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20950. this._facetParameters.bInfo = bInfo;
  20951. this._facetParameters.bbSize = this._bbSize;
  20952. this._facetParameters.subDiv = this._subDiv;
  20953. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20954. this._facetParameters.depthSort = this._facetDepthSort;
  20955. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20956. this.computeWorldMatrix(true);
  20957. this._worldMatrix.invertToRef(this._invertedMatrix);
  20958. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20959. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20960. }
  20961. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20962. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20963. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20964. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20965. var l = (this._depthSortedIndices.length / 3) | 0;
  20966. for (var f = 0; f < l; f++) {
  20967. var sind = this._depthSortedFacets[f].ind;
  20968. this._depthSortedIndices[f * 3] = indices[sind];
  20969. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20970. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20971. }
  20972. this.updateIndices(this._depthSortedIndices);
  20973. }
  20974. return this;
  20975. };
  20976. /**
  20977. * Returns the facetLocalNormals array.
  20978. * The normals are expressed in the mesh local spac
  20979. * @returns an array of Vector3
  20980. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20981. */
  20982. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20983. if (!this._facetNormals) {
  20984. this.updateFacetData();
  20985. }
  20986. return this._facetNormals;
  20987. };
  20988. /**
  20989. * Returns the facetLocalPositions array.
  20990. * The facet positions are expressed in the mesh local space
  20991. * @returns an array of Vector3
  20992. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20993. */
  20994. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20995. if (!this._facetPositions) {
  20996. this.updateFacetData();
  20997. }
  20998. return this._facetPositions;
  20999. };
  21000. /**
  21001. * Returns the facetLocalPartioning array
  21002. * @returns an array of array of numbers
  21003. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21004. */
  21005. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21006. if (!this._facetPartitioning) {
  21007. this.updateFacetData();
  21008. }
  21009. return this._facetPartitioning;
  21010. };
  21011. /**
  21012. * Returns the i-th facet position in the world system.
  21013. * This method allocates a new Vector3 per call
  21014. * @param i defines the facet index
  21015. * @returns a new Vector3
  21016. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21017. */
  21018. AbstractMesh.prototype.getFacetPosition = function (i) {
  21019. var pos = BABYLON.Vector3.Zero();
  21020. this.getFacetPositionToRef(i, pos);
  21021. return pos;
  21022. };
  21023. /**
  21024. * Sets the reference Vector3 with the i-th facet position in the world system
  21025. * @param i defines the facet index
  21026. * @param ref defines the target vector
  21027. * @returns the current mesh
  21028. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21029. */
  21030. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21031. var localPos = (this.getFacetLocalPositions())[i];
  21032. var world = this.getWorldMatrix();
  21033. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21034. return this;
  21035. };
  21036. /**
  21037. * Returns the i-th facet normal in the world system.
  21038. * This method allocates a new Vector3 per call
  21039. * @param i defines the facet index
  21040. * @returns a new Vector3
  21041. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21042. */
  21043. AbstractMesh.prototype.getFacetNormal = function (i) {
  21044. var norm = BABYLON.Vector3.Zero();
  21045. this.getFacetNormalToRef(i, norm);
  21046. return norm;
  21047. };
  21048. /**
  21049. * Sets the reference Vector3 with the i-th facet normal in the world system
  21050. * @param i defines the facet index
  21051. * @param ref defines the target vector
  21052. * @returns the current mesh
  21053. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21054. */
  21055. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21056. var localNorm = (this.getFacetLocalNormals())[i];
  21057. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21058. return this;
  21059. };
  21060. /**
  21061. * 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)
  21062. * @param x defines x coordinate
  21063. * @param y defines y coordinate
  21064. * @param z defines z coordinate
  21065. * @returns the array of facet indexes
  21066. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21067. */
  21068. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21069. var bInfo = this.getBoundingInfo();
  21070. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21071. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21072. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21073. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21074. return null;
  21075. }
  21076. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21077. };
  21078. /**
  21079. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21080. * @param projected sets as the (x,y,z) world projection on the facet
  21081. * @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
  21082. * @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
  21083. * @param x defines x coordinate
  21084. * @param y defines y coordinate
  21085. * @param z defines z coordinate
  21086. * @returns the face index if found (or null instead)
  21087. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21088. */
  21089. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21090. if (checkFace === void 0) { checkFace = false; }
  21091. if (facing === void 0) { facing = true; }
  21092. var world = this.getWorldMatrix();
  21093. var invMat = BABYLON.Tmp.Matrix[5];
  21094. world.invertToRef(invMat);
  21095. var invVect = BABYLON.Tmp.Vector3[8];
  21096. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21097. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21098. if (projected) {
  21099. // tranform the local computed projected vector to world coordinates
  21100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21101. }
  21102. return closest;
  21103. };
  21104. /**
  21105. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21106. * @param projected sets as the (x,y,z) local projection on the facet
  21107. * @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
  21108. * @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
  21109. * @param x defines x coordinate
  21110. * @param y defines y coordinate
  21111. * @param z defines z coordinate
  21112. * @returns the face index if found (or null instead)
  21113. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21114. */
  21115. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21116. if (checkFace === void 0) { checkFace = false; }
  21117. if (facing === void 0) { facing = true; }
  21118. var closest = null;
  21119. var tmpx = 0.0;
  21120. var tmpy = 0.0;
  21121. var tmpz = 0.0;
  21122. var d = 0.0; // tmp dot facet normal * facet position
  21123. var t0 = 0.0;
  21124. var projx = 0.0;
  21125. var projy = 0.0;
  21126. var projz = 0.0;
  21127. // Get all the facets in the same partitioning block than (x, y, z)
  21128. var facetPositions = this.getFacetLocalPositions();
  21129. var facetNormals = this.getFacetLocalNormals();
  21130. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21131. if (!facetsInBlock) {
  21132. return null;
  21133. }
  21134. // Get the closest facet to (x, y, z)
  21135. var shortest = Number.MAX_VALUE; // init distance vars
  21136. var tmpDistance = shortest;
  21137. var fib; // current facet in the block
  21138. var norm; // current facet normal
  21139. var p0; // current facet barycenter position
  21140. // loop on all the facets in the current partitioning block
  21141. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21142. fib = facetsInBlock[idx];
  21143. norm = facetNormals[fib];
  21144. p0 = facetPositions[fib];
  21145. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21146. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21147. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21148. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21149. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21150. projx = x + norm.x * t0;
  21151. projy = y + norm.y * t0;
  21152. projz = z + norm.z * t0;
  21153. tmpx = projx - x;
  21154. tmpy = projy - y;
  21155. tmpz = projz - z;
  21156. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21157. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21158. shortest = tmpDistance;
  21159. closest = fib;
  21160. if (projected) {
  21161. projected.x = projx;
  21162. projected.y = projy;
  21163. projected.z = projz;
  21164. }
  21165. }
  21166. }
  21167. }
  21168. return closest;
  21169. };
  21170. /**
  21171. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21172. * @returns the parameters
  21173. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21174. */
  21175. AbstractMesh.prototype.getFacetDataParameters = function () {
  21176. return this._facetParameters;
  21177. };
  21178. /**
  21179. * Disables the feature FacetData and frees the related memory
  21180. * @returns the current mesh
  21181. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21182. */
  21183. AbstractMesh.prototype.disableFacetData = function () {
  21184. if (this._facetDataEnabled) {
  21185. this._facetDataEnabled = false;
  21186. this._facetPositions = new Array();
  21187. this._facetNormals = new Array();
  21188. this._facetPartitioning = new Array();
  21189. this._facetParameters = null;
  21190. this._depthSortedIndices = new Uint32Array(0);
  21191. }
  21192. return this;
  21193. };
  21194. /**
  21195. * Updates the AbstractMesh indices array
  21196. * @param indices defines the data source
  21197. * @returns the current mesh
  21198. */
  21199. AbstractMesh.prototype.updateIndices = function (indices) {
  21200. return this;
  21201. };
  21202. /**
  21203. * Creates new normals data for the mesh
  21204. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21205. * @returns the current mesh
  21206. */
  21207. AbstractMesh.prototype.createNormals = function (updatable) {
  21208. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21209. var indices = this.getIndices();
  21210. var normals;
  21211. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21212. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21213. }
  21214. else {
  21215. normals = [];
  21216. }
  21217. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21218. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21219. return this;
  21220. };
  21221. /**
  21222. * Align the mesh with a normal
  21223. * @param normal defines the normal to use
  21224. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21225. * @returns the current mesh
  21226. */
  21227. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21228. if (!upDirection) {
  21229. upDirection = BABYLON.Axis.Y;
  21230. }
  21231. var axisX = BABYLON.Tmp.Vector3[0];
  21232. var axisZ = BABYLON.Tmp.Vector3[1];
  21233. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21234. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21235. if (this.rotationQuaternion) {
  21236. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21237. }
  21238. else {
  21239. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21240. }
  21241. return this;
  21242. };
  21243. /** @hidden */
  21244. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21245. this._isOccluded = false;
  21246. };
  21247. /** No occlusion */
  21248. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21249. /** Occlusion set to optimisitic */
  21250. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21251. /** Occlusion set to strict */
  21252. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21253. /** Use an accurante occlusion algorithm */
  21254. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21255. /** Use a conservative occlusion algorithm */
  21256. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21257. return AbstractMesh;
  21258. }(BABYLON.TransformNode));
  21259. BABYLON.AbstractMesh = AbstractMesh;
  21260. })(BABYLON || (BABYLON = {}));
  21261. //# sourceMappingURL=babylon.abstractMesh.js.map
  21262. var BABYLON;
  21263. (function (BABYLON) {
  21264. /**
  21265. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21266. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21267. * 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.
  21268. */
  21269. var Light = /** @class */ (function (_super) {
  21270. __extends(Light, _super);
  21271. /**
  21272. * Creates a Light object in the scene.
  21273. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21274. * @param name The firendly name of the light
  21275. * @param scene The scene the light belongs too
  21276. */
  21277. function Light(name, scene) {
  21278. var _this = _super.call(this, name, scene) || this;
  21279. /**
  21280. * Diffuse gives the basic color to an object.
  21281. */
  21282. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21283. /**
  21284. * Specular produces a highlight color on an object.
  21285. * Note: This is note affecting PBR materials.
  21286. */
  21287. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21288. /**
  21289. * Strength of the light.
  21290. * Note: By default it is define in the framework own unit.
  21291. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21292. */
  21293. _this.intensity = 1.0;
  21294. /**
  21295. * Defines how far from the source the light is impacting in scene units.
  21296. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21297. */
  21298. _this.range = Number.MAX_VALUE;
  21299. /**
  21300. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21301. * of light.
  21302. */
  21303. _this._photometricScale = 1.0;
  21304. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21305. _this._radius = 0.00001;
  21306. /**
  21307. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21308. * exceeding the number allowed of the materials.
  21309. */
  21310. _this.renderPriority = 0;
  21311. _this._shadowEnabled = true;
  21312. _this._excludeWithLayerMask = 0;
  21313. _this._includeOnlyWithLayerMask = 0;
  21314. _this._lightmapMode = 0;
  21315. /**
  21316. * @hidden Internal use only.
  21317. */
  21318. _this._excludedMeshesIds = new Array();
  21319. /**
  21320. * @hidden Internal use only.
  21321. */
  21322. _this._includedOnlyMeshesIds = new Array();
  21323. _this.getScene().addLight(_this);
  21324. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21325. _this._buildUniformLayout();
  21326. _this.includedOnlyMeshes = new Array();
  21327. _this.excludedMeshes = new Array();
  21328. _this._resyncMeshes();
  21329. return _this;
  21330. }
  21331. Object.defineProperty(Light.prototype, "intensityMode", {
  21332. /**
  21333. * Gets the photometric scale used to interpret the intensity.
  21334. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21335. */
  21336. get: function () {
  21337. return this._intensityMode;
  21338. },
  21339. /**
  21340. * Sets the photometric scale used to interpret the intensity.
  21341. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21342. */
  21343. set: function (value) {
  21344. this._intensityMode = value;
  21345. this._computePhotometricScale();
  21346. },
  21347. enumerable: true,
  21348. configurable: true
  21349. });
  21350. ;
  21351. ;
  21352. Object.defineProperty(Light.prototype, "radius", {
  21353. /**
  21354. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21355. */
  21356. get: function () {
  21357. return this._radius;
  21358. },
  21359. /**
  21360. * sets the light radius used by PBR Materials to simulate soft area lights.
  21361. */
  21362. set: function (value) {
  21363. this._radius = value;
  21364. this._computePhotometricScale();
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. ;
  21370. ;
  21371. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21372. /**
  21373. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21374. * the current shadow generator.
  21375. */
  21376. get: function () {
  21377. return this._shadowEnabled;
  21378. },
  21379. /**
  21380. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21381. * the current shadow generator.
  21382. */
  21383. set: function (value) {
  21384. if (this._shadowEnabled === value) {
  21385. return;
  21386. }
  21387. this._shadowEnabled = value;
  21388. this._markMeshesAsLightDirty();
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21394. /**
  21395. * Gets the only meshes impacted by this light.
  21396. */
  21397. get: function () {
  21398. return this._includedOnlyMeshes;
  21399. },
  21400. /**
  21401. * Sets the only meshes impacted by this light.
  21402. */
  21403. set: function (value) {
  21404. this._includedOnlyMeshes = value;
  21405. this._hookArrayForIncludedOnly(value);
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21411. /**
  21412. * Gets the meshes not impacted by this light.
  21413. */
  21414. get: function () {
  21415. return this._excludedMeshes;
  21416. },
  21417. /**
  21418. * Sets the meshes not impacted by this light.
  21419. */
  21420. set: function (value) {
  21421. this._excludedMeshes = value;
  21422. this._hookArrayForExcluded(value);
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21428. /**
  21429. * Gets the layer id use to find what meshes are not impacted by the light.
  21430. * Inactive if 0
  21431. */
  21432. get: function () {
  21433. return this._excludeWithLayerMask;
  21434. },
  21435. /**
  21436. * Sets the layer id use to find what meshes are not impacted by the light.
  21437. * Inactive if 0
  21438. */
  21439. set: function (value) {
  21440. this._excludeWithLayerMask = value;
  21441. this._resyncMeshes();
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21447. /**
  21448. * Gets the layer id use to find what meshes are impacted by the light.
  21449. * Inactive if 0
  21450. */
  21451. get: function () {
  21452. return this._includeOnlyWithLayerMask;
  21453. },
  21454. /**
  21455. * Sets the layer id use to find what meshes are impacted by the light.
  21456. * Inactive if 0
  21457. */
  21458. set: function (value) {
  21459. this._includeOnlyWithLayerMask = value;
  21460. this._resyncMeshes();
  21461. },
  21462. enumerable: true,
  21463. configurable: true
  21464. });
  21465. Object.defineProperty(Light.prototype, "lightmapMode", {
  21466. /**
  21467. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21468. */
  21469. get: function () {
  21470. return this._lightmapMode;
  21471. },
  21472. /**
  21473. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21474. */
  21475. set: function (value) {
  21476. if (this._lightmapMode === value) {
  21477. return;
  21478. }
  21479. this._lightmapMode = value;
  21480. this._markMeshesAsLightDirty();
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. /**
  21486. * Returns the string "Light".
  21487. * @returns the class name
  21488. */
  21489. Light.prototype.getClassName = function () {
  21490. return "Light";
  21491. };
  21492. /**
  21493. * Converts the light information to a readable string for debug purpose.
  21494. * @param fullDetails Supports for multiple levels of logging within scene loading
  21495. * @returns the human readable light info
  21496. */
  21497. Light.prototype.toString = function (fullDetails) {
  21498. var ret = "Name: " + this.name;
  21499. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21500. if (this.animations) {
  21501. for (var i = 0; i < this.animations.length; i++) {
  21502. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21503. }
  21504. }
  21505. if (fullDetails) {
  21506. }
  21507. return ret;
  21508. };
  21509. /**
  21510. * Set the enabled state of this node.
  21511. * @param value - the new enabled state
  21512. */
  21513. Light.prototype.setEnabled = function (value) {
  21514. _super.prototype.setEnabled.call(this, value);
  21515. this._resyncMeshes();
  21516. };
  21517. /**
  21518. * Returns the Light associated shadow generator if any.
  21519. * @return the associated shadow generator.
  21520. */
  21521. Light.prototype.getShadowGenerator = function () {
  21522. return this._shadowGenerator;
  21523. };
  21524. /**
  21525. * Returns a Vector3, the absolute light position in the World.
  21526. * @returns the world space position of the light
  21527. */
  21528. Light.prototype.getAbsolutePosition = function () {
  21529. return BABYLON.Vector3.Zero();
  21530. };
  21531. /**
  21532. * Specifies if the light will affect the passed mesh.
  21533. * @param mesh The mesh to test against the light
  21534. * @return true the mesh is affected otherwise, false.
  21535. */
  21536. Light.prototype.canAffectMesh = function (mesh) {
  21537. if (!mesh) {
  21538. return true;
  21539. }
  21540. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21541. return false;
  21542. }
  21543. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21544. return false;
  21545. }
  21546. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21547. return false;
  21548. }
  21549. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21550. return false;
  21551. }
  21552. return true;
  21553. };
  21554. /**
  21555. * Computes and Returns the light World matrix.
  21556. * @returns the world matrix
  21557. */
  21558. Light.prototype.getWorldMatrix = function () {
  21559. this._currentRenderId = this.getScene().getRenderId();
  21560. this._childRenderId = this._currentRenderId;
  21561. var worldMatrix = this._getWorldMatrix();
  21562. if (this.parent && this.parent.getWorldMatrix) {
  21563. if (!this._parentedWorldMatrix) {
  21564. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21565. }
  21566. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21567. this._markSyncedWithParent();
  21568. return this._parentedWorldMatrix;
  21569. }
  21570. return worldMatrix;
  21571. };
  21572. /**
  21573. * Sort function to order lights for rendering.
  21574. * @param a First Light object to compare to second.
  21575. * @param b Second Light object to compare first.
  21576. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21577. */
  21578. Light.CompareLightsPriority = function (a, b) {
  21579. //shadow-casting lights have priority over non-shadow-casting lights
  21580. //the renderPrioirty is a secondary sort criterion
  21581. if (a.shadowEnabled !== b.shadowEnabled) {
  21582. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21583. }
  21584. return b.renderPriority - a.renderPriority;
  21585. };
  21586. /**
  21587. * Releases resources associated with this node.
  21588. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21589. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21590. */
  21591. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21592. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21593. if (this._shadowGenerator) {
  21594. this._shadowGenerator.dispose();
  21595. this._shadowGenerator = null;
  21596. }
  21597. // Animations
  21598. this.getScene().stopAnimation(this);
  21599. // Remove from meshes
  21600. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21601. var mesh = _a[_i];
  21602. mesh._removeLightSource(this);
  21603. }
  21604. this._uniformBuffer.dispose();
  21605. // Remove from scene
  21606. this.getScene().removeLight(this);
  21607. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21608. };
  21609. /**
  21610. * Returns the light type ID (integer).
  21611. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21612. */
  21613. Light.prototype.getTypeID = function () {
  21614. return 0;
  21615. };
  21616. /**
  21617. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21618. * @returns the scaled intensity in intensity mode unit
  21619. */
  21620. Light.prototype.getScaledIntensity = function () {
  21621. return this._photometricScale * this.intensity;
  21622. };
  21623. /**
  21624. * Returns a new Light object, named "name", from the current one.
  21625. * @param name The name of the cloned light
  21626. * @returns the new created light
  21627. */
  21628. Light.prototype.clone = function (name) {
  21629. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21630. if (!constructor) {
  21631. return null;
  21632. }
  21633. return BABYLON.SerializationHelper.Clone(constructor, this);
  21634. };
  21635. /**
  21636. * Serializes the current light into a Serialization object.
  21637. * @returns the serialized object.
  21638. */
  21639. Light.prototype.serialize = function () {
  21640. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21641. // Type
  21642. serializationObject.type = this.getTypeID();
  21643. // Parent
  21644. if (this.parent) {
  21645. serializationObject.parentId = this.parent.id;
  21646. }
  21647. // Inclusion / exclusions
  21648. if (this.excludedMeshes.length > 0) {
  21649. serializationObject.excludedMeshesIds = [];
  21650. this.excludedMeshes.forEach(function (mesh) {
  21651. serializationObject.excludedMeshesIds.push(mesh.id);
  21652. });
  21653. }
  21654. if (this.includedOnlyMeshes.length > 0) {
  21655. serializationObject.includedOnlyMeshesIds = [];
  21656. this.includedOnlyMeshes.forEach(function (mesh) {
  21657. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21658. });
  21659. }
  21660. // Animations
  21661. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21662. serializationObject.ranges = this.serializeAnimationRanges();
  21663. return serializationObject;
  21664. };
  21665. /**
  21666. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21667. * This new light is named "name" and added to the passed scene.
  21668. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21669. * @param name The friendly name of the light
  21670. * @param scene The scene the new light will belong to
  21671. * @returns the constructor function
  21672. */
  21673. Light.GetConstructorFromName = function (type, name, scene) {
  21674. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21675. if (constructorFunc) {
  21676. return constructorFunc;
  21677. }
  21678. // Default to no light for none present once.
  21679. return null;
  21680. };
  21681. /**
  21682. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21683. * @param parsedLight The JSON representation of the light
  21684. * @param scene The scene to create the parsed light in
  21685. * @returns the created light after parsing
  21686. */
  21687. Light.Parse = function (parsedLight, scene) {
  21688. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21689. if (!constructor) {
  21690. return null;
  21691. }
  21692. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21693. // Inclusion / exclusions
  21694. if (parsedLight.excludedMeshesIds) {
  21695. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21696. }
  21697. if (parsedLight.includedOnlyMeshesIds) {
  21698. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21699. }
  21700. // Parent
  21701. if (parsedLight.parentId) {
  21702. light._waitingParentId = parsedLight.parentId;
  21703. }
  21704. // Animations
  21705. if (parsedLight.animations) {
  21706. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21707. var parsedAnimation = parsedLight.animations[animationIndex];
  21708. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21709. }
  21710. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21711. }
  21712. if (parsedLight.autoAnimate) {
  21713. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21714. }
  21715. return light;
  21716. };
  21717. Light.prototype._hookArrayForExcluded = function (array) {
  21718. var _this = this;
  21719. var oldPush = array.push;
  21720. array.push = function () {
  21721. var items = [];
  21722. for (var _i = 0; _i < arguments.length; _i++) {
  21723. items[_i] = arguments[_i];
  21724. }
  21725. var result = oldPush.apply(array, items);
  21726. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21727. var item = items_1[_a];
  21728. item._resyncLighSource(_this);
  21729. }
  21730. return result;
  21731. };
  21732. var oldSplice = array.splice;
  21733. array.splice = function (index, deleteCount) {
  21734. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21735. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21736. var item = deleted_1[_i];
  21737. item._resyncLighSource(_this);
  21738. }
  21739. return deleted;
  21740. };
  21741. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21742. var item = array_1[_i];
  21743. item._resyncLighSource(this);
  21744. }
  21745. };
  21746. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21747. var _this = this;
  21748. var oldPush = array.push;
  21749. array.push = function () {
  21750. var items = [];
  21751. for (var _i = 0; _i < arguments.length; _i++) {
  21752. items[_i] = arguments[_i];
  21753. }
  21754. var result = oldPush.apply(array, items);
  21755. _this._resyncMeshes();
  21756. return result;
  21757. };
  21758. var oldSplice = array.splice;
  21759. array.splice = function (index, deleteCount) {
  21760. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21761. _this._resyncMeshes();
  21762. return deleted;
  21763. };
  21764. this._resyncMeshes();
  21765. };
  21766. Light.prototype._resyncMeshes = function () {
  21767. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21768. var mesh = _a[_i];
  21769. mesh._resyncLighSource(this);
  21770. }
  21771. };
  21772. /**
  21773. * Forces the meshes to update their light related information in their rendering used effects
  21774. * @hidden Internal Use Only
  21775. */
  21776. Light.prototype._markMeshesAsLightDirty = function () {
  21777. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21778. var mesh = _a[_i];
  21779. if (mesh._lightSources.indexOf(this) !== -1) {
  21780. mesh._markSubMeshesAsLightDirty();
  21781. }
  21782. }
  21783. };
  21784. /**
  21785. * Recomputes the cached photometric scale if needed.
  21786. */
  21787. Light.prototype._computePhotometricScale = function () {
  21788. this._photometricScale = this._getPhotometricScale();
  21789. this.getScene().resetCachedMaterial();
  21790. };
  21791. /**
  21792. * Returns the Photometric Scale according to the light type and intensity mode.
  21793. */
  21794. Light.prototype._getPhotometricScale = function () {
  21795. var photometricScale = 0.0;
  21796. var lightTypeID = this.getTypeID();
  21797. //get photometric mode
  21798. var photometricMode = this.intensityMode;
  21799. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21800. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21801. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21802. }
  21803. else {
  21804. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21805. }
  21806. }
  21807. //compute photometric scale
  21808. switch (lightTypeID) {
  21809. case Light.LIGHTTYPEID_POINTLIGHT:
  21810. case Light.LIGHTTYPEID_SPOTLIGHT:
  21811. switch (photometricMode) {
  21812. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21813. photometricScale = 1.0 / (4.0 * Math.PI);
  21814. break;
  21815. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21816. photometricScale = 1.0;
  21817. break;
  21818. case Light.INTENSITYMODE_LUMINANCE:
  21819. photometricScale = this.radius * this.radius;
  21820. break;
  21821. }
  21822. break;
  21823. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21824. switch (photometricMode) {
  21825. case Light.INTENSITYMODE_ILLUMINANCE:
  21826. photometricScale = 1.0;
  21827. break;
  21828. case Light.INTENSITYMODE_LUMINANCE:
  21829. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21830. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21831. var apexAngleRadians = this.radius;
  21832. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21833. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21834. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21835. photometricScale = solidAngle;
  21836. break;
  21837. }
  21838. break;
  21839. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21840. // No fall off in hemisperic light.
  21841. photometricScale = 1.0;
  21842. break;
  21843. }
  21844. return photometricScale;
  21845. };
  21846. /**
  21847. * Reorder the light in the scene according to their defined priority.
  21848. * @hidden Internal Use Only
  21849. */
  21850. Light.prototype._reorderLightsInScene = function () {
  21851. var scene = this.getScene();
  21852. if (this._renderPriority != 0) {
  21853. scene.requireLightSorting = true;
  21854. }
  21855. this.getScene().sortLightsByPriority();
  21856. };
  21857. //lightmapMode Consts
  21858. /**
  21859. * If every light affecting the material is in this lightmapMode,
  21860. * material.lightmapTexture adds or multiplies
  21861. * (depends on material.useLightmapAsShadowmap)
  21862. * after every other light calculations.
  21863. */
  21864. Light.LIGHTMAP_DEFAULT = 0;
  21865. /**
  21866. * material.lightmapTexture as only diffuse lighting from this light
  21867. * adds only specular lighting from this light
  21868. * adds dynamic shadows
  21869. */
  21870. Light.LIGHTMAP_SPECULAR = 1;
  21871. /**
  21872. * material.lightmapTexture as only lighting
  21873. * no light calculation from this light
  21874. * only adds dynamic shadows from this light
  21875. */
  21876. Light.LIGHTMAP_SHADOWSONLY = 2;
  21877. // Intensity Mode Consts
  21878. /**
  21879. * Each light type uses the default quantity according to its type:
  21880. * point/spot lights use luminous intensity
  21881. * directional lights use illuminance
  21882. */
  21883. Light.INTENSITYMODE_AUTOMATIC = 0;
  21884. /**
  21885. * lumen (lm)
  21886. */
  21887. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21888. /**
  21889. * candela (lm/sr)
  21890. */
  21891. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21892. /**
  21893. * lux (lm/m^2)
  21894. */
  21895. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21896. /**
  21897. * nit (cd/m^2)
  21898. */
  21899. Light.INTENSITYMODE_LUMINANCE = 4;
  21900. // Light types ids const.
  21901. /**
  21902. * Light type const id of the point light.
  21903. */
  21904. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21905. /**
  21906. * Light type const id of the directional light.
  21907. */
  21908. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21909. /**
  21910. * Light type const id of the spot light.
  21911. */
  21912. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21913. /**
  21914. * Light type const id of the hemispheric light.
  21915. */
  21916. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21917. __decorate([
  21918. BABYLON.serializeAsColor3()
  21919. ], Light.prototype, "diffuse", void 0);
  21920. __decorate([
  21921. BABYLON.serializeAsColor3()
  21922. ], Light.prototype, "specular", void 0);
  21923. __decorate([
  21924. BABYLON.serialize()
  21925. ], Light.prototype, "intensity", void 0);
  21926. __decorate([
  21927. BABYLON.serialize()
  21928. ], Light.prototype, "range", void 0);
  21929. __decorate([
  21930. BABYLON.serialize()
  21931. ], Light.prototype, "intensityMode", null);
  21932. __decorate([
  21933. BABYLON.serialize()
  21934. ], Light.prototype, "radius", null);
  21935. __decorate([
  21936. BABYLON.serialize()
  21937. ], Light.prototype, "_renderPriority", void 0);
  21938. __decorate([
  21939. BABYLON.expandToProperty("_reorderLightsInScene")
  21940. ], Light.prototype, "renderPriority", void 0);
  21941. __decorate([
  21942. BABYLON.serialize("shadowEnabled")
  21943. ], Light.prototype, "_shadowEnabled", void 0);
  21944. __decorate([
  21945. BABYLON.serialize("excludeWithLayerMask")
  21946. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21947. __decorate([
  21948. BABYLON.serialize("includeOnlyWithLayerMask")
  21949. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21950. __decorate([
  21951. BABYLON.serialize("lightmapMode")
  21952. ], Light.prototype, "_lightmapMode", void 0);
  21953. return Light;
  21954. }(BABYLON.Node));
  21955. BABYLON.Light = Light;
  21956. })(BABYLON || (BABYLON = {}));
  21957. //# sourceMappingURL=babylon.light.js.map
  21958. var BABYLON;
  21959. (function (BABYLON) {
  21960. var Camera = /** @class */ (function (_super) {
  21961. __extends(Camera, _super);
  21962. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21963. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21964. var _this = _super.call(this, name, scene) || this;
  21965. /**
  21966. * The vector the camera should consider as up.
  21967. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21968. */
  21969. _this.upVector = BABYLON.Vector3.Up();
  21970. _this.orthoLeft = null;
  21971. _this.orthoRight = null;
  21972. _this.orthoBottom = null;
  21973. _this.orthoTop = null;
  21974. /**
  21975. * FOV is set in Radians. (default is 0.8)
  21976. */
  21977. _this.fov = 0.8;
  21978. _this.minZ = 1;
  21979. _this.maxZ = 10000.0;
  21980. _this.inertia = 0.9;
  21981. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21982. _this.isIntermediate = false;
  21983. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21984. /**
  21985. * Restricts the camera to viewing objects with the same layerMask.
  21986. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21987. */
  21988. _this.layerMask = 0x0FFFFFFF;
  21989. /**
  21990. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21991. */
  21992. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21993. // Camera rig members
  21994. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21995. _this._rigCameras = new Array();
  21996. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21997. _this._skipRendering = false;
  21998. _this.customRenderTargets = new Array();
  21999. // Observables
  22000. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22001. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22002. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22003. _this.onRestoreStateObservable = new BABYLON.Observable();
  22004. // Cache
  22005. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22006. _this._projectionMatrix = new BABYLON.Matrix();
  22007. _this._doNotComputeProjectionMatrix = false;
  22008. _this._worldMatrix = BABYLON.Matrix.Identity();
  22009. _this._postProcesses = new Array();
  22010. _this._transformMatrix = BABYLON.Matrix.Zero();
  22011. _this._activeMeshes = new BABYLON.SmartArray(256);
  22012. _this._globalPosition = BABYLON.Vector3.Zero();
  22013. _this._refreshFrustumPlanes = true;
  22014. _this.getScene().addCamera(_this);
  22015. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22016. _this.getScene().activeCamera = _this;
  22017. }
  22018. _this.position = position;
  22019. return _this;
  22020. }
  22021. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22022. get: function () {
  22023. return Camera._PERSPECTIVE_CAMERA;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22029. get: function () {
  22030. return Camera._ORTHOGRAPHIC_CAMERA;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22036. /**
  22037. * This is the default FOV mode for perspective cameras.
  22038. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22039. *
  22040. */
  22041. get: function () {
  22042. return Camera._FOVMODE_VERTICAL_FIXED;
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22048. /**
  22049. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22050. *
  22051. */
  22052. get: function () {
  22053. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22059. get: function () {
  22060. return Camera._RIG_MODE_NONE;
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22066. get: function () {
  22067. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22073. get: function () {
  22074. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22080. get: function () {
  22081. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22087. get: function () {
  22088. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22089. },
  22090. enumerable: true,
  22091. configurable: true
  22092. });
  22093. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22094. get: function () {
  22095. return Camera._RIG_MODE_VR;
  22096. },
  22097. enumerable: true,
  22098. configurable: true
  22099. });
  22100. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22101. get: function () {
  22102. return Camera._RIG_MODE_WEBVR;
  22103. },
  22104. enumerable: true,
  22105. configurable: true
  22106. });
  22107. /**
  22108. * Store current camera state (fov, position, etc..)
  22109. */
  22110. Camera.prototype.storeState = function () {
  22111. this._stateStored = true;
  22112. this._storedFov = this.fov;
  22113. return this;
  22114. };
  22115. /**
  22116. * Restores the camera state values if it has been stored. You must call storeState() first
  22117. */
  22118. Camera.prototype._restoreStateValues = function () {
  22119. if (!this._stateStored) {
  22120. return false;
  22121. }
  22122. this.fov = this._storedFov;
  22123. return true;
  22124. };
  22125. /**
  22126. * Restored camera state. You must call storeState() first
  22127. */
  22128. Camera.prototype.restoreState = function () {
  22129. if (this._restoreStateValues()) {
  22130. this.onRestoreStateObservable.notifyObservers(this);
  22131. return true;
  22132. }
  22133. return false;
  22134. };
  22135. Camera.prototype.getClassName = function () {
  22136. return "Camera";
  22137. };
  22138. /**
  22139. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22140. */
  22141. Camera.prototype.toString = function (fullDetails) {
  22142. var ret = "Name: " + this.name;
  22143. ret += ", type: " + this.getClassName();
  22144. if (this.animations) {
  22145. for (var i = 0; i < this.animations.length; i++) {
  22146. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22147. }
  22148. }
  22149. if (fullDetails) {
  22150. }
  22151. return ret;
  22152. };
  22153. Object.defineProperty(Camera.prototype, "globalPosition", {
  22154. get: function () {
  22155. return this._globalPosition;
  22156. },
  22157. enumerable: true,
  22158. configurable: true
  22159. });
  22160. Camera.prototype.getActiveMeshes = function () {
  22161. return this._activeMeshes;
  22162. };
  22163. Camera.prototype.isActiveMesh = function (mesh) {
  22164. return (this._activeMeshes.indexOf(mesh) !== -1);
  22165. };
  22166. /**
  22167. * Is this camera ready to be used/rendered
  22168. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22169. * @return true if the camera is ready
  22170. */
  22171. Camera.prototype.isReady = function (completeCheck) {
  22172. if (completeCheck === void 0) { completeCheck = false; }
  22173. if (completeCheck) {
  22174. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22175. var pp = _a[_i];
  22176. if (pp && !pp.isReady()) {
  22177. return false;
  22178. }
  22179. }
  22180. }
  22181. return _super.prototype.isReady.call(this, completeCheck);
  22182. };
  22183. //Cache
  22184. Camera.prototype._initCache = function () {
  22185. _super.prototype._initCache.call(this);
  22186. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22187. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22188. this._cache.mode = undefined;
  22189. this._cache.minZ = undefined;
  22190. this._cache.maxZ = undefined;
  22191. this._cache.fov = undefined;
  22192. this._cache.fovMode = undefined;
  22193. this._cache.aspectRatio = undefined;
  22194. this._cache.orthoLeft = undefined;
  22195. this._cache.orthoRight = undefined;
  22196. this._cache.orthoBottom = undefined;
  22197. this._cache.orthoTop = undefined;
  22198. this._cache.renderWidth = undefined;
  22199. this._cache.renderHeight = undefined;
  22200. };
  22201. Camera.prototype._updateCache = function (ignoreParentClass) {
  22202. if (!ignoreParentClass) {
  22203. _super.prototype._updateCache.call(this);
  22204. }
  22205. this._cache.position.copyFrom(this.position);
  22206. this._cache.upVector.copyFrom(this.upVector);
  22207. };
  22208. // Synchronized
  22209. Camera.prototype._isSynchronized = function () {
  22210. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22211. };
  22212. Camera.prototype._isSynchronizedViewMatrix = function () {
  22213. if (!_super.prototype._isSynchronized.call(this))
  22214. return false;
  22215. return this._cache.position.equals(this.position)
  22216. && this._cache.upVector.equals(this.upVector)
  22217. && this.isSynchronizedWithParent();
  22218. };
  22219. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22220. var check = this._cache.mode === this.mode
  22221. && this._cache.minZ === this.minZ
  22222. && this._cache.maxZ === this.maxZ;
  22223. if (!check) {
  22224. return false;
  22225. }
  22226. var engine = this.getEngine();
  22227. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22228. check = this._cache.fov === this.fov
  22229. && this._cache.fovMode === this.fovMode
  22230. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22231. }
  22232. else {
  22233. check = this._cache.orthoLeft === this.orthoLeft
  22234. && this._cache.orthoRight === this.orthoRight
  22235. && this._cache.orthoBottom === this.orthoBottom
  22236. && this._cache.orthoTop === this.orthoTop
  22237. && this._cache.renderWidth === engine.getRenderWidth()
  22238. && this._cache.renderHeight === engine.getRenderHeight();
  22239. }
  22240. return check;
  22241. };
  22242. // Controls
  22243. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22244. };
  22245. Camera.prototype.detachControl = function (element) {
  22246. };
  22247. Camera.prototype.update = function () {
  22248. this._checkInputs();
  22249. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22250. this._updateRigCameras();
  22251. }
  22252. };
  22253. Camera.prototype._checkInputs = function () {
  22254. this.onAfterCheckInputsObservable.notifyObservers(this);
  22255. };
  22256. Object.defineProperty(Camera.prototype, "rigCameras", {
  22257. get: function () {
  22258. return this._rigCameras;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22264. get: function () {
  22265. return this._rigPostProcess;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. /**
  22271. * Internal, gets the first post proces.
  22272. * @returns the first post process to be run on this camera.
  22273. */
  22274. Camera.prototype._getFirstPostProcess = function () {
  22275. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22276. if (this._postProcesses[ppIndex] !== null) {
  22277. return this._postProcesses[ppIndex];
  22278. }
  22279. }
  22280. return null;
  22281. };
  22282. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22283. // invalidate framebuffer
  22284. var firstPostProcess = this._getFirstPostProcess();
  22285. if (firstPostProcess) {
  22286. firstPostProcess.markTextureDirty();
  22287. }
  22288. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22289. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22290. var cam = this._rigCameras[i];
  22291. var rigPostProcess = cam._rigPostProcess;
  22292. // for VR rig, there does not have to be a post process
  22293. if (rigPostProcess) {
  22294. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22295. if (isPass) {
  22296. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22297. cam.isIntermediate = this._postProcesses.length === 0;
  22298. }
  22299. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22300. rigPostProcess.markTextureDirty();
  22301. }
  22302. else {
  22303. cam._postProcesses = this._postProcesses.slice(0);
  22304. }
  22305. }
  22306. };
  22307. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22308. if (insertAt === void 0) { insertAt = null; }
  22309. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22310. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22311. return 0;
  22312. }
  22313. if (insertAt == null || insertAt < 0) {
  22314. this._postProcesses.push(postProcess);
  22315. }
  22316. else if (this._postProcesses[insertAt] === null) {
  22317. this._postProcesses[insertAt] = postProcess;
  22318. }
  22319. else {
  22320. this._postProcesses.splice(insertAt, 0, postProcess);
  22321. }
  22322. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22323. return this._postProcesses.indexOf(postProcess);
  22324. };
  22325. Camera.prototype.detachPostProcess = function (postProcess) {
  22326. var idx = this._postProcesses.indexOf(postProcess);
  22327. if (idx !== -1) {
  22328. this._postProcesses[idx] = null;
  22329. }
  22330. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22331. };
  22332. Camera.prototype.getWorldMatrix = function () {
  22333. if (this._isSynchronizedViewMatrix()) {
  22334. return this._worldMatrix;
  22335. }
  22336. // Getting the the view matrix will also compute the world matrix.
  22337. this.getViewMatrix();
  22338. return this._worldMatrix;
  22339. };
  22340. Camera.prototype._getViewMatrix = function () {
  22341. return BABYLON.Matrix.Identity();
  22342. };
  22343. Camera.prototype.getViewMatrix = function (force) {
  22344. if (!force && this._isSynchronizedViewMatrix()) {
  22345. return this._computedViewMatrix;
  22346. }
  22347. this.updateCache();
  22348. this._computedViewMatrix = this._getViewMatrix();
  22349. this._currentRenderId = this.getScene().getRenderId();
  22350. this._childRenderId = this._currentRenderId;
  22351. this._refreshFrustumPlanes = true;
  22352. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22353. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22354. }
  22355. this.onViewMatrixChangedObservable.notifyObservers(this);
  22356. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22357. return this._computedViewMatrix;
  22358. };
  22359. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22360. this._doNotComputeProjectionMatrix = true;
  22361. if (projection !== undefined) {
  22362. this._projectionMatrix = projection;
  22363. }
  22364. };
  22365. ;
  22366. Camera.prototype.unfreezeProjectionMatrix = function () {
  22367. this._doNotComputeProjectionMatrix = false;
  22368. };
  22369. ;
  22370. Camera.prototype.getProjectionMatrix = function (force) {
  22371. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22372. return this._projectionMatrix;
  22373. }
  22374. // Cache
  22375. this._cache.mode = this.mode;
  22376. this._cache.minZ = this.minZ;
  22377. this._cache.maxZ = this.maxZ;
  22378. // Matrix
  22379. this._refreshFrustumPlanes = true;
  22380. var engine = this.getEngine();
  22381. var scene = this.getScene();
  22382. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22383. this._cache.fov = this.fov;
  22384. this._cache.fovMode = this.fovMode;
  22385. this._cache.aspectRatio = engine.getAspectRatio(this);
  22386. if (this.minZ <= 0) {
  22387. this.minZ = 0.1;
  22388. }
  22389. if (scene.useRightHandedSystem) {
  22390. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22391. }
  22392. else {
  22393. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22394. }
  22395. }
  22396. else {
  22397. var halfWidth = engine.getRenderWidth() / 2.0;
  22398. var halfHeight = engine.getRenderHeight() / 2.0;
  22399. if (scene.useRightHandedSystem) {
  22400. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22401. }
  22402. else {
  22403. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22404. }
  22405. this._cache.orthoLeft = this.orthoLeft;
  22406. this._cache.orthoRight = this.orthoRight;
  22407. this._cache.orthoBottom = this.orthoBottom;
  22408. this._cache.orthoTop = this.orthoTop;
  22409. this._cache.renderWidth = engine.getRenderWidth();
  22410. this._cache.renderHeight = engine.getRenderHeight();
  22411. }
  22412. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22413. return this._projectionMatrix;
  22414. };
  22415. Camera.prototype.getTranformationMatrix = function () {
  22416. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22417. return this._transformMatrix;
  22418. };
  22419. Camera.prototype.updateFrustumPlanes = function () {
  22420. if (!this._refreshFrustumPlanes) {
  22421. return;
  22422. }
  22423. this.getTranformationMatrix();
  22424. if (!this._frustumPlanes) {
  22425. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22426. }
  22427. else {
  22428. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22429. }
  22430. this._refreshFrustumPlanes = false;
  22431. };
  22432. Camera.prototype.isInFrustum = function (target) {
  22433. this.updateFrustumPlanes();
  22434. return target.isInFrustum(this._frustumPlanes);
  22435. };
  22436. Camera.prototype.isCompletelyInFrustum = function (target) {
  22437. this.updateFrustumPlanes();
  22438. return target.isCompletelyInFrustum(this._frustumPlanes);
  22439. };
  22440. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22441. if (length === void 0) { length = 100; }
  22442. if (!transform) {
  22443. transform = this.getWorldMatrix();
  22444. }
  22445. if (!origin) {
  22446. origin = this.position;
  22447. }
  22448. var forward = new BABYLON.Vector3(0, 0, 1);
  22449. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22450. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22451. return new BABYLON.Ray(origin, direction, length);
  22452. };
  22453. /**
  22454. * Releases resources associated with this node.
  22455. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22456. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22457. */
  22458. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22459. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22460. // Observables
  22461. this.onViewMatrixChangedObservable.clear();
  22462. this.onProjectionMatrixChangedObservable.clear();
  22463. this.onAfterCheckInputsObservable.clear();
  22464. this.onRestoreStateObservable.clear();
  22465. // Inputs
  22466. if (this.inputs) {
  22467. this.inputs.clear();
  22468. }
  22469. // Animations
  22470. this.getScene().stopAnimation(this);
  22471. // Remove from scene
  22472. this.getScene().removeCamera(this);
  22473. while (this._rigCameras.length > 0) {
  22474. var camera = this._rigCameras.pop();
  22475. if (camera) {
  22476. camera.dispose();
  22477. }
  22478. }
  22479. // Postprocesses
  22480. if (this._rigPostProcess) {
  22481. this._rigPostProcess.dispose(this);
  22482. this._rigPostProcess = null;
  22483. this._postProcesses = [];
  22484. }
  22485. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22486. this._rigPostProcess = null;
  22487. this._postProcesses = [];
  22488. }
  22489. else {
  22490. var i = this._postProcesses.length;
  22491. while (--i >= 0) {
  22492. var postProcess = this._postProcesses[i];
  22493. if (postProcess) {
  22494. postProcess.dispose(this);
  22495. }
  22496. }
  22497. }
  22498. // Render targets
  22499. var i = this.customRenderTargets.length;
  22500. while (--i >= 0) {
  22501. this.customRenderTargets[i].dispose();
  22502. }
  22503. this.customRenderTargets = [];
  22504. // Active Meshes
  22505. this._activeMeshes.dispose();
  22506. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22507. };
  22508. Object.defineProperty(Camera.prototype, "leftCamera", {
  22509. // ---- Camera rigs section ----
  22510. get: function () {
  22511. if (this._rigCameras.length < 1) {
  22512. return null;
  22513. }
  22514. return this._rigCameras[0];
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Object.defineProperty(Camera.prototype, "rightCamera", {
  22520. get: function () {
  22521. if (this._rigCameras.length < 2) {
  22522. return null;
  22523. }
  22524. return this._rigCameras[1];
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Camera.prototype.getLeftTarget = function () {
  22530. if (this._rigCameras.length < 1) {
  22531. return null;
  22532. }
  22533. return this._rigCameras[0].getTarget();
  22534. };
  22535. Camera.prototype.getRightTarget = function () {
  22536. if (this._rigCameras.length < 2) {
  22537. return null;
  22538. }
  22539. return this._rigCameras[1].getTarget();
  22540. };
  22541. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22542. if (this.cameraRigMode === mode) {
  22543. return;
  22544. }
  22545. while (this._rigCameras.length > 0) {
  22546. var camera = this._rigCameras.pop();
  22547. if (camera) {
  22548. camera.dispose();
  22549. }
  22550. }
  22551. this.cameraRigMode = mode;
  22552. this._cameraRigParams = {};
  22553. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22554. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22555. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22556. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22557. // create the rig cameras, unless none
  22558. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22559. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22560. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22561. if (leftCamera && rightCamera) {
  22562. this._rigCameras.push(leftCamera);
  22563. this._rigCameras.push(rightCamera);
  22564. }
  22565. }
  22566. switch (this.cameraRigMode) {
  22567. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22568. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22569. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22570. break;
  22571. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22572. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22573. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22574. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22575. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22576. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22577. break;
  22578. case Camera.RIG_MODE_VR:
  22579. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22580. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22581. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22582. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22583. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22584. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22585. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22586. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22587. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22588. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22589. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22590. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22591. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22592. if (metrics.compensateDistortion) {
  22593. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22594. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22595. }
  22596. break;
  22597. case Camera.RIG_MODE_WEBVR:
  22598. if (rigParams.vrDisplay) {
  22599. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22600. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22601. //Left eye
  22602. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22603. this._rigCameras[0].setCameraRigParameter("left", true);
  22604. //leaving this for future reference
  22605. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22606. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22607. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22608. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22609. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22610. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22611. this._rigCameras[0].parent = this;
  22612. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22613. //Right eye
  22614. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22615. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22616. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22617. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22618. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22619. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22620. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22621. this._rigCameras[1].parent = this;
  22622. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22623. if (Camera.UseAlternateWebVRRendering) {
  22624. this._rigCameras[1]._skipRendering = true;
  22625. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22626. }
  22627. }
  22628. break;
  22629. }
  22630. this._cascadePostProcessesToRigCams();
  22631. this.update();
  22632. };
  22633. Camera.prototype._getVRProjectionMatrix = function () {
  22634. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22635. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22636. return this._projectionMatrix;
  22637. };
  22638. Camera.prototype._updateCameraRotationMatrix = function () {
  22639. //Here for WebVR
  22640. };
  22641. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22642. //Here for WebVR
  22643. };
  22644. /**
  22645. * This function MUST be overwritten by the different WebVR cameras available.
  22646. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22647. */
  22648. Camera.prototype._getWebVRProjectionMatrix = function () {
  22649. return BABYLON.Matrix.Identity();
  22650. };
  22651. /**
  22652. * This function MUST be overwritten by the different WebVR cameras available.
  22653. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22654. */
  22655. Camera.prototype._getWebVRViewMatrix = function () {
  22656. return BABYLON.Matrix.Identity();
  22657. };
  22658. Camera.prototype.setCameraRigParameter = function (name, value) {
  22659. if (!this._cameraRigParams) {
  22660. this._cameraRigParams = {};
  22661. }
  22662. this._cameraRigParams[name] = value;
  22663. //provisionnally:
  22664. if (name === "interaxialDistance") {
  22665. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22666. }
  22667. };
  22668. /**
  22669. * needs to be overridden by children so sub has required properties to be copied
  22670. */
  22671. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22672. return null;
  22673. };
  22674. /**
  22675. * May need to be overridden by children
  22676. */
  22677. Camera.prototype._updateRigCameras = function () {
  22678. for (var i = 0; i < this._rigCameras.length; i++) {
  22679. this._rigCameras[i].minZ = this.minZ;
  22680. this._rigCameras[i].maxZ = this.maxZ;
  22681. this._rigCameras[i].fov = this.fov;
  22682. }
  22683. // only update viewport when ANAGLYPH
  22684. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22685. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22686. }
  22687. };
  22688. Camera.prototype._setupInputs = function () {
  22689. };
  22690. Camera.prototype.serialize = function () {
  22691. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22692. // Type
  22693. serializationObject.type = this.getClassName();
  22694. // Parent
  22695. if (this.parent) {
  22696. serializationObject.parentId = this.parent.id;
  22697. }
  22698. if (this.inputs) {
  22699. this.inputs.serialize(serializationObject);
  22700. }
  22701. // Animations
  22702. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22703. serializationObject.ranges = this.serializeAnimationRanges();
  22704. return serializationObject;
  22705. };
  22706. Camera.prototype.clone = function (name) {
  22707. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22708. };
  22709. Camera.prototype.getDirection = function (localAxis) {
  22710. var result = BABYLON.Vector3.Zero();
  22711. this.getDirectionToRef(localAxis, result);
  22712. return result;
  22713. };
  22714. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22715. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22716. };
  22717. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22718. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22719. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22720. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22721. interaxial_distance: interaxial_distance,
  22722. isStereoscopicSideBySide: isStereoscopicSideBySide
  22723. });
  22724. if (constructorFunc) {
  22725. return constructorFunc;
  22726. }
  22727. // Default to universal camera
  22728. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22729. };
  22730. Camera.prototype.computeWorldMatrix = function () {
  22731. return this.getWorldMatrix();
  22732. };
  22733. Camera.Parse = function (parsedCamera, scene) {
  22734. var type = parsedCamera.type;
  22735. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22736. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22737. // Parent
  22738. if (parsedCamera.parentId) {
  22739. camera._waitingParentId = parsedCamera.parentId;
  22740. }
  22741. //If camera has an input manager, let it parse inputs settings
  22742. if (camera.inputs) {
  22743. camera.inputs.parse(parsedCamera);
  22744. camera._setupInputs();
  22745. }
  22746. if (camera.setPosition) { // need to force position
  22747. camera.position.copyFromFloats(0, 0, 0);
  22748. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22749. }
  22750. // Target
  22751. if (parsedCamera.target) {
  22752. if (camera.setTarget) {
  22753. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22754. }
  22755. }
  22756. // Apply 3d rig, when found
  22757. if (parsedCamera.cameraRigMode) {
  22758. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22759. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22760. }
  22761. // Animations
  22762. if (parsedCamera.animations) {
  22763. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22764. var parsedAnimation = parsedCamera.animations[animationIndex];
  22765. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22766. }
  22767. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22768. }
  22769. if (parsedCamera.autoAnimate) {
  22770. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22771. }
  22772. return camera;
  22773. };
  22774. // Statics
  22775. Camera._PERSPECTIVE_CAMERA = 0;
  22776. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22777. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22778. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22779. Camera._RIG_MODE_NONE = 0;
  22780. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22781. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22782. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22783. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22784. Camera._RIG_MODE_VR = 20;
  22785. Camera._RIG_MODE_WEBVR = 21;
  22786. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22787. Camera.UseAlternateWebVRRendering = false;
  22788. __decorate([
  22789. BABYLON.serializeAsVector3()
  22790. ], Camera.prototype, "position", void 0);
  22791. __decorate([
  22792. BABYLON.serializeAsVector3()
  22793. ], Camera.prototype, "upVector", void 0);
  22794. __decorate([
  22795. BABYLON.serialize()
  22796. ], Camera.prototype, "orthoLeft", void 0);
  22797. __decorate([
  22798. BABYLON.serialize()
  22799. ], Camera.prototype, "orthoRight", void 0);
  22800. __decorate([
  22801. BABYLON.serialize()
  22802. ], Camera.prototype, "orthoBottom", void 0);
  22803. __decorate([
  22804. BABYLON.serialize()
  22805. ], Camera.prototype, "orthoTop", void 0);
  22806. __decorate([
  22807. BABYLON.serialize()
  22808. ], Camera.prototype, "fov", void 0);
  22809. __decorate([
  22810. BABYLON.serialize()
  22811. ], Camera.prototype, "minZ", void 0);
  22812. __decorate([
  22813. BABYLON.serialize()
  22814. ], Camera.prototype, "maxZ", void 0);
  22815. __decorate([
  22816. BABYLON.serialize()
  22817. ], Camera.prototype, "inertia", void 0);
  22818. __decorate([
  22819. BABYLON.serialize()
  22820. ], Camera.prototype, "mode", void 0);
  22821. __decorate([
  22822. BABYLON.serialize()
  22823. ], Camera.prototype, "layerMask", void 0);
  22824. __decorate([
  22825. BABYLON.serialize()
  22826. ], Camera.prototype, "fovMode", void 0);
  22827. __decorate([
  22828. BABYLON.serialize()
  22829. ], Camera.prototype, "cameraRigMode", void 0);
  22830. __decorate([
  22831. BABYLON.serialize()
  22832. ], Camera.prototype, "interaxialDistance", void 0);
  22833. __decorate([
  22834. BABYLON.serialize()
  22835. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22836. return Camera;
  22837. }(BABYLON.Node));
  22838. BABYLON.Camera = Camera;
  22839. })(BABYLON || (BABYLON = {}));
  22840. //# sourceMappingURL=babylon.camera.js.map
  22841. var BABYLON;
  22842. (function (BABYLON) {
  22843. var RenderingManager = /** @class */ (function () {
  22844. function RenderingManager(scene) {
  22845. /**
  22846. * Hidden
  22847. */
  22848. this._useSceneAutoClearSetup = false;
  22849. this._renderingGroups = new Array();
  22850. this._autoClearDepthStencil = {};
  22851. this._customOpaqueSortCompareFn = {};
  22852. this._customAlphaTestSortCompareFn = {};
  22853. this._customTransparentSortCompareFn = {};
  22854. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22855. this._scene = scene;
  22856. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22857. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22858. }
  22859. }
  22860. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22861. if (depth === void 0) { depth = true; }
  22862. if (stencil === void 0) { stencil = true; }
  22863. if (this._depthStencilBufferAlreadyCleaned) {
  22864. return;
  22865. }
  22866. this._scene.getEngine().clear(null, false, depth, stencil);
  22867. this._depthStencilBufferAlreadyCleaned = true;
  22868. };
  22869. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22870. // Update the observable context (not null as it only goes away on dispose)
  22871. var info = this._renderingGroupInfo;
  22872. info.scene = this._scene;
  22873. info.camera = this._scene.activeCamera;
  22874. // Dispatch sprites
  22875. if (renderSprites) {
  22876. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22877. var manager = this._scene.spriteManagers[index];
  22878. this.dispatchSprites(manager);
  22879. }
  22880. }
  22881. // Render
  22882. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22883. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22884. var renderingGroup = this._renderingGroups[index];
  22885. if (!renderingGroup)
  22886. continue;
  22887. var renderingGroupMask = Math.pow(2, index);
  22888. info.renderingGroupId = index;
  22889. // Before Observable
  22890. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22891. // Clear depth/stencil if needed
  22892. if (RenderingManager.AUTOCLEAR) {
  22893. var autoClear = this._useSceneAutoClearSetup ?
  22894. this._scene.getAutoClearDepthStencilSetup(index) :
  22895. this._autoClearDepthStencil[index];
  22896. if (autoClear && autoClear.autoClear) {
  22897. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22898. }
  22899. }
  22900. // Render
  22901. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22902. var step = _a[_i];
  22903. step.action(index);
  22904. }
  22905. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22906. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22907. var step = _c[_b];
  22908. step.action(index);
  22909. }
  22910. // After Observable
  22911. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22912. }
  22913. };
  22914. RenderingManager.prototype.reset = function () {
  22915. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22916. var renderingGroup = this._renderingGroups[index];
  22917. if (renderingGroup) {
  22918. renderingGroup.prepare();
  22919. }
  22920. }
  22921. };
  22922. RenderingManager.prototype.dispose = function () {
  22923. this.freeRenderingGroups();
  22924. this._renderingGroups.length = 0;
  22925. this._renderingGroupInfo = null;
  22926. };
  22927. /**
  22928. * Clear the info related to rendering groups preventing retention points during dispose.
  22929. */
  22930. RenderingManager.prototype.freeRenderingGroups = function () {
  22931. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22932. var renderingGroup = this._renderingGroups[index];
  22933. if (renderingGroup) {
  22934. renderingGroup.dispose();
  22935. }
  22936. }
  22937. };
  22938. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22939. if (this._renderingGroups[renderingGroupId] === undefined) {
  22940. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22941. }
  22942. };
  22943. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22944. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22945. this._prepareRenderingGroup(renderingGroupId);
  22946. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22947. };
  22948. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22949. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22950. this._prepareRenderingGroup(renderingGroupId);
  22951. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22952. };
  22953. /**
  22954. * @param subMesh The submesh to dispatch
  22955. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22956. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22957. */
  22958. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22959. if (mesh === undefined) {
  22960. mesh = subMesh.getMesh();
  22961. }
  22962. var renderingGroupId = mesh.renderingGroupId || 0;
  22963. this._prepareRenderingGroup(renderingGroupId);
  22964. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22965. };
  22966. /**
  22967. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22968. * This allowed control for front to back rendering or reversly depending of the special needs.
  22969. *
  22970. * @param renderingGroupId The rendering group id corresponding to its index
  22971. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22972. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22973. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22974. */
  22975. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22976. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22977. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22978. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22979. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22980. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22981. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22982. if (this._renderingGroups[renderingGroupId]) {
  22983. var group = this._renderingGroups[renderingGroupId];
  22984. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22985. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22986. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22987. }
  22988. };
  22989. /**
  22990. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22991. *
  22992. * @param renderingGroupId The rendering group id corresponding to its index
  22993. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22994. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22995. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22996. */
  22997. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22998. if (depth === void 0) { depth = true; }
  22999. if (stencil === void 0) { stencil = true; }
  23000. this._autoClearDepthStencil[renderingGroupId] = {
  23001. autoClear: autoClearDepthStencil,
  23002. depth: depth,
  23003. stencil: stencil
  23004. };
  23005. };
  23006. /**
  23007. * Gets the current auto clear configuration for one rendering group of the rendering
  23008. * manager.
  23009. * @param index the rendering group index to get the information for
  23010. * @returns The auto clear setup for the requested rendering group
  23011. */
  23012. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23013. return this._autoClearDepthStencil[index];
  23014. };
  23015. /**
  23016. * The max id used for rendering groups (not included)
  23017. */
  23018. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23019. /**
  23020. * The min id used for rendering groups (included)
  23021. */
  23022. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23023. /**
  23024. * Used to globally prevent autoclearing scenes.
  23025. */
  23026. RenderingManager.AUTOCLEAR = true;
  23027. return RenderingManager;
  23028. }());
  23029. BABYLON.RenderingManager = RenderingManager;
  23030. })(BABYLON || (BABYLON = {}));
  23031. //# sourceMappingURL=babylon.renderingManager.js.map
  23032. var BABYLON;
  23033. (function (BABYLON) {
  23034. var RenderingGroup = /** @class */ (function () {
  23035. /**
  23036. * Creates a new rendering group.
  23037. * @param index The rendering group index
  23038. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23039. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23040. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23041. */
  23042. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23043. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23044. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23045. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23046. this.index = index;
  23047. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23048. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23049. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23050. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23051. this._particleSystems = new BABYLON.SmartArray(256);
  23052. this._spriteManagers = new BABYLON.SmartArray(256);
  23053. this._edgesRenderers = new BABYLON.SmartArray(16);
  23054. this._scene = scene;
  23055. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23056. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23057. this.transparentSortCompareFn = transparentSortCompareFn;
  23058. }
  23059. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23060. /**
  23061. * Set the opaque sort comparison function.
  23062. * If null the sub meshes will be render in the order they were created
  23063. */
  23064. set: function (value) {
  23065. this._opaqueSortCompareFn = value;
  23066. if (value) {
  23067. this._renderOpaque = this.renderOpaqueSorted;
  23068. }
  23069. else {
  23070. this._renderOpaque = RenderingGroup.renderUnsorted;
  23071. }
  23072. },
  23073. enumerable: true,
  23074. configurable: true
  23075. });
  23076. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23077. /**
  23078. * Set the alpha test sort comparison function.
  23079. * If null the sub meshes will be render in the order they were created
  23080. */
  23081. set: function (value) {
  23082. this._alphaTestSortCompareFn = value;
  23083. if (value) {
  23084. this._renderAlphaTest = this.renderAlphaTestSorted;
  23085. }
  23086. else {
  23087. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23088. }
  23089. },
  23090. enumerable: true,
  23091. configurable: true
  23092. });
  23093. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23094. /**
  23095. * Set the transparent sort comparison function.
  23096. * If null the sub meshes will be render in the order they were created
  23097. */
  23098. set: function (value) {
  23099. if (value) {
  23100. this._transparentSortCompareFn = value;
  23101. }
  23102. else {
  23103. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23104. }
  23105. this._renderTransparent = this.renderTransparentSorted;
  23106. },
  23107. enumerable: true,
  23108. configurable: true
  23109. });
  23110. /**
  23111. * Render all the sub meshes contained in the group.
  23112. * @param customRenderFunction Used to override the default render behaviour of the group.
  23113. * @returns true if rendered some submeshes.
  23114. */
  23115. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23116. if (customRenderFunction) {
  23117. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23118. return;
  23119. }
  23120. var engine = this._scene.getEngine();
  23121. // Depth only
  23122. if (this._depthOnlySubMeshes.length !== 0) {
  23123. engine.setColorWrite(false);
  23124. this._renderAlphaTest(this._depthOnlySubMeshes);
  23125. engine.setColorWrite(true);
  23126. }
  23127. // Opaque
  23128. if (this._opaqueSubMeshes.length !== 0) {
  23129. this._renderOpaque(this._opaqueSubMeshes);
  23130. }
  23131. // Alpha test
  23132. if (this._alphaTestSubMeshes.length !== 0) {
  23133. this._renderAlphaTest(this._alphaTestSubMeshes);
  23134. }
  23135. var stencilState = engine.getStencilBuffer();
  23136. engine.setStencilBuffer(false);
  23137. // Sprites
  23138. if (renderSprites) {
  23139. this._renderSprites();
  23140. }
  23141. // Particles
  23142. if (renderParticles) {
  23143. this._renderParticles(activeMeshes);
  23144. }
  23145. if (this.onBeforeTransparentRendering) {
  23146. this.onBeforeTransparentRendering();
  23147. }
  23148. // Transparent
  23149. if (this._transparentSubMeshes.length !== 0) {
  23150. this._renderTransparent(this._transparentSubMeshes);
  23151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23152. }
  23153. // Set back stencil to false in case it changes before the edge renderer.
  23154. engine.setStencilBuffer(false);
  23155. // Edges
  23156. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23157. this._edgesRenderers.data[edgesRendererIndex].render();
  23158. }
  23159. // Restore Stencil state.
  23160. engine.setStencilBuffer(stencilState);
  23161. };
  23162. /**
  23163. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23164. * @param subMeshes The submeshes to render
  23165. */
  23166. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23167. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23168. };
  23169. /**
  23170. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23171. * @param subMeshes The submeshes to render
  23172. */
  23173. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23174. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23175. };
  23176. /**
  23177. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23178. * @param subMeshes The submeshes to render
  23179. */
  23180. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23181. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23182. };
  23183. /**
  23184. * Renders the submeshes in a specified order.
  23185. * @param subMeshes The submeshes to sort before render
  23186. * @param sortCompareFn The comparison function use to sort
  23187. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23188. * @param transparent Specifies to activate blending if true
  23189. */
  23190. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23191. var subIndex = 0;
  23192. var subMesh;
  23193. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23194. for (; subIndex < subMeshes.length; subIndex++) {
  23195. subMesh = subMeshes.data[subIndex];
  23196. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23197. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23198. }
  23199. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23200. if (sortCompareFn) {
  23201. sortedArray.sort(sortCompareFn);
  23202. }
  23203. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23204. subMesh = sortedArray[subIndex];
  23205. if (transparent) {
  23206. var material = subMesh.getMaterial();
  23207. if (material && material.needDepthPrePass) {
  23208. var engine = material.getScene().getEngine();
  23209. engine.setColorWrite(false);
  23210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23211. subMesh.render(false);
  23212. engine.setColorWrite(true);
  23213. }
  23214. }
  23215. subMesh.render(transparent);
  23216. }
  23217. };
  23218. /**
  23219. * Renders the submeshes in the order they were dispatched (no sort applied).
  23220. * @param subMeshes The submeshes to render
  23221. */
  23222. RenderingGroup.renderUnsorted = function (subMeshes) {
  23223. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23224. var submesh = subMeshes.data[subIndex];
  23225. submesh.render(false);
  23226. }
  23227. };
  23228. /**
  23229. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23230. * are rendered back to front if in the same alpha index.
  23231. *
  23232. * @param a The first submesh
  23233. * @param b The second submesh
  23234. * @returns The result of the comparison
  23235. */
  23236. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23237. // Alpha index first
  23238. if (a._alphaIndex > b._alphaIndex) {
  23239. return 1;
  23240. }
  23241. if (a._alphaIndex < b._alphaIndex) {
  23242. return -1;
  23243. }
  23244. // Then distance to camera
  23245. return RenderingGroup.backToFrontSortCompare(a, b);
  23246. };
  23247. /**
  23248. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23249. * are rendered back to front.
  23250. *
  23251. * @param a The first submesh
  23252. * @param b The second submesh
  23253. * @returns The result of the comparison
  23254. */
  23255. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23256. // Then distance to camera
  23257. if (a._distanceToCamera < b._distanceToCamera) {
  23258. return 1;
  23259. }
  23260. if (a._distanceToCamera > b._distanceToCamera) {
  23261. return -1;
  23262. }
  23263. return 0;
  23264. };
  23265. /**
  23266. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23267. * are rendered front to back (prevent overdraw).
  23268. *
  23269. * @param a The first submesh
  23270. * @param b The second submesh
  23271. * @returns The result of the comparison
  23272. */
  23273. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23274. // Then distance to camera
  23275. if (a._distanceToCamera < b._distanceToCamera) {
  23276. return -1;
  23277. }
  23278. if (a._distanceToCamera > b._distanceToCamera) {
  23279. return 1;
  23280. }
  23281. return 0;
  23282. };
  23283. /**
  23284. * Resets the different lists of submeshes to prepare a new frame.
  23285. */
  23286. RenderingGroup.prototype.prepare = function () {
  23287. this._opaqueSubMeshes.reset();
  23288. this._transparentSubMeshes.reset();
  23289. this._alphaTestSubMeshes.reset();
  23290. this._depthOnlySubMeshes.reset();
  23291. this._particleSystems.reset();
  23292. this._spriteManagers.reset();
  23293. this._edgesRenderers.reset();
  23294. };
  23295. RenderingGroup.prototype.dispose = function () {
  23296. this._opaqueSubMeshes.dispose();
  23297. this._transparentSubMeshes.dispose();
  23298. this._alphaTestSubMeshes.dispose();
  23299. this._depthOnlySubMeshes.dispose();
  23300. this._particleSystems.dispose();
  23301. this._spriteManagers.dispose();
  23302. this._edgesRenderers.dispose();
  23303. };
  23304. /**
  23305. * Inserts the submesh in its correct queue depending on its material.
  23306. * @param subMesh The submesh to dispatch
  23307. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23308. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23309. */
  23310. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23311. // Get mesh and materials if not provided
  23312. if (mesh === undefined) {
  23313. mesh = subMesh.getMesh();
  23314. }
  23315. if (material === undefined) {
  23316. material = subMesh.getMaterial();
  23317. }
  23318. if (material === null || material === undefined) {
  23319. return;
  23320. }
  23321. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23322. this._transparentSubMeshes.push(subMesh);
  23323. }
  23324. else if (material.needAlphaTesting()) { // Alpha test
  23325. if (material.needDepthPrePass) {
  23326. this._depthOnlySubMeshes.push(subMesh);
  23327. }
  23328. this._alphaTestSubMeshes.push(subMesh);
  23329. }
  23330. else {
  23331. if (material.needDepthPrePass) {
  23332. this._depthOnlySubMeshes.push(subMesh);
  23333. }
  23334. this._opaqueSubMeshes.push(subMesh); // Opaque
  23335. }
  23336. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23337. this._edgesRenderers.push(mesh._edgesRenderer);
  23338. }
  23339. };
  23340. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23341. this._spriteManagers.push(spriteManager);
  23342. };
  23343. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23344. this._particleSystems.push(particleSystem);
  23345. };
  23346. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23347. if (this._particleSystems.length === 0) {
  23348. return;
  23349. }
  23350. // Particles
  23351. var activeCamera = this._scene.activeCamera;
  23352. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23353. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23354. var particleSystem = this._particleSystems.data[particleIndex];
  23355. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23356. continue;
  23357. }
  23358. var emitter = particleSystem.emitter;
  23359. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23360. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23361. }
  23362. }
  23363. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23364. };
  23365. RenderingGroup.prototype._renderSprites = function () {
  23366. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23367. return;
  23368. }
  23369. // Sprites
  23370. var activeCamera = this._scene.activeCamera;
  23371. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23372. for (var id = 0; id < this._spriteManagers.length; id++) {
  23373. var spriteManager = this._spriteManagers.data[id];
  23374. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23375. spriteManager.render();
  23376. }
  23377. }
  23378. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23379. };
  23380. return RenderingGroup;
  23381. }());
  23382. BABYLON.RenderingGroup = RenderingGroup;
  23383. })(BABYLON || (BABYLON = {}));
  23384. //# sourceMappingURL=babylon.renderingGroup.js.map
  23385. var BABYLON;
  23386. (function (BABYLON) {
  23387. /**
  23388. * Groups all the scene component constants in one place to ease maintenance.
  23389. * @hidden
  23390. */
  23391. var SceneComponentConstants = /** @class */ (function () {
  23392. function SceneComponentConstants() {
  23393. }
  23394. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23395. SceneComponentConstants.NAME_LAYER = "Layer";
  23396. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23397. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23398. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23399. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23400. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23401. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23402. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23403. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23404. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23405. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23406. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23407. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23408. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23409. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23410. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23411. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23412. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23413. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23414. return SceneComponentConstants;
  23415. }());
  23416. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23417. /**
  23418. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23419. * @hidden
  23420. */
  23421. var Stage = /** @class */ (function (_super) {
  23422. __extends(Stage, _super);
  23423. /**
  23424. * Hide ctor from the rest of the world.
  23425. * @param items The items to add.
  23426. */
  23427. function Stage(items) {
  23428. return _super.apply(this, items) || this;
  23429. }
  23430. /**
  23431. * Creates a new Stage.
  23432. * @returns A new instance of a Stage
  23433. */
  23434. Stage.Create = function () {
  23435. return Object.create(Stage.prototype);
  23436. };
  23437. /**
  23438. * Registers a step in an ordered way in the targeted stage.
  23439. * @param index Defines the position to register the step in
  23440. * @param component Defines the component attached to the step
  23441. * @param action Defines the action to launch during the step
  23442. */
  23443. Stage.prototype.registerStep = function (index, component, action) {
  23444. var i = 0;
  23445. var maxIndex = Number.MAX_VALUE;
  23446. for (; i < this.length && i < maxIndex; i++) {
  23447. var step = this[i];
  23448. maxIndex = step.index;
  23449. }
  23450. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23451. };
  23452. /**
  23453. * Clears all the steps from the stage.
  23454. */
  23455. Stage.prototype.clear = function () {
  23456. this.length = 0;
  23457. };
  23458. return Stage;
  23459. }(Array));
  23460. BABYLON.Stage = Stage;
  23461. })(BABYLON || (BABYLON = {}));
  23462. //# sourceMappingURL=babylon.sceneComponent.js.map
  23463. var BABYLON;
  23464. (function (BABYLON) {
  23465. /**
  23466. * Base class of the scene acting as a container for the different elements composing a scene.
  23467. * This class is dynamically extended by the different components of the scene increasing
  23468. * flexibility and reducing coupling
  23469. */
  23470. var AbstractScene = /** @class */ (function () {
  23471. function AbstractScene() {
  23472. /** All of the cameras added to this scene
  23473. * @see http://doc.babylonjs.com/babylon101/cameras
  23474. */
  23475. this.cameras = new Array();
  23476. /**
  23477. * All of the lights added to this scene
  23478. * @see http://doc.babylonjs.com/babylon101/lights
  23479. */
  23480. this.lights = new Array();
  23481. /**
  23482. * All of the (abstract) meshes added to this scene
  23483. */
  23484. this.meshes = new Array();
  23485. /**
  23486. * The list of skeletons added to the scene
  23487. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23488. */
  23489. this.skeletons = new Array();
  23490. /**
  23491. * All of the particle systems added to this scene
  23492. * @see http://doc.babylonjs.com/babylon101/particles
  23493. */
  23494. this.particleSystems = new Array();
  23495. /**
  23496. * Gets a list of Animations associated with the scene
  23497. */
  23498. this.animations = [];
  23499. /**
  23500. * All of the animation groups added to this scene
  23501. * @see http://doc.babylonjs.com/how_to/group
  23502. */
  23503. this.animationGroups = new Array();
  23504. /**
  23505. * All of the multi-materials added to this scene
  23506. * @see http://doc.babylonjs.com/how_to/multi_materials
  23507. */
  23508. this.multiMaterials = new Array();
  23509. /**
  23510. * All of the materials added to this scene
  23511. * @see http://doc.babylonjs.com/babylon101/materials
  23512. */
  23513. this.materials = new Array();
  23514. /**
  23515. * The list of morph target managers added to the scene
  23516. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23517. */
  23518. this.morphTargetManagers = new Array();
  23519. /**
  23520. * The list of geometries used in the scene.
  23521. */
  23522. this.geometries = new Array();
  23523. /**
  23524. * All of the tranform nodes added to this scene
  23525. * @see http://doc.babylonjs.com/how_to/transformnode
  23526. */
  23527. this.transformNodes = new Array();
  23528. /**
  23529. * ActionManagers available on the scene.
  23530. */
  23531. this.actionManagers = new Array();
  23532. /**
  23533. * Sounds to keep.
  23534. */
  23535. this.sounds = new Array();
  23536. /**
  23537. * Textures to keep.
  23538. */
  23539. this.textures = new Array();
  23540. }
  23541. /**
  23542. * Adds a parser in the list of available ones
  23543. * @param name Defines the name of the parser
  23544. * @param parser Defines the parser to add
  23545. */
  23546. AbstractScene.AddParser = function (name, parser) {
  23547. this._BabylonFileParsers[name] = parser;
  23548. };
  23549. /**
  23550. * Gets a general parser from the list of avaialble ones
  23551. * @param name Defines the name of the parser
  23552. * @returns the requested parser or null
  23553. */
  23554. AbstractScene.GetParser = function (name) {
  23555. if (this._BabylonFileParsers[name]) {
  23556. return this._BabylonFileParsers[name];
  23557. }
  23558. return null;
  23559. };
  23560. /**
  23561. * Adds n individual parser in the list of available ones
  23562. * @param name Defines the name of the parser
  23563. * @param parser Defines the parser to add
  23564. */
  23565. AbstractScene.AddIndividualParser = function (name, parser) {
  23566. this._IndividualBabylonFileParsers[name] = parser;
  23567. };
  23568. /**
  23569. * Gets an individual parser from the list of avaialble ones
  23570. * @param name Defines the name of the parser
  23571. * @returns the requested parser or null
  23572. */
  23573. AbstractScene.GetIndividualParser = function (name) {
  23574. if (this._IndividualBabylonFileParsers[name]) {
  23575. return this._IndividualBabylonFileParsers[name];
  23576. }
  23577. return null;
  23578. };
  23579. /**
  23580. * Parser json data and populate both a scene and its associated container object
  23581. * @param jsonData Defines the data to parse
  23582. * @param scene Defines the scene to parse the data for
  23583. * @param container Defines the container attached to the parsing sequence
  23584. * @param rootUrl Defines the root url of the data
  23585. */
  23586. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23587. for (var parserName in this._BabylonFileParsers) {
  23588. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23589. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23590. }
  23591. }
  23592. };
  23593. /**
  23594. * Stores the list of available parsers in the application.
  23595. */
  23596. AbstractScene._BabylonFileParsers = {};
  23597. /**
  23598. * Stores the list of available individual parsers in the application.
  23599. */
  23600. AbstractScene._IndividualBabylonFileParsers = {};
  23601. return AbstractScene;
  23602. }());
  23603. BABYLON.AbstractScene = AbstractScene;
  23604. })(BABYLON || (BABYLON = {}));
  23605. //# sourceMappingURL=babylon.abstractScene.js.map
  23606. var BABYLON;
  23607. (function (BABYLON) {
  23608. /** @hidden */
  23609. var ClickInfo = /** @class */ (function () {
  23610. function ClickInfo() {
  23611. this._singleClick = false;
  23612. this._doubleClick = false;
  23613. this._hasSwiped = false;
  23614. this._ignore = false;
  23615. }
  23616. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23617. get: function () {
  23618. return this._singleClick;
  23619. },
  23620. set: function (b) {
  23621. this._singleClick = b;
  23622. },
  23623. enumerable: true,
  23624. configurable: true
  23625. });
  23626. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23627. get: function () {
  23628. return this._doubleClick;
  23629. },
  23630. set: function (b) {
  23631. this._doubleClick = b;
  23632. },
  23633. enumerable: true,
  23634. configurable: true
  23635. });
  23636. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23637. get: function () {
  23638. return this._hasSwiped;
  23639. },
  23640. set: function (b) {
  23641. this._hasSwiped = b;
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23647. get: function () {
  23648. return this._ignore;
  23649. },
  23650. set: function (b) {
  23651. this._ignore = b;
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. return ClickInfo;
  23657. }());
  23658. /**
  23659. * This class is used by the onRenderingGroupObservable
  23660. */
  23661. var RenderingGroupInfo = /** @class */ (function () {
  23662. function RenderingGroupInfo() {
  23663. }
  23664. return RenderingGroupInfo;
  23665. }());
  23666. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23667. /**
  23668. * Represents a scene to be rendered by the engine.
  23669. * @see http://doc.babylonjs.com/features/scene
  23670. */
  23671. var Scene = /** @class */ (function (_super) {
  23672. __extends(Scene, _super);
  23673. /**
  23674. * Creates a new Scene
  23675. * @param engine defines the engine to use to render this scene
  23676. */
  23677. function Scene(engine) {
  23678. var _this = _super.call(this) || this;
  23679. // Members
  23680. /**
  23681. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23682. */
  23683. _this.autoClear = true;
  23684. /**
  23685. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23686. */
  23687. _this.autoClearDepthAndStencil = true;
  23688. /**
  23689. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23690. */
  23691. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23692. /**
  23693. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23694. */
  23695. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23696. _this._forceWireframe = false;
  23697. _this._forcePointsCloud = false;
  23698. /**
  23699. * Gets or sets a boolean indicating if animations are enabled
  23700. */
  23701. _this.animationsEnabled = true;
  23702. _this._animationPropertiesOverride = null;
  23703. /**
  23704. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23705. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23706. */
  23707. _this.useConstantAnimationDeltaTime = false;
  23708. /**
  23709. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23710. * Please note that it requires to run a ray cast through the scene on every frame
  23711. */
  23712. _this.constantlyUpdateMeshUnderPointer = false;
  23713. /**
  23714. * Defines the HTML cursor to use when hovering over interactive elements
  23715. */
  23716. _this.hoverCursor = "pointer";
  23717. /**
  23718. * Defines the HTML default cursor to use (empty by default)
  23719. */
  23720. _this.defaultCursor = "";
  23721. /**
  23722. * This is used to call preventDefault() on pointer down
  23723. * in order to block unwanted artifacts like system double clicks
  23724. */
  23725. _this.preventDefaultOnPointerDown = true;
  23726. // Metadata
  23727. /**
  23728. * Gets or sets user defined metadata
  23729. */
  23730. _this.metadata = null;
  23731. /**
  23732. * Use this array to add regular expressions used to disable offline support for specific urls
  23733. */
  23734. _this.disableOfflineSupportExceptionRules = new Array();
  23735. /**
  23736. * An event triggered when the scene is disposed.
  23737. */
  23738. _this.onDisposeObservable = new BABYLON.Observable();
  23739. _this._onDisposeObserver = null;
  23740. /**
  23741. * An event triggered before rendering the scene (right after animations and physics)
  23742. */
  23743. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23744. _this._onBeforeRenderObserver = null;
  23745. /**
  23746. * An event triggered after rendering the scene
  23747. */
  23748. _this.onAfterRenderObservable = new BABYLON.Observable();
  23749. _this._onAfterRenderObserver = null;
  23750. /**
  23751. * An event triggered before animating the scene
  23752. */
  23753. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23754. /**
  23755. * An event triggered after animations processing
  23756. */
  23757. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23758. /**
  23759. * An event triggered before draw calls are ready to be sent
  23760. */
  23761. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23762. /**
  23763. * An event triggered after draw calls have been sent
  23764. */
  23765. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23766. /**
  23767. * An event triggered when physic simulation is about to be run
  23768. */
  23769. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered when physic simulation has been done
  23772. */
  23773. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23774. /**
  23775. * An event triggered when the scene is ready
  23776. */
  23777. _this.onReadyObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered before rendering a camera
  23780. */
  23781. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23782. _this._onBeforeCameraRenderObserver = null;
  23783. /**
  23784. * An event triggered after rendering a camera
  23785. */
  23786. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23787. _this._onAfterCameraRenderObserver = null;
  23788. /**
  23789. * An event triggered when active meshes evaluation is about to start
  23790. */
  23791. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when active meshes evaluation is done
  23794. */
  23795. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when particles rendering is about to start
  23798. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23799. */
  23800. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23801. /**
  23802. * An event triggered when particles rendering is done
  23803. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23804. */
  23805. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23806. /**
  23807. * An event triggered when sprites rendering is about to start
  23808. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23809. */
  23810. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23811. /**
  23812. * An event triggered when sprites rendering is done
  23813. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23814. */
  23815. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23818. */
  23819. _this.onDataLoadedObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered when a camera is created
  23822. */
  23823. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered when a camera is removed
  23826. */
  23827. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered when a light is created
  23830. */
  23831. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered when a light is removed
  23834. */
  23835. _this.onLightRemovedObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered when a geometry is created
  23838. */
  23839. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered when a geometry is removed
  23842. */
  23843. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered when a transform node is created
  23846. */
  23847. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23848. /**
  23849. * An event triggered when a transform node is removed
  23850. */
  23851. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23852. /**
  23853. * An event triggered when a mesh is created
  23854. */
  23855. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23856. /**
  23857. * An event triggered when a mesh is removed
  23858. */
  23859. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23860. /**
  23861. * An event triggered when render targets are about to be rendered
  23862. * Can happen multiple times per frame.
  23863. */
  23864. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23865. /**
  23866. * An event triggered when render targets were rendered.
  23867. * Can happen multiple times per frame.
  23868. */
  23869. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23870. /**
  23871. * An event triggered before calculating deterministic simulation step
  23872. */
  23873. _this.onBeforeStepObservable = new BABYLON.Observable();
  23874. /**
  23875. * An event triggered after calculating deterministic simulation step
  23876. */
  23877. _this.onAfterStepObservable = new BABYLON.Observable();
  23878. /**
  23879. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23880. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23881. * 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)
  23882. */
  23883. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23884. /**
  23885. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23886. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23887. * 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)
  23888. */
  23889. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23890. // Animations
  23891. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23892. /**
  23893. * 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).
  23894. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23895. */
  23896. _this.onPrePointerObservable = new BABYLON.Observable();
  23897. /**
  23898. * Observable event triggered each time an input event is received from the rendering canvas
  23899. */
  23900. _this.onPointerObservable = new BABYLON.Observable();
  23901. _this._meshPickProceed = false;
  23902. _this._currentPickResult = null;
  23903. _this._previousPickResult = null;
  23904. _this._totalPointersPressed = 0;
  23905. _this._doubleClickOccured = false;
  23906. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23907. _this.cameraToUseForPointers = null;
  23908. _this._pointerX = 0;
  23909. _this._pointerY = 0;
  23910. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23911. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23912. _this._startingPointerTime = 0;
  23913. _this._previousStartingPointerTime = 0;
  23914. _this._pointerCaptures = {};
  23915. // Deterministic lockstep
  23916. _this._timeAccumulator = 0;
  23917. _this._currentStepId = 0;
  23918. _this._currentInternalStep = 0;
  23919. // Keyboard
  23920. /**
  23921. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23922. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23923. */
  23924. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23925. /**
  23926. * Observable event triggered each time an keyboard event is received from the hosting window
  23927. */
  23928. _this.onKeyboardObservable = new BABYLON.Observable();
  23929. // Coordinates system
  23930. _this._useRightHandedSystem = false;
  23931. // Fog
  23932. _this._fogEnabled = true;
  23933. _this._fogMode = Scene.FOGMODE_NONE;
  23934. /**
  23935. * Gets or sets the fog color to use
  23936. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23937. */
  23938. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23939. /**
  23940. * Gets or sets the fog density to use
  23941. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23942. */
  23943. _this.fogDensity = 0.1;
  23944. /**
  23945. * Gets or sets the fog start distance to use
  23946. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23947. */
  23948. _this.fogStart = 0;
  23949. /**
  23950. * Gets or sets the fog end distance to use
  23951. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23952. */
  23953. _this.fogEnd = 1000.0;
  23954. // Lights
  23955. _this._shadowsEnabled = true;
  23956. _this._lightsEnabled = true;
  23957. /** All of the active cameras added to this scene. */
  23958. _this.activeCameras = new Array();
  23959. // Textures
  23960. _this._texturesEnabled = true;
  23961. // Particles
  23962. /**
  23963. * Gets or sets a boolean indicating if particles are enabled on this scene
  23964. */
  23965. _this.particlesEnabled = true;
  23966. // Sprites
  23967. /**
  23968. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23969. */
  23970. _this.spritesEnabled = true;
  23971. /**
  23972. * All of the sprite managers added to this scene
  23973. * @see http://doc.babylonjs.com/babylon101/sprites
  23974. */
  23975. _this.spriteManagers = new Array();
  23976. // Skeletons
  23977. _this._skeletonsEnabled = true;
  23978. // Lens flares
  23979. /**
  23980. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23981. */
  23982. _this.lensFlaresEnabled = true;
  23983. // Collisions
  23984. /**
  23985. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23986. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23987. */
  23988. _this.collisionsEnabled = true;
  23989. /**
  23990. * Defines the gravity applied to this scene (used only for collisions)
  23991. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23992. */
  23993. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23994. // Postprocesses
  23995. /**
  23996. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23997. */
  23998. _this.postProcessesEnabled = true;
  23999. /**
  24000. * The list of postprocesses added to the scene
  24001. */
  24002. _this.postProcesses = new Array();
  24003. // Customs render targets
  24004. /**
  24005. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24006. */
  24007. _this.renderTargetsEnabled = true;
  24008. /**
  24009. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24010. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24011. */
  24012. _this.dumpNextRenderTargets = false;
  24013. /**
  24014. * The list of user defined render targets added to the scene
  24015. */
  24016. _this.customRenderTargets = new Array();
  24017. /**
  24018. * Gets the list of meshes imported to the scene through SceneLoader
  24019. */
  24020. _this.importedMeshesFiles = new Array();
  24021. // Probes
  24022. /**
  24023. * Gets or sets a boolean indicating if probes are enabled on this scene
  24024. */
  24025. _this.probesEnabled = true;
  24026. /**
  24027. * The list of reflection probes added to the scene
  24028. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24029. */
  24030. _this.reflectionProbes = new Array();
  24031. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24032. // Procedural textures
  24033. /**
  24034. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24035. */
  24036. _this.proceduralTexturesEnabled = true;
  24037. /**
  24038. * The list of procedural textures added to the scene
  24039. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24040. */
  24041. _this.proceduralTextures = new Array();
  24042. /**
  24043. * The list of sound tracks added to the scene
  24044. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24045. */
  24046. _this.soundTracks = new Array();
  24047. _this._audioEnabled = true;
  24048. _this._headphone = false;
  24049. // Performance counters
  24050. _this._totalVertices = new BABYLON.PerfCounter();
  24051. /** @hidden */
  24052. _this._activeIndices = new BABYLON.PerfCounter();
  24053. /** @hidden */
  24054. _this._activeParticles = new BABYLON.PerfCounter();
  24055. /** @hidden */
  24056. _this._activeBones = new BABYLON.PerfCounter();
  24057. _this._animationTime = 0;
  24058. /**
  24059. * Gets or sets a general scale for animation speed
  24060. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24061. */
  24062. _this.animationTimeScale = 1;
  24063. _this._renderId = 0;
  24064. _this._executeWhenReadyTimeoutId = -1;
  24065. _this._intermediateRendering = false;
  24066. _this._viewUpdateFlag = -1;
  24067. _this._projectionUpdateFlag = -1;
  24068. _this._alternateViewUpdateFlag = -1;
  24069. _this._alternateProjectionUpdateFlag = -1;
  24070. /** @hidden */
  24071. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24072. _this._activeRequests = new Array();
  24073. _this._pendingData = new Array();
  24074. _this._isDisposed = false;
  24075. /**
  24076. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24077. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24078. */
  24079. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24080. _this._activeMeshes = new BABYLON.SmartArray(256);
  24081. _this._processedMaterials = new BABYLON.SmartArray(256);
  24082. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24083. /** @hidden */
  24084. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24085. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24086. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24087. /** @hidden */
  24088. _this._activeAnimatables = new Array();
  24089. _this._transformMatrix = BABYLON.Matrix.Zero();
  24090. _this._useAlternateCameraConfiguration = false;
  24091. _this._alternateRendering = false;
  24092. /**
  24093. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24094. * This is useful if there are more lights that the maximum simulteanous authorized
  24095. */
  24096. _this.requireLightSorting = false;
  24097. _this._depthRenderer = {};
  24098. /**
  24099. * Backing store of defined scene components.
  24100. */
  24101. _this._components = [];
  24102. /**
  24103. * Backing store of defined scene components.
  24104. */
  24105. _this._serializableComponents = [];
  24106. /**
  24107. * List of components to register on the next registration step.
  24108. */
  24109. _this._transientComponents = [];
  24110. /**
  24111. * Defines the actions happening before camera updates.
  24112. */
  24113. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24114. /**
  24115. * Defines the actions happening during the per mesh ready checks.
  24116. */
  24117. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24118. /**
  24119. * Defines the actions happening before evaluate active mesh checks.
  24120. */
  24121. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24122. /**
  24123. * Defines the actions happening during the evaluate sub mesh checks.
  24124. */
  24125. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24126. /**
  24127. * Defines the actions happening during the active mesh stage.
  24128. */
  24129. _this._activeMeshStage = BABYLON.Stage.Create();
  24130. /**
  24131. * Defines the actions happening during the per camera render target step.
  24132. */
  24133. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24134. /**
  24135. * Defines the actions happening just before the active camera is drawing.
  24136. */
  24137. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24138. /**
  24139. * Defines the actions happening just before a rendering group is drawing.
  24140. */
  24141. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24142. /**
  24143. * Defines the actions happening just after a rendering group has been drawn.
  24144. */
  24145. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24146. /**
  24147. * Defines the actions happening just after the active camera has been drawn.
  24148. */
  24149. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24150. _this._activeMeshesFrozen = false;
  24151. /** @hidden */
  24152. _this._allowPostProcessClear = true;
  24153. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24154. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24155. _this._engine.scenes.push(_this);
  24156. _this._uid = null;
  24157. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24158. if (BABYLON.PostProcessManager) {
  24159. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24160. }
  24161. if (BABYLON.OutlineRenderer) {
  24162. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24163. }
  24164. if (BABYLON.Tools.IsWindowObjectExist()) {
  24165. _this.attachControl();
  24166. }
  24167. //simplification queue
  24168. if (BABYLON.SimplificationQueue) {
  24169. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24170. }
  24171. //collision coordinator initialization. For now legacy per default.
  24172. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24173. // Uniform Buffer
  24174. _this._createUbo();
  24175. // Default Image processing definition
  24176. if (BABYLON.ImageProcessingConfiguration) {
  24177. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24178. }
  24179. return _this;
  24180. }
  24181. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24182. /** The fog is deactivated */
  24183. get: function () {
  24184. return Scene._FOGMODE_NONE;
  24185. },
  24186. enumerable: true,
  24187. configurable: true
  24188. });
  24189. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24190. /** The fog density is following an exponential function */
  24191. get: function () {
  24192. return Scene._FOGMODE_EXP;
  24193. },
  24194. enumerable: true,
  24195. configurable: true
  24196. });
  24197. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24198. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24199. get: function () {
  24200. return Scene._FOGMODE_EXP2;
  24201. },
  24202. enumerable: true,
  24203. configurable: true
  24204. });
  24205. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24206. /** The fog density is following a linear function. */
  24207. get: function () {
  24208. return Scene._FOGMODE_LINEAR;
  24209. },
  24210. enumerable: true,
  24211. configurable: true
  24212. });
  24213. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24214. /**
  24215. * Texture used in all pbr material as the reflection texture.
  24216. * As in the majority of the scene they are the same (exception for multi room and so on),
  24217. * this is easier to reference from here than from all the materials.
  24218. */
  24219. get: function () {
  24220. return this._environmentTexture;
  24221. },
  24222. /**
  24223. * Texture used in all pbr material as the reflection texture.
  24224. * As in the majority of the scene they are the same (exception for multi room and so on),
  24225. * this is easier to set here than in all the materials.
  24226. */
  24227. set: function (value) {
  24228. if (this._environmentTexture === value) {
  24229. return;
  24230. }
  24231. this._environmentTexture = value;
  24232. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24233. },
  24234. enumerable: true,
  24235. configurable: true
  24236. });
  24237. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24238. /**
  24239. * Default image processing configuration used either in the rendering
  24240. * Forward main pass or through the imageProcessingPostProcess if present.
  24241. * As in the majority of the scene they are the same (exception for multi camera),
  24242. * this is easier to reference from here than from all the materials and post process.
  24243. *
  24244. * No setter as we it is a shared configuration, you can set the values instead.
  24245. */
  24246. get: function () {
  24247. return this._imageProcessingConfiguration;
  24248. },
  24249. enumerable: true,
  24250. configurable: true
  24251. });
  24252. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24253. get: function () {
  24254. return this._forceWireframe;
  24255. },
  24256. /**
  24257. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24258. */
  24259. set: function (value) {
  24260. if (this._forceWireframe === value) {
  24261. return;
  24262. }
  24263. this._forceWireframe = value;
  24264. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24265. },
  24266. enumerable: true,
  24267. configurable: true
  24268. });
  24269. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24270. get: function () {
  24271. return this._forcePointsCloud;
  24272. },
  24273. /**
  24274. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24275. */
  24276. set: function (value) {
  24277. if (this._forcePointsCloud === value) {
  24278. return;
  24279. }
  24280. this._forcePointsCloud = value;
  24281. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24287. /**
  24288. * Gets or sets the animation properties override
  24289. */
  24290. get: function () {
  24291. return this._animationPropertiesOverride;
  24292. },
  24293. set: function (value) {
  24294. this._animationPropertiesOverride = value;
  24295. },
  24296. enumerable: true,
  24297. configurable: true
  24298. });
  24299. Object.defineProperty(Scene.prototype, "onDispose", {
  24300. /** Sets a function to be executed when this scene is disposed. */
  24301. set: function (callback) {
  24302. if (this._onDisposeObserver) {
  24303. this.onDisposeObservable.remove(this._onDisposeObserver);
  24304. }
  24305. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24306. },
  24307. enumerable: true,
  24308. configurable: true
  24309. });
  24310. Object.defineProperty(Scene.prototype, "beforeRender", {
  24311. /** Sets a function to be executed before rendering this scene */
  24312. set: function (callback) {
  24313. if (this._onBeforeRenderObserver) {
  24314. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24315. }
  24316. if (callback) {
  24317. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24318. }
  24319. },
  24320. enumerable: true,
  24321. configurable: true
  24322. });
  24323. Object.defineProperty(Scene.prototype, "afterRender", {
  24324. /** Sets a function to be executed after rendering this scene */
  24325. set: function (callback) {
  24326. if (this._onAfterRenderObserver) {
  24327. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24328. }
  24329. if (callback) {
  24330. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24331. }
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24337. /** Sets a function to be executed before rendering a camera*/
  24338. set: function (callback) {
  24339. if (this._onBeforeCameraRenderObserver) {
  24340. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24341. }
  24342. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24343. },
  24344. enumerable: true,
  24345. configurable: true
  24346. });
  24347. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24348. /** Sets a function to be executed after rendering a camera*/
  24349. set: function (callback) {
  24350. if (this._onAfterCameraRenderObserver) {
  24351. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24352. }
  24353. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24354. },
  24355. enumerable: true,
  24356. configurable: true
  24357. });
  24358. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24359. /**
  24360. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24361. */
  24362. get: function () {
  24363. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24369. get: function () {
  24370. return this._useRightHandedSystem;
  24371. },
  24372. /**
  24373. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24374. */
  24375. set: function (value) {
  24376. if (this._useRightHandedSystem === value) {
  24377. return;
  24378. }
  24379. this._useRightHandedSystem = value;
  24380. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. /**
  24386. * Sets the step Id used by deterministic lock step
  24387. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24388. * @param newStepId defines the step Id
  24389. */
  24390. Scene.prototype.setStepId = function (newStepId) {
  24391. this._currentStepId = newStepId;
  24392. };
  24393. ;
  24394. /**
  24395. * Gets the step Id used by deterministic lock step
  24396. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24397. * @returns the step Id
  24398. */
  24399. Scene.prototype.getStepId = function () {
  24400. return this._currentStepId;
  24401. };
  24402. ;
  24403. /**
  24404. * Gets the internal step used by deterministic lock step
  24405. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24406. * @returns the internal step
  24407. */
  24408. Scene.prototype.getInternalStep = function () {
  24409. return this._currentInternalStep;
  24410. };
  24411. ;
  24412. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24413. get: function () {
  24414. return this._fogEnabled;
  24415. },
  24416. /**
  24417. * Gets or sets a boolean indicating if fog is enabled on this scene
  24418. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24419. */
  24420. set: function (value) {
  24421. if (this._fogEnabled === value) {
  24422. return;
  24423. }
  24424. this._fogEnabled = value;
  24425. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Scene.prototype, "fogMode", {
  24431. get: function () {
  24432. return this._fogMode;
  24433. },
  24434. /**
  24435. * Gets or sets the fog mode to use
  24436. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24437. */
  24438. set: function (value) {
  24439. if (this._fogMode === value) {
  24440. return;
  24441. }
  24442. this._fogMode = value;
  24443. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24449. get: function () {
  24450. return this._shadowsEnabled;
  24451. },
  24452. /**
  24453. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24454. */
  24455. set: function (value) {
  24456. if (this._shadowsEnabled === value) {
  24457. return;
  24458. }
  24459. this._shadowsEnabled = value;
  24460. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24461. },
  24462. enumerable: true,
  24463. configurable: true
  24464. });
  24465. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24466. get: function () {
  24467. return this._lightsEnabled;
  24468. },
  24469. /**
  24470. * Gets or sets a boolean indicating if lights are enabled on this scene
  24471. */
  24472. set: function (value) {
  24473. if (this._lightsEnabled === value) {
  24474. return;
  24475. }
  24476. this._lightsEnabled = value;
  24477. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24483. /** The default material used on meshes when no material is affected */
  24484. get: function () {
  24485. if (!this._defaultMaterial) {
  24486. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24487. }
  24488. return this._defaultMaterial;
  24489. },
  24490. /** The default material used on meshes when no material is affected */
  24491. set: function (value) {
  24492. this._defaultMaterial = value;
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24498. get: function () {
  24499. return this._texturesEnabled;
  24500. },
  24501. /**
  24502. * Gets or sets a boolean indicating if textures are enabled on this scene
  24503. */
  24504. set: function (value) {
  24505. if (this._texturesEnabled === value) {
  24506. return;
  24507. }
  24508. this._texturesEnabled = value;
  24509. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24510. },
  24511. enumerable: true,
  24512. configurable: true
  24513. });
  24514. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24515. get: function () {
  24516. return this._skeletonsEnabled;
  24517. },
  24518. /**
  24519. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24520. */
  24521. set: function (value) {
  24522. if (this._skeletonsEnabled === value) {
  24523. return;
  24524. }
  24525. this._skeletonsEnabled = value;
  24526. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24532. /**
  24533. * Gets the postprocess render pipeline manager
  24534. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24535. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24536. */
  24537. get: function () {
  24538. if (!this._postProcessRenderPipelineManager) {
  24539. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24540. }
  24541. return this._postProcessRenderPipelineManager;
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24547. /**
  24548. * Gets the main soundtrack associated with the scene
  24549. */
  24550. get: function () {
  24551. if (!this._mainSoundTrack) {
  24552. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24553. }
  24554. return this._mainSoundTrack;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24560. /** @hidden */
  24561. get: function () {
  24562. return this._alternateRendering;
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24568. /**
  24569. * Gets the list of frustum planes (built from the active camera)
  24570. */
  24571. get: function () {
  24572. return this._frustumPlanes;
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24578. /**
  24579. * Gets the current geometry buffer associated to the scene.
  24580. */
  24581. get: function () {
  24582. return this._geometryBufferRenderer;
  24583. },
  24584. /**
  24585. * Sets the current geometry buffer for the scene.
  24586. */
  24587. set: function (geometryBufferRenderer) {
  24588. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24589. this._geometryBufferRenderer = geometryBufferRenderer;
  24590. }
  24591. },
  24592. enumerable: true,
  24593. configurable: true
  24594. });
  24595. /**
  24596. * Registers the transient components if needed.
  24597. */
  24598. Scene.prototype._registerTransientComponents = function () {
  24599. // Register components that have been associated lately to the scene.
  24600. if (this._transientComponents.length > 0) {
  24601. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24602. var component = _a[_i];
  24603. component.register();
  24604. }
  24605. this._transientComponents = [];
  24606. }
  24607. };
  24608. /**
  24609. * Add a component to the scene.
  24610. * Note that the ccomponent could be registered on th next frame if this is called after
  24611. * the register component stage.
  24612. * @param component Defines the component to add to the scene
  24613. */
  24614. Scene.prototype._addComponent = function (component) {
  24615. this._components.push(component);
  24616. this._transientComponents.push(component);
  24617. var serializableComponent = component;
  24618. if (serializableComponent.addFromContainer) {
  24619. this._serializableComponents.push(serializableComponent);
  24620. }
  24621. };
  24622. /**
  24623. * Gets a component from the scene.
  24624. * @param name defines the name of the component to retrieve
  24625. * @returns the component or null if not present
  24626. */
  24627. Scene.prototype._getComponent = function (name) {
  24628. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24629. var component = _a[_i];
  24630. if (component.name === name) {
  24631. return component;
  24632. }
  24633. }
  24634. return null;
  24635. };
  24636. Object.defineProperty(Scene.prototype, "debugLayer", {
  24637. /**
  24638. * Gets the debug layer (aka Inspector) associated with the scene
  24639. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24640. */
  24641. get: function () {
  24642. if (!this._debugLayer) {
  24643. this._debugLayer = new BABYLON.DebugLayer(this);
  24644. }
  24645. return this._debugLayer;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24651. /**
  24652. * Gets a boolean indicating if collisions are processed on a web worker
  24653. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24654. */
  24655. get: function () {
  24656. return this._workerCollisions;
  24657. },
  24658. set: function (enabled) {
  24659. if (!BABYLON.CollisionCoordinatorLegacy) {
  24660. return;
  24661. }
  24662. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24663. this._workerCollisions = enabled;
  24664. if (this.collisionCoordinator) {
  24665. this.collisionCoordinator.destroy();
  24666. }
  24667. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24668. this.collisionCoordinator.init(this);
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24674. /**
  24675. * Gets the octree used to boost mesh selection (picking)
  24676. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24677. */
  24678. get: function () {
  24679. return this._selectionOctree;
  24680. },
  24681. enumerable: true,
  24682. configurable: true
  24683. });
  24684. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24685. /**
  24686. * Gets the mesh that is currently under the pointer
  24687. */
  24688. get: function () {
  24689. return this._pointerOverMesh;
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. Object.defineProperty(Scene.prototype, "pointerX", {
  24695. /**
  24696. * Gets the current on-screen X position of the pointer
  24697. */
  24698. get: function () {
  24699. return this._pointerX;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. Object.defineProperty(Scene.prototype, "pointerY", {
  24705. /**
  24706. * Gets the current on-screen Y position of the pointer
  24707. */
  24708. get: function () {
  24709. return this._pointerY;
  24710. },
  24711. enumerable: true,
  24712. configurable: true
  24713. });
  24714. /**
  24715. * Gets the cached material (ie. the latest rendered one)
  24716. * @returns the cached material
  24717. */
  24718. Scene.prototype.getCachedMaterial = function () {
  24719. return this._cachedMaterial;
  24720. };
  24721. /**
  24722. * Gets the cached effect (ie. the latest rendered one)
  24723. * @returns the cached effect
  24724. */
  24725. Scene.prototype.getCachedEffect = function () {
  24726. return this._cachedEffect;
  24727. };
  24728. /**
  24729. * Gets the cached visibility state (ie. the latest rendered one)
  24730. * @returns the cached visibility state
  24731. */
  24732. Scene.prototype.getCachedVisibility = function () {
  24733. return this._cachedVisibility;
  24734. };
  24735. /**
  24736. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24737. * @param material defines the current material
  24738. * @param effect defines the current effect
  24739. * @param visibility defines the current visibility state
  24740. * @returns true if one parameter is not cached
  24741. */
  24742. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24743. if (visibility === void 0) { visibility = 1; }
  24744. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24745. };
  24746. /**
  24747. * Gets the outline renderer associated with the scene
  24748. * @returns a OutlineRenderer
  24749. */
  24750. Scene.prototype.getOutlineRenderer = function () {
  24751. return this._outlineRenderer;
  24752. };
  24753. /**
  24754. * Gets the engine associated with the scene
  24755. * @returns an Engine
  24756. */
  24757. Scene.prototype.getEngine = function () {
  24758. return this._engine;
  24759. };
  24760. /**
  24761. * Gets the total number of vertices rendered per frame
  24762. * @returns the total number of vertices rendered per frame
  24763. */
  24764. Scene.prototype.getTotalVertices = function () {
  24765. return this._totalVertices.current;
  24766. };
  24767. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24768. /**
  24769. * Gets the performance counter for total vertices
  24770. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24771. */
  24772. get: function () {
  24773. return this._totalVertices;
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. /**
  24779. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24780. * @returns the total number of active indices rendered per frame
  24781. */
  24782. Scene.prototype.getActiveIndices = function () {
  24783. return this._activeIndices.current;
  24784. };
  24785. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24786. /**
  24787. * Gets the performance counter for active indices
  24788. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24789. */
  24790. get: function () {
  24791. return this._activeIndices;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. /**
  24797. * Gets the total number of active particles rendered per frame
  24798. * @returns the total number of active particles rendered per frame
  24799. */
  24800. Scene.prototype.getActiveParticles = function () {
  24801. return this._activeParticles.current;
  24802. };
  24803. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24804. /**
  24805. * Gets the performance counter for active particles
  24806. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24807. */
  24808. get: function () {
  24809. return this._activeParticles;
  24810. },
  24811. enumerable: true,
  24812. configurable: true
  24813. });
  24814. /**
  24815. * Gets the total number of active bones rendered per frame
  24816. * @returns the total number of active bones rendered per frame
  24817. */
  24818. Scene.prototype.getActiveBones = function () {
  24819. return this._activeBones.current;
  24820. };
  24821. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24822. /**
  24823. * Gets the performance counter for active bones
  24824. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24825. */
  24826. get: function () {
  24827. return this._activeBones;
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. /** @hidden */
  24833. Scene.prototype.getInterFramePerfCounter = function () {
  24834. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24835. return 0;
  24836. };
  24837. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24838. /** @hidden */
  24839. get: function () {
  24840. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24841. return null;
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. /** @hidden */
  24847. Scene.prototype.getLastFrameDuration = function () {
  24848. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24849. return 0;
  24850. };
  24851. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24852. /** @hidden */
  24853. get: function () {
  24854. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24855. return null;
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. /** @hidden */
  24861. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24862. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24863. return 0;
  24864. };
  24865. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24866. /** @hidden */
  24867. get: function () {
  24868. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24869. return null;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. /**
  24875. * Gets the array of active meshes
  24876. * @returns an array of AbstractMesh
  24877. */
  24878. Scene.prototype.getActiveMeshes = function () {
  24879. return this._activeMeshes;
  24880. };
  24881. /** @hidden */
  24882. Scene.prototype.getRenderTargetsDuration = function () {
  24883. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24884. return 0;
  24885. };
  24886. /** @hidden */
  24887. Scene.prototype.getRenderDuration = function () {
  24888. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24889. return 0;
  24890. };
  24891. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24892. /** @hidden */
  24893. get: function () {
  24894. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24895. return null;
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. /** @hidden */
  24901. Scene.prototype.getParticlesDuration = function () {
  24902. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24903. return 0;
  24904. };
  24905. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24906. /** @hidden */
  24907. get: function () {
  24908. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24909. return null;
  24910. },
  24911. enumerable: true,
  24912. configurable: true
  24913. });
  24914. /** @hidden */
  24915. Scene.prototype.getSpritesDuration = function () {
  24916. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24917. return 0;
  24918. };
  24919. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24920. /** @hidden */
  24921. get: function () {
  24922. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24923. return null;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. /**
  24929. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24930. * @returns a number
  24931. */
  24932. Scene.prototype.getAnimationRatio = function () {
  24933. return this._animationRatio;
  24934. };
  24935. /**
  24936. * Gets an unique Id for the current frame
  24937. * @returns a number
  24938. */
  24939. Scene.prototype.getRenderId = function () {
  24940. return this._renderId;
  24941. };
  24942. /** Call this function if you want to manually increment the render Id*/
  24943. Scene.prototype.incrementRenderId = function () {
  24944. this._renderId++;
  24945. };
  24946. Scene.prototype._updatePointerPosition = function (evt) {
  24947. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24948. if (!canvasRect) {
  24949. return;
  24950. }
  24951. this._pointerX = evt.clientX - canvasRect.left;
  24952. this._pointerY = evt.clientY - canvasRect.top;
  24953. this._unTranslatedPointerX = this._pointerX;
  24954. this._unTranslatedPointerY = this._pointerY;
  24955. };
  24956. Scene.prototype._createUbo = function () {
  24957. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24958. this._sceneUbo.addUniform("viewProjection", 16);
  24959. this._sceneUbo.addUniform("view", 16);
  24960. };
  24961. Scene.prototype._createAlternateUbo = function () {
  24962. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24963. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24964. this._alternateSceneUbo.addUniform("view", 16);
  24965. };
  24966. // Pointers handling
  24967. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24968. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24969. if (result) {
  24970. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24971. }
  24972. return result;
  24973. };
  24974. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24975. if (pointerInfo.pickInfo) {
  24976. if (!pointerInfo.pickInfo.ray) {
  24977. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24978. }
  24979. }
  24980. };
  24981. /**
  24982. * Use this method to simulate a pointer move on a mesh
  24983. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24984. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24985. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24986. * @returns the current scene
  24987. */
  24988. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24989. var evt = new PointerEvent("pointermove", pointerEventInit);
  24990. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24991. return this;
  24992. }
  24993. return this._processPointerMove(pickResult, evt);
  24994. };
  24995. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24996. var canvas = this._engine.getRenderingCanvas();
  24997. if (!canvas) {
  24998. return this;
  24999. }
  25000. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25001. this.setPointerOverSprite(null);
  25002. this.setPointerOverMesh(pickResult.pickedMesh);
  25003. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25004. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25005. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25006. }
  25007. else {
  25008. canvas.style.cursor = this.hoverCursor;
  25009. }
  25010. }
  25011. else {
  25012. canvas.style.cursor = this.defaultCursor;
  25013. }
  25014. }
  25015. else {
  25016. this.setPointerOverMesh(null);
  25017. // Sprites
  25018. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25019. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25020. this.setPointerOverSprite(pickResult.pickedSprite);
  25021. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25022. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25023. }
  25024. else {
  25025. canvas.style.cursor = this.hoverCursor;
  25026. }
  25027. }
  25028. else {
  25029. this.setPointerOverSprite(null);
  25030. // Restore pointer
  25031. canvas.style.cursor = this.defaultCursor;
  25032. }
  25033. }
  25034. if (pickResult) {
  25035. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25036. if (this.onPointerMove) {
  25037. this.onPointerMove(evt, pickResult, type);
  25038. }
  25039. if (this.onPointerObservable.hasObservers()) {
  25040. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25041. this._setRayOnPointerInfo(pi);
  25042. this.onPointerObservable.notifyObservers(pi, type);
  25043. }
  25044. }
  25045. return this;
  25046. };
  25047. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25048. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25049. if (pickResult) {
  25050. pi.ray = pickResult.ray;
  25051. }
  25052. this.onPrePointerObservable.notifyObservers(pi, type);
  25053. if (pi.skipOnPointerObservable) {
  25054. return true;
  25055. }
  25056. else {
  25057. return false;
  25058. }
  25059. };
  25060. /**
  25061. * Use this method to simulate a pointer down on a mesh
  25062. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25063. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25064. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25065. * @returns the current scene
  25066. */
  25067. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25068. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25069. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25070. return this;
  25071. }
  25072. return this._processPointerDown(pickResult, evt);
  25073. };
  25074. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25075. var _this = this;
  25076. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25077. this._pickedDownMesh = pickResult.pickedMesh;
  25078. var actionManager = pickResult.pickedMesh.actionManager;
  25079. if (actionManager) {
  25080. if (actionManager.hasPickTriggers) {
  25081. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25082. switch (evt.button) {
  25083. case 0:
  25084. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25085. break;
  25086. case 1:
  25087. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25088. break;
  25089. case 2:
  25090. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25091. break;
  25092. }
  25093. }
  25094. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25095. window.setTimeout(function () {
  25096. 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);
  25097. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25098. if (_this._totalPointersPressed !== 0 &&
  25099. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25100. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25101. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25102. _this._startingPointerTime = 0;
  25103. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25104. }
  25105. }
  25106. }, Scene.LongPressDelay);
  25107. }
  25108. }
  25109. }
  25110. if (pickResult) {
  25111. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25112. if (this.onPointerDown) {
  25113. this.onPointerDown(evt, pickResult, type);
  25114. }
  25115. if (this.onPointerObservable.hasObservers()) {
  25116. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25117. this._setRayOnPointerInfo(pi);
  25118. this.onPointerObservable.notifyObservers(pi, type);
  25119. }
  25120. }
  25121. return this;
  25122. };
  25123. /**
  25124. * Use this method to simulate a pointer up on a mesh
  25125. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25126. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25127. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25128. * @returns the current scene
  25129. */
  25130. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25131. var evt = new PointerEvent("pointerup", pointerEventInit);
  25132. var clickInfo = new ClickInfo();
  25133. clickInfo.singleClick = true;
  25134. clickInfo.ignore = true;
  25135. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25136. return this;
  25137. }
  25138. return this._processPointerUp(pickResult, evt, clickInfo);
  25139. };
  25140. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25141. if (pickResult && pickResult && pickResult.pickedMesh) {
  25142. this._pickedUpMesh = pickResult.pickedMesh;
  25143. if (this._pickedDownMesh === this._pickedUpMesh) {
  25144. if (this.onPointerPick) {
  25145. this.onPointerPick(evt, pickResult);
  25146. }
  25147. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25148. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25149. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25150. this._setRayOnPointerInfo(pi);
  25151. this.onPointerObservable.notifyObservers(pi, type_1);
  25152. }
  25153. }
  25154. if (pickResult.pickedMesh.actionManager) {
  25155. if (clickInfo.ignore) {
  25156. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25157. }
  25158. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25159. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25160. }
  25161. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25162. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25163. }
  25164. }
  25165. }
  25166. if (this._pickedDownMesh &&
  25167. this._pickedDownMesh.actionManager &&
  25168. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25169. this._pickedDownMesh !== this._pickedUpMesh) {
  25170. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25171. }
  25172. var type = BABYLON.PointerEventTypes.POINTERUP;
  25173. if (this.onPointerObservable.hasObservers()) {
  25174. if (!clickInfo.ignore) {
  25175. if (!clickInfo.hasSwiped) {
  25176. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25177. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25178. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25179. this._setRayOnPointerInfo(pi);
  25180. this.onPointerObservable.notifyObservers(pi, type_2);
  25181. }
  25182. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25183. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25184. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25185. this._setRayOnPointerInfo(pi);
  25186. this.onPointerObservable.notifyObservers(pi, type_3);
  25187. }
  25188. }
  25189. }
  25190. else {
  25191. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25192. this._setRayOnPointerInfo(pi);
  25193. this.onPointerObservable.notifyObservers(pi, type);
  25194. }
  25195. }
  25196. if (this.onPointerUp) {
  25197. this.onPointerUp(evt, pickResult, type);
  25198. }
  25199. return this;
  25200. };
  25201. /**
  25202. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25203. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25204. * @returns true if the pointer was captured
  25205. */
  25206. Scene.prototype.isPointerCaptured = function (pointerId) {
  25207. if (pointerId === void 0) { pointerId = 0; }
  25208. return this._pointerCaptures[pointerId];
  25209. };
  25210. /**
  25211. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25212. * @param attachUp defines if you want to attach events to pointerup
  25213. * @param attachDown defines if you want to attach events to pointerdown
  25214. * @param attachMove defines if you want to attach events to pointermove
  25215. */
  25216. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25217. var _this = this;
  25218. if (attachUp === void 0) { attachUp = true; }
  25219. if (attachDown === void 0) { attachDown = true; }
  25220. if (attachMove === void 0) { attachMove = true; }
  25221. this._initActionManager = function (act, clickInfo) {
  25222. if (!_this._meshPickProceed) {
  25223. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25224. _this._currentPickResult = pickResult;
  25225. if (pickResult) {
  25226. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25227. }
  25228. _this._meshPickProceed = true;
  25229. }
  25230. return act;
  25231. };
  25232. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25233. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25234. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25235. btn !== _this._previousButtonPressed) {
  25236. _this._doubleClickOccured = false;
  25237. clickInfo.singleClick = true;
  25238. clickInfo.ignore = false;
  25239. cb(clickInfo, _this._currentPickResult);
  25240. }
  25241. };
  25242. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25243. var clickInfo = new ClickInfo();
  25244. _this._currentPickResult = null;
  25245. var act = null;
  25246. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25247. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25248. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25249. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25250. act = _this._initActionManager(act, clickInfo);
  25251. if (act)
  25252. checkPicking = act.hasPickTriggers;
  25253. }
  25254. if (checkPicking) {
  25255. var btn = evt.button;
  25256. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25257. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25258. if (!clickInfo.hasSwiped) {
  25259. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25260. if (!checkSingleClickImmediately) {
  25261. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25262. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25263. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25264. act = _this._initActionManager(act, clickInfo);
  25265. if (act)
  25266. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25267. }
  25268. }
  25269. if (checkSingleClickImmediately) {
  25270. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25271. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25272. btn !== _this._previousButtonPressed) {
  25273. clickInfo.singleClick = true;
  25274. cb(clickInfo, _this._currentPickResult);
  25275. }
  25276. }
  25277. // at least one double click is required to be check and exclusive double click is enabled
  25278. else {
  25279. // wait that no double click has been raised during the double click delay
  25280. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25281. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25282. }
  25283. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25284. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25285. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25286. act = _this._initActionManager(act, clickInfo);
  25287. if (act)
  25288. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25289. }
  25290. if (checkDoubleClick) {
  25291. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25292. if (btn === _this._previousButtonPressed &&
  25293. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25294. !_this._doubleClickOccured) {
  25295. // pointer has not moved for 2 clicks, it's a double click
  25296. if (!clickInfo.hasSwiped &&
  25297. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25298. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25299. _this._previousStartingPointerTime = 0;
  25300. _this._doubleClickOccured = true;
  25301. clickInfo.doubleClick = true;
  25302. clickInfo.ignore = false;
  25303. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25304. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25305. }
  25306. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25307. cb(clickInfo, _this._currentPickResult);
  25308. }
  25309. // if the two successive clicks are too far, it's just two simple clicks
  25310. else {
  25311. _this._doubleClickOccured = false;
  25312. _this._previousStartingPointerTime = _this._startingPointerTime;
  25313. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25314. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25315. _this._previousButtonPressed = btn;
  25316. if (Scene.ExclusiveDoubleClickMode) {
  25317. if (_this._previousDelayedSimpleClickTimeout) {
  25318. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25319. }
  25320. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25321. cb(clickInfo, _this._previousPickResult);
  25322. }
  25323. else {
  25324. cb(clickInfo, _this._currentPickResult);
  25325. }
  25326. }
  25327. }
  25328. // just the first click of the double has been raised
  25329. else {
  25330. _this._doubleClickOccured = false;
  25331. _this._previousStartingPointerTime = _this._startingPointerTime;
  25332. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25333. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25334. _this._previousButtonPressed = btn;
  25335. }
  25336. }
  25337. }
  25338. }
  25339. clickInfo.ignore = true;
  25340. cb(clickInfo, _this._currentPickResult);
  25341. };
  25342. this._spritePredicate = function (sprite) {
  25343. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25344. };
  25345. this._onPointerMove = function (evt) {
  25346. _this._updatePointerPosition(evt);
  25347. // PreObservable support
  25348. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25349. return;
  25350. }
  25351. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25352. return;
  25353. }
  25354. if (!_this.pointerMovePredicate) {
  25355. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25356. }
  25357. // Meshes
  25358. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25359. _this._processPointerMove(pickResult, evt);
  25360. };
  25361. this._onPointerDown = function (evt) {
  25362. _this._totalPointersPressed++;
  25363. _this._pickedDownMesh = null;
  25364. _this._meshPickProceed = false;
  25365. _this._updatePointerPosition(evt);
  25366. if (_this.preventDefaultOnPointerDown && canvas) {
  25367. evt.preventDefault();
  25368. canvas.focus();
  25369. }
  25370. // PreObservable support
  25371. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25372. return;
  25373. }
  25374. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25375. return;
  25376. }
  25377. _this._pointerCaptures[evt.pointerId] = true;
  25378. _this._startingPointerPosition.x = _this._pointerX;
  25379. _this._startingPointerPosition.y = _this._pointerY;
  25380. _this._startingPointerTime = Date.now();
  25381. if (!_this.pointerDownPredicate) {
  25382. _this.pointerDownPredicate = function (mesh) {
  25383. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25384. };
  25385. }
  25386. // Meshes
  25387. _this._pickedDownMesh = null;
  25388. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25389. _this._processPointerDown(pickResult, evt);
  25390. // Sprites
  25391. _this._pickedDownSprite = null;
  25392. if (_this.spriteManagers.length > 0) {
  25393. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25394. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25395. if (pickResult.pickedSprite.actionManager) {
  25396. _this._pickedDownSprite = pickResult.pickedSprite;
  25397. switch (evt.button) {
  25398. case 0:
  25399. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25400. break;
  25401. case 1:
  25402. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25403. break;
  25404. case 2:
  25405. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25406. break;
  25407. }
  25408. if (pickResult.pickedSprite.actionManager) {
  25409. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25410. }
  25411. }
  25412. }
  25413. }
  25414. };
  25415. this._onPointerUp = function (evt) {
  25416. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25417. return; // So we need to test it the pointer down was pressed before.
  25418. }
  25419. _this._totalPointersPressed--;
  25420. _this._pickedUpMesh = null;
  25421. _this._meshPickProceed = false;
  25422. _this._updatePointerPosition(evt);
  25423. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25424. // PreObservable support
  25425. if (_this.onPrePointerObservable.hasObservers()) {
  25426. if (!clickInfo.ignore) {
  25427. if (!clickInfo.hasSwiped) {
  25428. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25429. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25430. return;
  25431. }
  25432. }
  25433. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25434. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25435. return;
  25436. }
  25437. }
  25438. }
  25439. }
  25440. else {
  25441. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25442. return;
  25443. }
  25444. }
  25445. }
  25446. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25447. return;
  25448. }
  25449. _this._pointerCaptures[evt.pointerId] = false;
  25450. if (!_this.pointerUpPredicate) {
  25451. _this.pointerUpPredicate = function (mesh) {
  25452. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25453. };
  25454. }
  25455. // Meshes
  25456. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25457. _this._initActionManager(null, clickInfo);
  25458. }
  25459. if (!pickResult) {
  25460. pickResult = _this._currentPickResult;
  25461. }
  25462. _this._processPointerUp(pickResult, evt, clickInfo);
  25463. // Sprites
  25464. if (!clickInfo.ignore) {
  25465. if (_this.spriteManagers.length > 0) {
  25466. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25467. if (spritePickResult) {
  25468. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25469. if (spritePickResult.pickedSprite.actionManager) {
  25470. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25471. if (spritePickResult.pickedSprite.actionManager) {
  25472. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25473. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25474. }
  25475. }
  25476. }
  25477. }
  25478. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25479. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25480. }
  25481. }
  25482. }
  25483. }
  25484. _this._previousPickResult = _this._currentPickResult;
  25485. });
  25486. };
  25487. this._onKeyDown = function (evt) {
  25488. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25489. if (_this.onPreKeyboardObservable.hasObservers()) {
  25490. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25491. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25492. if (pi.skipOnPointerObservable) {
  25493. return;
  25494. }
  25495. }
  25496. if (_this.onKeyboardObservable.hasObservers()) {
  25497. var pi = new BABYLON.KeyboardInfo(type, evt);
  25498. _this.onKeyboardObservable.notifyObservers(pi, type);
  25499. }
  25500. if (_this.actionManager) {
  25501. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25502. }
  25503. };
  25504. this._onKeyUp = function (evt) {
  25505. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25506. if (_this.onPreKeyboardObservable.hasObservers()) {
  25507. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25508. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25509. if (pi.skipOnPointerObservable) {
  25510. return;
  25511. }
  25512. }
  25513. if (_this.onKeyboardObservable.hasObservers()) {
  25514. var pi = new BABYLON.KeyboardInfo(type, evt);
  25515. _this.onKeyboardObservable.notifyObservers(pi, type);
  25516. }
  25517. if (_this.actionManager) {
  25518. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25519. }
  25520. };
  25521. var engine = this.getEngine();
  25522. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25523. if (!canvas) {
  25524. return;
  25525. }
  25526. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25527. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25528. });
  25529. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25530. if (!canvas) {
  25531. return;
  25532. }
  25533. canvas.removeEventListener("keydown", _this._onKeyDown);
  25534. canvas.removeEventListener("keyup", _this._onKeyUp);
  25535. });
  25536. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25537. var canvas = this._engine.getRenderingCanvas();
  25538. if (!canvas) {
  25539. return;
  25540. }
  25541. if (attachMove) {
  25542. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25543. // Wheel
  25544. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25545. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25546. }
  25547. if (attachDown) {
  25548. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25549. }
  25550. if (attachUp) {
  25551. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25552. }
  25553. canvas.tabIndex = 1;
  25554. };
  25555. /** Detaches all event handlers*/
  25556. Scene.prototype.detachControl = function () {
  25557. var engine = this.getEngine();
  25558. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25559. var canvas = engine.getRenderingCanvas();
  25560. if (!canvas) {
  25561. return;
  25562. }
  25563. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25564. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25565. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25566. if (this._onCanvasBlurObserver) {
  25567. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25568. }
  25569. if (this._onCanvasFocusObserver) {
  25570. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25571. }
  25572. // Wheel
  25573. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25574. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25575. // Keyboard
  25576. canvas.removeEventListener("keydown", this._onKeyDown);
  25577. canvas.removeEventListener("keyup", this._onKeyUp);
  25578. // Observables
  25579. this.onKeyboardObservable.clear();
  25580. this.onPreKeyboardObservable.clear();
  25581. this.onPointerObservable.clear();
  25582. this.onPrePointerObservable.clear();
  25583. };
  25584. /**
  25585. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25586. * Delay loaded resources are not taking in account
  25587. * @return true if all required resources are ready
  25588. */
  25589. Scene.prototype.isReady = function () {
  25590. if (this._isDisposed) {
  25591. return false;
  25592. }
  25593. if (this._pendingData.length > 0) {
  25594. return false;
  25595. }
  25596. var index;
  25597. var engine = this.getEngine();
  25598. // Geometries
  25599. for (index = 0; index < this.geometries.length; index++) {
  25600. var geometry = this.geometries[index];
  25601. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25602. return false;
  25603. }
  25604. }
  25605. // Meshes
  25606. for (index = 0; index < this.meshes.length; index++) {
  25607. var mesh = this.meshes[index];
  25608. if (!mesh.isEnabled()) {
  25609. continue;
  25610. }
  25611. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25612. continue;
  25613. }
  25614. if (!mesh.isReady(true)) {
  25615. return false;
  25616. }
  25617. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25618. // Is Ready For Mesh
  25619. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25620. var step = _a[_i];
  25621. if (!step.action(mesh, hardwareInstancedRendering)) {
  25622. return false;
  25623. }
  25624. }
  25625. }
  25626. // Post-processes
  25627. if (this.activeCameras && this.activeCameras.length > 0) {
  25628. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25629. var camera = _c[_b];
  25630. if (!camera.isReady(true)) {
  25631. return false;
  25632. }
  25633. }
  25634. }
  25635. else if (this.activeCamera) {
  25636. if (!this.activeCamera.isReady(true)) {
  25637. return false;
  25638. }
  25639. }
  25640. // Particles
  25641. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25642. var particleSystem = _e[_d];
  25643. if (!particleSystem.isReady()) {
  25644. return false;
  25645. }
  25646. }
  25647. return true;
  25648. };
  25649. /** Resets all cached information relative to material (including effect and visibility) */
  25650. Scene.prototype.resetCachedMaterial = function () {
  25651. this._cachedMaterial = null;
  25652. this._cachedEffect = null;
  25653. this._cachedVisibility = null;
  25654. };
  25655. /**
  25656. * Registers a function to be called before every frame render
  25657. * @param func defines the function to register
  25658. */
  25659. Scene.prototype.registerBeforeRender = function (func) {
  25660. this.onBeforeRenderObservable.add(func);
  25661. };
  25662. /**
  25663. * Unregisters a function called before every frame render
  25664. * @param func defines the function to unregister
  25665. */
  25666. Scene.prototype.unregisterBeforeRender = function (func) {
  25667. this.onBeforeRenderObservable.removeCallback(func);
  25668. };
  25669. /**
  25670. * Registers a function to be called after every frame render
  25671. * @param func defines the function to register
  25672. */
  25673. Scene.prototype.registerAfterRender = function (func) {
  25674. this.onAfterRenderObservable.add(func);
  25675. };
  25676. /**
  25677. * Unregisters a function called after every frame render
  25678. * @param func defines the function to unregister
  25679. */
  25680. Scene.prototype.unregisterAfterRender = function (func) {
  25681. this.onAfterRenderObservable.removeCallback(func);
  25682. };
  25683. Scene.prototype._executeOnceBeforeRender = function (func) {
  25684. var _this = this;
  25685. var execFunc = function () {
  25686. func();
  25687. setTimeout(function () {
  25688. _this.unregisterBeforeRender(execFunc);
  25689. });
  25690. };
  25691. this.registerBeforeRender(execFunc);
  25692. };
  25693. /**
  25694. * The provided function will run before render once and will be disposed afterwards.
  25695. * A timeout delay can be provided so that the function will be executed in N ms.
  25696. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25697. * @param func The function to be executed.
  25698. * @param timeout optional delay in ms
  25699. */
  25700. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25701. var _this = this;
  25702. if (timeout !== undefined) {
  25703. setTimeout(function () {
  25704. _this._executeOnceBeforeRender(func);
  25705. }, timeout);
  25706. }
  25707. else {
  25708. this._executeOnceBeforeRender(func);
  25709. }
  25710. };
  25711. /** @hidden */
  25712. Scene.prototype._addPendingData = function (data) {
  25713. this._pendingData.push(data);
  25714. };
  25715. /** @hidden */
  25716. Scene.prototype._removePendingData = function (data) {
  25717. var wasLoading = this.isLoading;
  25718. var index = this._pendingData.indexOf(data);
  25719. if (index !== -1) {
  25720. this._pendingData.splice(index, 1);
  25721. }
  25722. if (wasLoading && !this.isLoading) {
  25723. this.onDataLoadedObservable.notifyObservers(this);
  25724. }
  25725. };
  25726. /**
  25727. * Returns the number of items waiting to be loaded
  25728. * @returns the number of items waiting to be loaded
  25729. */
  25730. Scene.prototype.getWaitingItemsCount = function () {
  25731. return this._pendingData.length;
  25732. };
  25733. Object.defineProperty(Scene.prototype, "isLoading", {
  25734. /**
  25735. * Returns a boolean indicating if the scene is still loading data
  25736. */
  25737. get: function () {
  25738. return this._pendingData.length > 0;
  25739. },
  25740. enumerable: true,
  25741. configurable: true
  25742. });
  25743. /**
  25744. * Registers a function to be executed when the scene is ready
  25745. * @param {Function} func - the function to be executed
  25746. */
  25747. Scene.prototype.executeWhenReady = function (func) {
  25748. var _this = this;
  25749. this.onReadyObservable.add(func);
  25750. if (this._executeWhenReadyTimeoutId !== -1) {
  25751. return;
  25752. }
  25753. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25754. _this._checkIsReady();
  25755. }, 150);
  25756. };
  25757. /**
  25758. * Returns a promise that resolves when the scene is ready
  25759. * @returns A promise that resolves when the scene is ready
  25760. */
  25761. Scene.prototype.whenReadyAsync = function () {
  25762. var _this = this;
  25763. return new Promise(function (resolve) {
  25764. _this.executeWhenReady(function () {
  25765. resolve();
  25766. });
  25767. });
  25768. };
  25769. /** @hidden */
  25770. Scene.prototype._checkIsReady = function () {
  25771. var _this = this;
  25772. this._registerTransientComponents();
  25773. if (this.isReady()) {
  25774. this.onReadyObservable.notifyObservers(this);
  25775. this.onReadyObservable.clear();
  25776. this._executeWhenReadyTimeoutId = -1;
  25777. return;
  25778. }
  25779. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25780. _this._checkIsReady();
  25781. }, 150);
  25782. };
  25783. // Animations
  25784. /**
  25785. * Will start the animation sequence of a given target
  25786. * @param target defines the target
  25787. * @param from defines from which frame should animation start
  25788. * @param to defines until which frame should animation run.
  25789. * @param weight defines the weight to apply to the animation (1.0 by default)
  25790. * @param loop defines if the animation loops
  25791. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25792. * @param onAnimationEnd defines the function to be executed when the animation ends
  25793. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25794. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25795. * @returns the animatable object created for this animation
  25796. */
  25797. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25798. if (weight === void 0) { weight = 1.0; }
  25799. if (speedRatio === void 0) { speedRatio = 1.0; }
  25800. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25801. returnedAnimatable.weight = weight;
  25802. return returnedAnimatable;
  25803. };
  25804. /**
  25805. * Will start the animation sequence of a given target
  25806. * @param target defines the target
  25807. * @param from defines from which frame should animation start
  25808. * @param to defines until which frame should animation run.
  25809. * @param loop defines if the animation loops
  25810. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25811. * @param onAnimationEnd defines the function to be executed when the animation ends
  25812. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25813. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25814. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25815. * @returns the animatable object created for this animation
  25816. */
  25817. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25818. if (speedRatio === void 0) { speedRatio = 1.0; }
  25819. if (stopCurrent === void 0) { stopCurrent = true; }
  25820. if (from > to && speedRatio > 0) {
  25821. speedRatio *= -1;
  25822. }
  25823. if (stopCurrent) {
  25824. this.stopAnimation(target, undefined, targetMask);
  25825. }
  25826. if (!animatable) {
  25827. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25828. }
  25829. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25830. // Local animations
  25831. if (target.animations && shouldRunTargetAnimations) {
  25832. animatable.appendAnimations(target, target.animations);
  25833. }
  25834. // Children animations
  25835. if (target.getAnimatables) {
  25836. var animatables = target.getAnimatables();
  25837. for (var index = 0; index < animatables.length; index++) {
  25838. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25839. }
  25840. }
  25841. animatable.reset();
  25842. return animatable;
  25843. };
  25844. /**
  25845. * Begin a new animation on a given node
  25846. * @param target defines the target where the animation will take place
  25847. * @param animations defines the list of animations to start
  25848. * @param from defines the initial value
  25849. * @param to defines the final value
  25850. * @param loop defines if you want animation to loop (off by default)
  25851. * @param speedRatio defines the speed ratio to apply to all animations
  25852. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25853. * @returns the list of created animatables
  25854. */
  25855. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25856. if (speedRatio === undefined) {
  25857. speedRatio = 1.0;
  25858. }
  25859. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25860. return animatable;
  25861. };
  25862. /**
  25863. * Begin a new animation on a given node and its hierarchy
  25864. * @param target defines the root node where the animation will take place
  25865. * @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.
  25866. * @param animations defines the list of animations to start
  25867. * @param from defines the initial value
  25868. * @param to defines the final value
  25869. * @param loop defines if you want animation to loop (off by default)
  25870. * @param speedRatio defines the speed ratio to apply to all animations
  25871. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25872. * @returns the list of animatables created for all nodes
  25873. */
  25874. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25875. var children = target.getDescendants(directDescendantsOnly);
  25876. var result = [];
  25877. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25878. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25879. var child = children_1[_i];
  25880. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25881. }
  25882. return result;
  25883. };
  25884. /**
  25885. * Gets the animatable associated with a specific target
  25886. * @param target defines the target of the animatable
  25887. * @returns the required animatable if found
  25888. */
  25889. Scene.prototype.getAnimatableByTarget = function (target) {
  25890. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25891. if (this._activeAnimatables[index].target === target) {
  25892. return this._activeAnimatables[index];
  25893. }
  25894. }
  25895. return null;
  25896. };
  25897. /**
  25898. * Gets all animatables associated with a given target
  25899. * @param target defines the target to look animatables for
  25900. * @returns an array of Animatables
  25901. */
  25902. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25903. var result = [];
  25904. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25905. if (this._activeAnimatables[index].target === target) {
  25906. result.push(this._activeAnimatables[index]);
  25907. }
  25908. }
  25909. return result;
  25910. };
  25911. Object.defineProperty(Scene.prototype, "animatables", {
  25912. /**
  25913. * Gets all animatable attached to the scene
  25914. */
  25915. get: function () {
  25916. return this._activeAnimatables;
  25917. },
  25918. enumerable: true,
  25919. configurable: true
  25920. });
  25921. /**
  25922. * Will stop the animation of the given target
  25923. * @param target - the target
  25924. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25925. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  25926. */
  25927. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25928. var animatables = this.getAllAnimatablesByTarget(target);
  25929. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25930. var animatable = animatables_1[_i];
  25931. animatable.stop(animationName, targetMask);
  25932. }
  25933. };
  25934. /**
  25935. * Stops and removes all animations that have been applied to the scene
  25936. */
  25937. Scene.prototype.stopAllAnimations = function () {
  25938. if (this._activeAnimatables) {
  25939. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25940. this._activeAnimatables[i].stop();
  25941. }
  25942. this._activeAnimatables = [];
  25943. }
  25944. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25945. var group = _a[_i];
  25946. group.stop();
  25947. }
  25948. };
  25949. Scene.prototype._animate = function () {
  25950. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25951. return;
  25952. }
  25953. // Getting time
  25954. var now = BABYLON.Tools.Now;
  25955. if (!this._animationTimeLast) {
  25956. if (this._pendingData.length > 0) {
  25957. return;
  25958. }
  25959. this._animationTimeLast = now;
  25960. }
  25961. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25962. this._animationTime += deltaTime;
  25963. this._animationTimeLast = now;
  25964. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25965. this._activeAnimatables[index]._animate(this._animationTime);
  25966. }
  25967. // Late animation bindings
  25968. this._processLateAnimationBindings();
  25969. };
  25970. /** @hidden */
  25971. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25972. var target = runtimeAnimation.target;
  25973. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25974. if (!target._lateAnimationHolders) {
  25975. target._lateAnimationHolders = {};
  25976. }
  25977. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25978. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25979. totalWeight: 0,
  25980. animations: [],
  25981. originalValue: originalValue
  25982. };
  25983. }
  25984. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25985. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25986. };
  25987. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25988. var normalizer = 1.0;
  25989. var finalPosition = BABYLON.Tmp.Vector3[0];
  25990. var finalScaling = BABYLON.Tmp.Vector3[1];
  25991. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25992. var startIndex = 0;
  25993. var originalAnimation = holder.animations[0];
  25994. var originalValue = holder.originalValue;
  25995. var scale = 1;
  25996. if (holder.totalWeight < 1.0) {
  25997. // We need to mix the original value in
  25998. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25999. scale = 1.0 - holder.totalWeight;
  26000. }
  26001. else {
  26002. startIndex = 1;
  26003. // We need to normalize the weights
  26004. normalizer = holder.totalWeight;
  26005. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26006. scale = originalAnimation.weight / normalizer;
  26007. if (scale == 1) {
  26008. return originalAnimation.currentValue;
  26009. }
  26010. }
  26011. finalScaling.scaleInPlace(scale);
  26012. finalPosition.scaleInPlace(scale);
  26013. finalQuaternion.scaleInPlace(scale);
  26014. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26015. var runtimeAnimation = holder.animations[animIndex];
  26016. var scale = runtimeAnimation.weight / normalizer;
  26017. var currentPosition = BABYLON.Tmp.Vector3[2];
  26018. var currentScaling = BABYLON.Tmp.Vector3[3];
  26019. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26020. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26021. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26022. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26023. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26024. }
  26025. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26026. return originalAnimation._workValue;
  26027. };
  26028. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26029. var originalAnimation = holder.animations[0];
  26030. var originalValue = holder.originalValue;
  26031. if (holder.animations.length === 1) {
  26032. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26033. }
  26034. var normalizer = 1.0;
  26035. var quaternions;
  26036. var weights;
  26037. if (holder.totalWeight < 1.0) {
  26038. var scale = 1.0 - holder.totalWeight;
  26039. quaternions = [];
  26040. weights = [];
  26041. quaternions.push(originalValue);
  26042. weights.push(scale);
  26043. }
  26044. else {
  26045. if (holder.animations.length === 2) { // Slerp as soon as we can
  26046. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26047. }
  26048. quaternions = [];
  26049. weights = [];
  26050. normalizer = holder.totalWeight;
  26051. }
  26052. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26053. var runtimeAnimation = holder.animations[animIndex];
  26054. quaternions.push(runtimeAnimation.currentValue);
  26055. weights.push(runtimeAnimation.weight / normalizer);
  26056. }
  26057. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26058. var cumulativeAmount = 0;
  26059. var cumulativeQuaternion = null;
  26060. for (var index = 0; index < quaternions.length;) {
  26061. if (!cumulativeQuaternion) {
  26062. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26063. cumulativeAmount = weights[index] + weights[index + 1];
  26064. index += 2;
  26065. continue;
  26066. }
  26067. cumulativeAmount += weights[index];
  26068. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26069. index++;
  26070. }
  26071. return cumulativeQuaternion;
  26072. };
  26073. Scene.prototype._processLateAnimationBindings = function () {
  26074. if (!this._registeredForLateAnimationBindings.length) {
  26075. return;
  26076. }
  26077. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26078. var target = this._registeredForLateAnimationBindings.data[index];
  26079. for (var path in target._lateAnimationHolders) {
  26080. var holder = target._lateAnimationHolders[path];
  26081. var originalAnimation = holder.animations[0];
  26082. var originalValue = holder.originalValue;
  26083. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26084. var finalValue = void 0;
  26085. if (matrixDecomposeMode) {
  26086. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26087. }
  26088. else {
  26089. var quaternionMode = originalValue.w !== undefined;
  26090. if (quaternionMode) {
  26091. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26092. }
  26093. else {
  26094. var startIndex = 0;
  26095. var normalizer = 1.0;
  26096. if (holder.totalWeight < 1.0) {
  26097. // We need to mix the original value in
  26098. if (originalValue.scale) {
  26099. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26100. }
  26101. else {
  26102. finalValue = originalValue * (1.0 - holder.totalWeight);
  26103. }
  26104. }
  26105. else {
  26106. // We need to normalize the weights
  26107. normalizer = holder.totalWeight;
  26108. var scale_1 = originalAnimation.weight / normalizer;
  26109. if (scale_1 !== 1) {
  26110. if (originalAnimation.currentValue.scale) {
  26111. finalValue = originalAnimation.currentValue.scale(scale_1);
  26112. }
  26113. else {
  26114. finalValue = originalAnimation.currentValue * scale_1;
  26115. }
  26116. }
  26117. else {
  26118. finalValue = originalAnimation.currentValue;
  26119. }
  26120. startIndex = 1;
  26121. }
  26122. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26123. var runtimeAnimation = holder.animations[animIndex];
  26124. var scale = runtimeAnimation.weight / normalizer;
  26125. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26126. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26127. }
  26128. else {
  26129. finalValue += runtimeAnimation.currentValue * scale;
  26130. }
  26131. }
  26132. }
  26133. }
  26134. target[path] = finalValue;
  26135. }
  26136. target._lateAnimationHolders = {};
  26137. }
  26138. this._registeredForLateAnimationBindings.reset();
  26139. };
  26140. // Matrix
  26141. /** @hidden */
  26142. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26143. this._useAlternateCameraConfiguration = active;
  26144. };
  26145. /**
  26146. * Gets the current view matrix
  26147. * @returns a Matrix
  26148. */
  26149. Scene.prototype.getViewMatrix = function () {
  26150. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26151. };
  26152. /**
  26153. * Gets the current projection matrix
  26154. * @returns a Matrix
  26155. */
  26156. Scene.prototype.getProjectionMatrix = function () {
  26157. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26158. };
  26159. /**
  26160. * Gets the current transform matrix
  26161. * @returns a Matrix made of View * Projection
  26162. */
  26163. Scene.prototype.getTransformMatrix = function () {
  26164. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26165. };
  26166. /**
  26167. * Sets the current transform matrix
  26168. * @param view defines the View matrix to use
  26169. * @param projection defines the Projection matrix to use
  26170. */
  26171. Scene.prototype.setTransformMatrix = function (view, projection) {
  26172. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26173. return;
  26174. }
  26175. this._viewUpdateFlag = view.updateFlag;
  26176. this._projectionUpdateFlag = projection.updateFlag;
  26177. this._viewMatrix = view;
  26178. this._projectionMatrix = projection;
  26179. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26180. // Update frustum
  26181. if (!this._frustumPlanes) {
  26182. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26183. }
  26184. else {
  26185. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26186. }
  26187. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26188. var otherCamera = this.activeCamera._alternateCamera;
  26189. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26190. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26191. }
  26192. if (this._sceneUbo.useUbo) {
  26193. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26194. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26195. this._sceneUbo.update();
  26196. }
  26197. };
  26198. /** @hidden */
  26199. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26200. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26201. return;
  26202. }
  26203. this._alternateViewUpdateFlag = view.updateFlag;
  26204. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26205. this._alternateViewMatrix = view;
  26206. this._alternateProjectionMatrix = projection;
  26207. if (!this._alternateTransformMatrix) {
  26208. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26209. }
  26210. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26211. if (!this._alternateSceneUbo) {
  26212. this._createAlternateUbo();
  26213. }
  26214. if (this._alternateSceneUbo.useUbo) {
  26215. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26216. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26217. this._alternateSceneUbo.update();
  26218. }
  26219. };
  26220. /**
  26221. * Gets the uniform buffer used to store scene data
  26222. * @returns a UniformBuffer
  26223. */
  26224. Scene.prototype.getSceneUniformBuffer = function () {
  26225. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26226. };
  26227. /**
  26228. * Gets an unique (relatively to the current scene) Id
  26229. * @returns an unique number for the scene
  26230. */
  26231. Scene.prototype.getUniqueId = function () {
  26232. var result = Scene._uniqueIdCounter;
  26233. Scene._uniqueIdCounter++;
  26234. return result;
  26235. };
  26236. /**
  26237. * Add a mesh to the list of scene's meshes
  26238. * @param newMesh defines the mesh to add
  26239. * @param recursive if all child meshes should also be added to the scene
  26240. */
  26241. Scene.prototype.addMesh = function (newMesh, recursive) {
  26242. var _this = this;
  26243. if (recursive === void 0) { recursive = false; }
  26244. this.meshes.push(newMesh);
  26245. //notify the collision coordinator
  26246. if (this.collisionCoordinator) {
  26247. this.collisionCoordinator.onMeshAdded(newMesh);
  26248. }
  26249. newMesh._resyncLightSources();
  26250. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26251. if (recursive) {
  26252. newMesh.getChildMeshes().forEach(function (m) {
  26253. _this.addMesh(m);
  26254. });
  26255. }
  26256. };
  26257. /**
  26258. * Remove a mesh for the list of scene's meshes
  26259. * @param toRemove defines the mesh to remove
  26260. * @param recursive if all child meshes should also be removed from the scene
  26261. * @returns the index where the mesh was in the mesh list
  26262. */
  26263. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26264. var _this = this;
  26265. if (recursive === void 0) { recursive = false; }
  26266. var index = this.meshes.indexOf(toRemove);
  26267. if (index !== -1) {
  26268. // Remove from the scene if mesh found
  26269. this.meshes.splice(index, 1);
  26270. }
  26271. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26272. if (recursive) {
  26273. toRemove.getChildMeshes().forEach(function (m) {
  26274. _this.removeMesh(m);
  26275. });
  26276. }
  26277. return index;
  26278. };
  26279. /**
  26280. * Add a transform node to the list of scene's transform nodes
  26281. * @param newTransformNode defines the transform node to add
  26282. */
  26283. Scene.prototype.addTransformNode = function (newTransformNode) {
  26284. this.transformNodes.push(newTransformNode);
  26285. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26286. };
  26287. /**
  26288. * Remove a transform node for the list of scene's transform nodes
  26289. * @param toRemove defines the transform node to remove
  26290. * @returns the index where the transform node was in the transform node list
  26291. */
  26292. Scene.prototype.removeTransformNode = function (toRemove) {
  26293. var index = this.transformNodes.indexOf(toRemove);
  26294. if (index !== -1) {
  26295. // Remove from the scene if found
  26296. this.transformNodes.splice(index, 1);
  26297. }
  26298. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26299. return index;
  26300. };
  26301. /**
  26302. * Remove a skeleton for the list of scene's skeletons
  26303. * @param toRemove defines the skeleton to remove
  26304. * @returns the index where the skeleton was in the skeleton list
  26305. */
  26306. Scene.prototype.removeSkeleton = function (toRemove) {
  26307. var index = this.skeletons.indexOf(toRemove);
  26308. if (index !== -1) {
  26309. // Remove from the scene if found
  26310. this.skeletons.splice(index, 1);
  26311. }
  26312. return index;
  26313. };
  26314. /**
  26315. * Remove a morph target for the list of scene's morph targets
  26316. * @param toRemove defines the morph target to remove
  26317. * @returns the index where the morph target was in the morph target list
  26318. */
  26319. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26320. var index = this.morphTargetManagers.indexOf(toRemove);
  26321. if (index !== -1) {
  26322. // Remove from the scene if found
  26323. this.morphTargetManagers.splice(index, 1);
  26324. }
  26325. return index;
  26326. };
  26327. /**
  26328. * Remove a light for the list of scene's lights
  26329. * @param toRemove defines the light to remove
  26330. * @returns the index where the light was in the light list
  26331. */
  26332. Scene.prototype.removeLight = function (toRemove) {
  26333. var index = this.lights.indexOf(toRemove);
  26334. if (index !== -1) {
  26335. // Remove from meshes
  26336. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26337. var mesh = _a[_i];
  26338. mesh._removeLightSource(toRemove);
  26339. }
  26340. // Remove from the scene if mesh found
  26341. this.lights.splice(index, 1);
  26342. this.sortLightsByPriority();
  26343. }
  26344. this.onLightRemovedObservable.notifyObservers(toRemove);
  26345. return index;
  26346. };
  26347. /**
  26348. * Remove a camera for the list of scene's cameras
  26349. * @param toRemove defines the camera to remove
  26350. * @returns the index where the camera was in the camera list
  26351. */
  26352. Scene.prototype.removeCamera = function (toRemove) {
  26353. var index = this.cameras.indexOf(toRemove);
  26354. if (index !== -1) {
  26355. // Remove from the scene if mesh found
  26356. this.cameras.splice(index, 1);
  26357. }
  26358. // Remove from activeCameras
  26359. var index2 = this.activeCameras.indexOf(toRemove);
  26360. if (index2 !== -1) {
  26361. // Remove from the scene if mesh found
  26362. this.activeCameras.splice(index2, 1);
  26363. }
  26364. // Reset the activeCamera
  26365. if (this.activeCamera === toRemove) {
  26366. if (this.cameras.length > 0) {
  26367. this.activeCamera = this.cameras[0];
  26368. }
  26369. else {
  26370. this.activeCamera = null;
  26371. }
  26372. }
  26373. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26374. return index;
  26375. };
  26376. /**
  26377. * Remove a particle system for the list of scene's particle systems
  26378. * @param toRemove defines the particle system to remove
  26379. * @returns the index where the particle system was in the particle system list
  26380. */
  26381. Scene.prototype.removeParticleSystem = function (toRemove) {
  26382. var index = this.particleSystems.indexOf(toRemove);
  26383. if (index !== -1) {
  26384. this.particleSystems.splice(index, 1);
  26385. }
  26386. return index;
  26387. };
  26388. /**
  26389. * Remove a animation for the list of scene's animations
  26390. * @param toRemove defines the animation to remove
  26391. * @returns the index where the animation was in the animation list
  26392. */
  26393. Scene.prototype.removeAnimation = function (toRemove) {
  26394. var index = this.animations.indexOf(toRemove);
  26395. if (index !== -1) {
  26396. this.animations.splice(index, 1);
  26397. }
  26398. return index;
  26399. };
  26400. /**
  26401. * Removes the given animation group from this scene.
  26402. * @param toRemove The animation group to remove
  26403. * @returns The index of the removed animation group
  26404. */
  26405. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26406. var index = this.animationGroups.indexOf(toRemove);
  26407. if (index !== -1) {
  26408. this.animationGroups.splice(index, 1);
  26409. }
  26410. return index;
  26411. };
  26412. /**
  26413. * Removes the given multi-material from this scene.
  26414. * @param toRemove The multi-material to remove
  26415. * @returns The index of the removed multi-material
  26416. */
  26417. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26418. var index = this.multiMaterials.indexOf(toRemove);
  26419. if (index !== -1) {
  26420. this.multiMaterials.splice(index, 1);
  26421. }
  26422. return index;
  26423. };
  26424. /**
  26425. * Removes the given material from this scene.
  26426. * @param toRemove The material to remove
  26427. * @returns The index of the removed material
  26428. */
  26429. Scene.prototype.removeMaterial = function (toRemove) {
  26430. var index = this.materials.indexOf(toRemove);
  26431. if (index !== -1) {
  26432. this.materials.splice(index, 1);
  26433. }
  26434. return index;
  26435. };
  26436. /**
  26437. * Removes the given action manager from this scene.
  26438. * @param toRemove The action manager to remove
  26439. * @returns The index of the removed action manager
  26440. */
  26441. Scene.prototype.removeActionManager = function (toRemove) {
  26442. var index = this.actionManagers.indexOf(toRemove);
  26443. if (index !== -1) {
  26444. this.actionManagers.splice(index, 1);
  26445. }
  26446. return index;
  26447. };
  26448. /**
  26449. * Removes the given texture from this scene.
  26450. * @param toRemove The texture to remove
  26451. * @returns The index of the removed texture
  26452. */
  26453. Scene.prototype.removeTexture = function (toRemove) {
  26454. var index = this.textures.indexOf(toRemove);
  26455. if (index !== -1) {
  26456. this.textures.splice(index, 1);
  26457. }
  26458. return index;
  26459. };
  26460. /**
  26461. * Adds the given light to this scene
  26462. * @param newLight The light to add
  26463. */
  26464. Scene.prototype.addLight = function (newLight) {
  26465. this.lights.push(newLight);
  26466. this.sortLightsByPriority();
  26467. // Add light to all meshes (To support if the light is removed and then readded)
  26468. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26469. var mesh = _a[_i];
  26470. if (mesh._lightSources.indexOf(newLight) === -1) {
  26471. mesh._lightSources.push(newLight);
  26472. mesh._resyncLightSources();
  26473. }
  26474. }
  26475. this.onNewLightAddedObservable.notifyObservers(newLight);
  26476. };
  26477. /**
  26478. * Sorts the list list based on light priorities
  26479. */
  26480. Scene.prototype.sortLightsByPriority = function () {
  26481. if (this.requireLightSorting) {
  26482. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26483. }
  26484. };
  26485. /**
  26486. * Adds the given camera to this scene
  26487. * @param newCamera The camera to add
  26488. */
  26489. Scene.prototype.addCamera = function (newCamera) {
  26490. this.cameras.push(newCamera);
  26491. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26492. };
  26493. /**
  26494. * Adds the given skeleton to this scene
  26495. * @param newSkeleton The skeleton to add
  26496. */
  26497. Scene.prototype.addSkeleton = function (newSkeleton) {
  26498. this.skeletons.push(newSkeleton);
  26499. };
  26500. /**
  26501. * Adds the given particle system to this scene
  26502. * @param newParticleSystem The particle system to add
  26503. */
  26504. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26505. this.particleSystems.push(newParticleSystem);
  26506. };
  26507. /**
  26508. * Adds the given animation to this scene
  26509. * @param newAnimation The animation to add
  26510. */
  26511. Scene.prototype.addAnimation = function (newAnimation) {
  26512. this.animations.push(newAnimation);
  26513. };
  26514. /**
  26515. * Adds the given animation group to this scene.
  26516. * @param newAnimationGroup The animation group to add
  26517. */
  26518. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26519. this.animationGroups.push(newAnimationGroup);
  26520. };
  26521. /**
  26522. * Adds the given multi-material to this scene
  26523. * @param newMultiMaterial The multi-material to add
  26524. */
  26525. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26526. this.multiMaterials.push(newMultiMaterial);
  26527. };
  26528. /**
  26529. * Adds the given material to this scene
  26530. * @param newMaterial The material to add
  26531. */
  26532. Scene.prototype.addMaterial = function (newMaterial) {
  26533. this.materials.push(newMaterial);
  26534. };
  26535. /**
  26536. * Adds the given morph target to this scene
  26537. * @param newMorphTargetManager The morph target to add
  26538. */
  26539. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26540. this.morphTargetManagers.push(newMorphTargetManager);
  26541. };
  26542. /**
  26543. * Adds the given geometry to this scene
  26544. * @param newGeometry The geometry to add
  26545. */
  26546. Scene.prototype.addGeometry = function (newGeometry) {
  26547. this.geometries.push(newGeometry);
  26548. };
  26549. /**
  26550. * Adds the given action manager to this scene
  26551. * @param newActionManager The action manager to add
  26552. */
  26553. Scene.prototype.addActionManager = function (newActionManager) {
  26554. this.actionManagers.push(newActionManager);
  26555. };
  26556. /**
  26557. * Adds the given texture to this scene.
  26558. * @param newTexture The texture to add
  26559. */
  26560. Scene.prototype.addTexture = function (newTexture) {
  26561. this.textures.push(newTexture);
  26562. };
  26563. /**
  26564. * Switch active camera
  26565. * @param newCamera defines the new active camera
  26566. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26567. */
  26568. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26569. if (attachControl === void 0) { attachControl = true; }
  26570. var canvas = this._engine.getRenderingCanvas();
  26571. if (!canvas) {
  26572. return;
  26573. }
  26574. if (this.activeCamera) {
  26575. this.activeCamera.detachControl(canvas);
  26576. }
  26577. this.activeCamera = newCamera;
  26578. if (attachControl) {
  26579. newCamera.attachControl(canvas);
  26580. }
  26581. };
  26582. /**
  26583. * sets the active camera of the scene using its ID
  26584. * @param id defines the camera's ID
  26585. * @return the new active camera or null if none found.
  26586. */
  26587. Scene.prototype.setActiveCameraByID = function (id) {
  26588. var camera = this.getCameraByID(id);
  26589. if (camera) {
  26590. this.activeCamera = camera;
  26591. return camera;
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * sets the active camera of the scene using its name
  26597. * @param name defines the camera's name
  26598. * @returns the new active camera or null if none found.
  26599. */
  26600. Scene.prototype.setActiveCameraByName = function (name) {
  26601. var camera = this.getCameraByName(name);
  26602. if (camera) {
  26603. this.activeCamera = camera;
  26604. return camera;
  26605. }
  26606. return null;
  26607. };
  26608. /**
  26609. * get an animation group using its name
  26610. * @param name defines the material's name
  26611. * @return the animation group or null if none found.
  26612. */
  26613. Scene.prototype.getAnimationGroupByName = function (name) {
  26614. for (var index = 0; index < this.animationGroups.length; index++) {
  26615. if (this.animationGroups[index].name === name) {
  26616. return this.animationGroups[index];
  26617. }
  26618. }
  26619. return null;
  26620. };
  26621. /**
  26622. * get a material using its id
  26623. * @param id defines the material's ID
  26624. * @return the material or null if none found.
  26625. */
  26626. Scene.prototype.getMaterialByID = function (id) {
  26627. for (var index = 0; index < this.materials.length; index++) {
  26628. if (this.materials[index].id === id) {
  26629. return this.materials[index];
  26630. }
  26631. }
  26632. return null;
  26633. };
  26634. /**
  26635. * Gets a material using its name
  26636. * @param name defines the material's name
  26637. * @return the material or null if none found.
  26638. */
  26639. Scene.prototype.getMaterialByName = function (name) {
  26640. for (var index = 0; index < this.materials.length; index++) {
  26641. if (this.materials[index].name === name) {
  26642. return this.materials[index];
  26643. }
  26644. }
  26645. return null;
  26646. };
  26647. /**
  26648. * Gets a camera using its id
  26649. * @param id defines the id to look for
  26650. * @returns the camera or null if not found
  26651. */
  26652. Scene.prototype.getCameraByID = function (id) {
  26653. for (var index = 0; index < this.cameras.length; index++) {
  26654. if (this.cameras[index].id === id) {
  26655. return this.cameras[index];
  26656. }
  26657. }
  26658. return null;
  26659. };
  26660. /**
  26661. * Gets a camera using its unique id
  26662. * @param uniqueId defines the unique id to look for
  26663. * @returns the camera or null if not found
  26664. */
  26665. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26666. for (var index = 0; index < this.cameras.length; index++) {
  26667. if (this.cameras[index].uniqueId === uniqueId) {
  26668. return this.cameras[index];
  26669. }
  26670. }
  26671. return null;
  26672. };
  26673. /**
  26674. * Gets a camera using its name
  26675. * @param name defines the camera's name
  26676. * @return the camera or null if none found.
  26677. */
  26678. Scene.prototype.getCameraByName = function (name) {
  26679. for (var index = 0; index < this.cameras.length; index++) {
  26680. if (this.cameras[index].name === name) {
  26681. return this.cameras[index];
  26682. }
  26683. }
  26684. return null;
  26685. };
  26686. /**
  26687. * Gets a bone using its id
  26688. * @param id defines the bone's id
  26689. * @return the bone or null if not found
  26690. */
  26691. Scene.prototype.getBoneByID = function (id) {
  26692. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26693. var skeleton = this.skeletons[skeletonIndex];
  26694. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26695. if (skeleton.bones[boneIndex].id === id) {
  26696. return skeleton.bones[boneIndex];
  26697. }
  26698. }
  26699. }
  26700. return null;
  26701. };
  26702. /**
  26703. * Gets a bone using its id
  26704. * @param name defines the bone's name
  26705. * @return the bone or null if not found
  26706. */
  26707. Scene.prototype.getBoneByName = function (name) {
  26708. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26709. var skeleton = this.skeletons[skeletonIndex];
  26710. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26711. if (skeleton.bones[boneIndex].name === name) {
  26712. return skeleton.bones[boneIndex];
  26713. }
  26714. }
  26715. }
  26716. return null;
  26717. };
  26718. /**
  26719. * Gets a light node using its name
  26720. * @param name defines the the light's name
  26721. * @return the light or null if none found.
  26722. */
  26723. Scene.prototype.getLightByName = function (name) {
  26724. for (var index = 0; index < this.lights.length; index++) {
  26725. if (this.lights[index].name === name) {
  26726. return this.lights[index];
  26727. }
  26728. }
  26729. return null;
  26730. };
  26731. /**
  26732. * Gets a light node using its id
  26733. * @param id defines the light's id
  26734. * @return the light or null if none found.
  26735. */
  26736. Scene.prototype.getLightByID = function (id) {
  26737. for (var index = 0; index < this.lights.length; index++) {
  26738. if (this.lights[index].id === id) {
  26739. return this.lights[index];
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * Gets a light node using its scene-generated unique ID
  26746. * @param uniqueId defines the light's unique id
  26747. * @return the light or null if none found.
  26748. */
  26749. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26750. for (var index = 0; index < this.lights.length; index++) {
  26751. if (this.lights[index].uniqueId === uniqueId) {
  26752. return this.lights[index];
  26753. }
  26754. }
  26755. return null;
  26756. };
  26757. /**
  26758. * Gets a particle system by id
  26759. * @param id defines the particle system id
  26760. * @return the corresponding system or null if none found
  26761. */
  26762. Scene.prototype.getParticleSystemByID = function (id) {
  26763. for (var index = 0; index < this.particleSystems.length; index++) {
  26764. if (this.particleSystems[index].id === id) {
  26765. return this.particleSystems[index];
  26766. }
  26767. }
  26768. return null;
  26769. };
  26770. /**
  26771. * Gets a geometry using its ID
  26772. * @param id defines the geometry's id
  26773. * @return the geometry or null if none found.
  26774. */
  26775. Scene.prototype.getGeometryByID = function (id) {
  26776. for (var index = 0; index < this.geometries.length; index++) {
  26777. if (this.geometries[index].id === id) {
  26778. return this.geometries[index];
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Add a new geometry to this scene
  26785. * @param geometry defines the geometry to be added to the scene.
  26786. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26787. * @return a boolean defining if the geometry was added or not
  26788. */
  26789. Scene.prototype.pushGeometry = function (geometry, force) {
  26790. if (!force && this.getGeometryByID(geometry.id)) {
  26791. return false;
  26792. }
  26793. this.geometries.push(geometry);
  26794. //notify the collision coordinator
  26795. if (this.collisionCoordinator) {
  26796. this.collisionCoordinator.onGeometryAdded(geometry);
  26797. }
  26798. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26799. return true;
  26800. };
  26801. /**
  26802. * Removes an existing geometry
  26803. * @param geometry defines the geometry to be removed from the scene
  26804. * @return a boolean defining if the geometry was removed or not
  26805. */
  26806. Scene.prototype.removeGeometry = function (geometry) {
  26807. var index = this.geometries.indexOf(geometry);
  26808. if (index > -1) {
  26809. this.geometries.splice(index, 1);
  26810. //notify the collision coordinator
  26811. if (this.collisionCoordinator) {
  26812. this.collisionCoordinator.onGeometryDeleted(geometry);
  26813. }
  26814. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26815. return true;
  26816. }
  26817. return false;
  26818. };
  26819. /**
  26820. * Gets the list of geometries attached to the scene
  26821. * @returns an array of Geometry
  26822. */
  26823. Scene.prototype.getGeometries = function () {
  26824. return this.geometries;
  26825. };
  26826. /**
  26827. * Gets the first added mesh found of a given ID
  26828. * @param id defines the id to search for
  26829. * @return the mesh found or null if not found at all
  26830. */
  26831. Scene.prototype.getMeshByID = function (id) {
  26832. for (var index = 0; index < this.meshes.length; index++) {
  26833. if (this.meshes[index].id === id) {
  26834. return this.meshes[index];
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * Gets a list of meshes using their id
  26841. * @param id defines the id to search for
  26842. * @returns a list of meshes
  26843. */
  26844. Scene.prototype.getMeshesByID = function (id) {
  26845. return this.meshes.filter(function (m) {
  26846. return m.id === id;
  26847. });
  26848. };
  26849. /**
  26850. * Gets the first added transform node found of a given ID
  26851. * @param id defines the id to search for
  26852. * @return the found transform node or null if not found at all.
  26853. */
  26854. Scene.prototype.getTransformNodeByID = function (id) {
  26855. for (var index = 0; index < this.transformNodes.length; index++) {
  26856. if (this.transformNodes[index].id === id) {
  26857. return this.transformNodes[index];
  26858. }
  26859. }
  26860. return null;
  26861. };
  26862. /**
  26863. * Gets a list of transform nodes using their id
  26864. * @param id defines the id to search for
  26865. * @returns a list of transform nodes
  26866. */
  26867. Scene.prototype.getTransformNodesByID = function (id) {
  26868. return this.transformNodes.filter(function (m) {
  26869. return m.id === id;
  26870. });
  26871. };
  26872. /**
  26873. * Gets a mesh with its auto-generated unique id
  26874. * @param uniqueId defines the unique id to search for
  26875. * @return the found mesh or null if not found at all.
  26876. */
  26877. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26878. for (var index = 0; index < this.meshes.length; index++) {
  26879. if (this.meshes[index].uniqueId === uniqueId) {
  26880. return this.meshes[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a the last added mesh using a given id
  26887. * @param id defines the id to search for
  26888. * @return the found mesh or null if not found at all.
  26889. */
  26890. Scene.prototype.getLastMeshByID = function (id) {
  26891. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26892. if (this.meshes[index].id === id) {
  26893. return this.meshes[index];
  26894. }
  26895. }
  26896. return null;
  26897. };
  26898. /**
  26899. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26900. * @param id defines the id to search for
  26901. * @return the found node or null if not found at all
  26902. */
  26903. Scene.prototype.getLastEntryByID = function (id) {
  26904. var index;
  26905. for (index = this.meshes.length - 1; index >= 0; index--) {
  26906. if (this.meshes[index].id === id) {
  26907. return this.meshes[index];
  26908. }
  26909. }
  26910. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26911. if (this.transformNodes[index].id === id) {
  26912. return this.transformNodes[index];
  26913. }
  26914. }
  26915. for (index = this.cameras.length - 1; index >= 0; index--) {
  26916. if (this.cameras[index].id === id) {
  26917. return this.cameras[index];
  26918. }
  26919. }
  26920. for (index = this.lights.length - 1; index >= 0; index--) {
  26921. if (this.lights[index].id === id) {
  26922. return this.lights[index];
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a node (Mesh, Camera, Light) using a given id
  26929. * @param id defines the id to search for
  26930. * @return the found node or null if not found at all
  26931. */
  26932. Scene.prototype.getNodeByID = function (id) {
  26933. var mesh = this.getMeshByID(id);
  26934. if (mesh) {
  26935. return mesh;
  26936. }
  26937. var light = this.getLightByID(id);
  26938. if (light) {
  26939. return light;
  26940. }
  26941. var camera = this.getCameraByID(id);
  26942. if (camera) {
  26943. return camera;
  26944. }
  26945. var bone = this.getBoneByID(id);
  26946. return bone;
  26947. };
  26948. /**
  26949. * Gets a node (Mesh, Camera, Light) using a given name
  26950. * @param name defines the name to search for
  26951. * @return the found node or null if not found at all.
  26952. */
  26953. Scene.prototype.getNodeByName = function (name) {
  26954. var mesh = this.getMeshByName(name);
  26955. if (mesh) {
  26956. return mesh;
  26957. }
  26958. var light = this.getLightByName(name);
  26959. if (light) {
  26960. return light;
  26961. }
  26962. var camera = this.getCameraByName(name);
  26963. if (camera) {
  26964. return camera;
  26965. }
  26966. var bone = this.getBoneByName(name);
  26967. return bone;
  26968. };
  26969. /**
  26970. * Gets a mesh using a given name
  26971. * @param name defines the name to search for
  26972. * @return the found mesh or null if not found at all.
  26973. */
  26974. Scene.prototype.getMeshByName = function (name) {
  26975. for (var index = 0; index < this.meshes.length; index++) {
  26976. if (this.meshes[index].name === name) {
  26977. return this.meshes[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * Gets a transform node using a given name
  26984. * @param name defines the name to search for
  26985. * @return the found transform node or null if not found at all.
  26986. */
  26987. Scene.prototype.getTransformNodeByName = function (name) {
  26988. for (var index = 0; index < this.transformNodes.length; index++) {
  26989. if (this.transformNodes[index].name === name) {
  26990. return this.transformNodes[index];
  26991. }
  26992. }
  26993. return null;
  26994. };
  26995. /**
  26996. * Gets a sound using a given name
  26997. * @param name defines the name to search for
  26998. * @return the found sound or null if not found at all.
  26999. */
  27000. Scene.prototype.getSoundByName = function (name) {
  27001. var index;
  27002. if (BABYLON.AudioEngine) {
  27003. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27004. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27005. return this.mainSoundTrack.soundCollection[index];
  27006. }
  27007. }
  27008. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27009. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27010. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27011. return this.soundTracks[sdIndex].soundCollection[index];
  27012. }
  27013. }
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27020. * @param id defines the id to search for
  27021. * @return the found skeleton or null if not found at all.
  27022. */
  27023. Scene.prototype.getLastSkeletonByID = function (id) {
  27024. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27025. if (this.skeletons[index].id === id) {
  27026. return this.skeletons[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27033. * @param id defines the id to search for
  27034. * @return the found skeleton or null if not found at all.
  27035. */
  27036. Scene.prototype.getSkeletonById = function (id) {
  27037. for (var index = 0; index < this.skeletons.length; index++) {
  27038. if (this.skeletons[index].id === id) {
  27039. return this.skeletons[index];
  27040. }
  27041. }
  27042. return null;
  27043. };
  27044. /**
  27045. * Gets a skeleton using a given name
  27046. * @param name defines the name to search for
  27047. * @return the found skeleton or null if not found at all.
  27048. */
  27049. Scene.prototype.getSkeletonByName = function (name) {
  27050. for (var index = 0; index < this.skeletons.length; index++) {
  27051. if (this.skeletons[index].name === name) {
  27052. return this.skeletons[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27059. * @param id defines the id to search for
  27060. * @return the found morph target manager or null if not found at all.
  27061. */
  27062. Scene.prototype.getMorphTargetManagerById = function (id) {
  27063. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27064. if (this.morphTargetManagers[index].uniqueId === id) {
  27065. return this.morphTargetManagers[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Gets a boolean indicating if the given mesh is active
  27072. * @param mesh defines the mesh to look for
  27073. * @returns true if the mesh is in the active list
  27074. */
  27075. Scene.prototype.isActiveMesh = function (mesh) {
  27076. return (this._activeMeshes.indexOf(mesh) !== -1);
  27077. };
  27078. Object.defineProperty(Scene.prototype, "uid", {
  27079. /**
  27080. * Return a unique id as a string which can serve as an identifier for the scene
  27081. */
  27082. get: function () {
  27083. if (!this._uid) {
  27084. this._uid = BABYLON.Tools.RandomId();
  27085. }
  27086. return this._uid;
  27087. },
  27088. enumerable: true,
  27089. configurable: true
  27090. });
  27091. /**
  27092. * Add an externaly attached data from its key.
  27093. * This method call will fail and return false, if such key already exists.
  27094. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27095. * @param key the unique key that identifies the data
  27096. * @param data the data object to associate to the key for this Engine instance
  27097. * @return true if no such key were already present and the data was added successfully, false otherwise
  27098. */
  27099. Scene.prototype.addExternalData = function (key, data) {
  27100. if (!this._externalData) {
  27101. this._externalData = new BABYLON.StringDictionary();
  27102. }
  27103. return this._externalData.add(key, data);
  27104. };
  27105. /**
  27106. * Get an externaly attached data from its key
  27107. * @param key the unique key that identifies the data
  27108. * @return the associated data, if present (can be null), or undefined if not present
  27109. */
  27110. Scene.prototype.getExternalData = function (key) {
  27111. if (!this._externalData) {
  27112. return null;
  27113. }
  27114. return this._externalData.get(key);
  27115. };
  27116. /**
  27117. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27118. * @param key the unique key that identifies the data
  27119. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27120. * @return the associated data, can be null if the factory returned null.
  27121. */
  27122. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27123. if (!this._externalData) {
  27124. this._externalData = new BABYLON.StringDictionary();
  27125. }
  27126. return this._externalData.getOrAddWithFactory(key, factory);
  27127. };
  27128. /**
  27129. * Remove an externaly attached data from the Engine instance
  27130. * @param key the unique key that identifies the data
  27131. * @return true if the data was successfully removed, false if it doesn't exist
  27132. */
  27133. Scene.prototype.removeExternalData = function (key) {
  27134. return this._externalData.remove(key);
  27135. };
  27136. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27137. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27138. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27139. var step = _a[_i];
  27140. step.action(mesh, subMesh);
  27141. }
  27142. var material = subMesh.getMaterial();
  27143. if (material !== null && material !== undefined) {
  27144. // Render targets
  27145. if (material.getRenderTargetTextures !== undefined) {
  27146. if (this._processedMaterials.indexOf(material) === -1) {
  27147. this._processedMaterials.push(material);
  27148. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27149. }
  27150. }
  27151. // Dispatch
  27152. this._activeIndices.addCount(subMesh.indexCount, false);
  27153. this._renderingManager.dispatch(subMesh, mesh, material);
  27154. }
  27155. }
  27156. };
  27157. /**
  27158. * Clear the processed materials smart array preventing retention point in material dispose.
  27159. */
  27160. Scene.prototype.freeProcessedMaterials = function () {
  27161. this._processedMaterials.dispose();
  27162. };
  27163. /**
  27164. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27165. */
  27166. Scene.prototype.freeActiveMeshes = function () {
  27167. this._activeMeshes.dispose();
  27168. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27169. this.activeCamera._activeMeshes.dispose();
  27170. }
  27171. if (this.activeCameras) {
  27172. for (var i = 0; i < this.activeCameras.length; i++) {
  27173. var activeCamera = this.activeCameras[i];
  27174. if (activeCamera && activeCamera._activeMeshes) {
  27175. activeCamera._activeMeshes.dispose();
  27176. }
  27177. }
  27178. }
  27179. };
  27180. /**
  27181. * Clear the info related to rendering groups preventing retention points during dispose.
  27182. */
  27183. Scene.prototype.freeRenderingGroups = function () {
  27184. if (this._renderingManager) {
  27185. this._renderingManager.freeRenderingGroups();
  27186. }
  27187. if (this.textures) {
  27188. for (var i = 0; i < this.textures.length; i++) {
  27189. var texture = this.textures[i];
  27190. if (texture && texture.renderList) {
  27191. texture.freeRenderingGroups();
  27192. }
  27193. }
  27194. }
  27195. };
  27196. /** @hidden */
  27197. Scene.prototype._isInIntermediateRendering = function () {
  27198. return this._intermediateRendering;
  27199. };
  27200. /**
  27201. * Defines the current active mesh candidate provider
  27202. * @param provider defines the provider to use
  27203. */
  27204. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27205. this._activeMeshCandidateProvider = provider;
  27206. };
  27207. /**
  27208. * Gets the current active mesh candidate provider
  27209. * @returns the current active mesh candidate provider
  27210. */
  27211. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27212. return this._activeMeshCandidateProvider;
  27213. };
  27214. /**
  27215. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27216. * @returns the current scene
  27217. */
  27218. Scene.prototype.freezeActiveMeshes = function () {
  27219. if (!this.activeCamera) {
  27220. return this;
  27221. }
  27222. if (!this._frustumPlanes) {
  27223. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27224. }
  27225. this._evaluateActiveMeshes();
  27226. this._activeMeshesFrozen = true;
  27227. return this;
  27228. };
  27229. /**
  27230. * Use this function to restart evaluating active meshes on every frame
  27231. * @returns the current scene
  27232. */
  27233. Scene.prototype.unfreezeActiveMeshes = function () {
  27234. this._activeMeshesFrozen = false;
  27235. return this;
  27236. };
  27237. Scene.prototype._evaluateActiveMeshes = function () {
  27238. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27239. return;
  27240. }
  27241. if (!this.activeCamera) {
  27242. return;
  27243. }
  27244. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27245. this.activeCamera._activeMeshes.reset();
  27246. this._activeMeshes.reset();
  27247. this._renderingManager.reset();
  27248. this._processedMaterials.reset();
  27249. this._activeParticleSystems.reset();
  27250. this._activeSkeletons.reset();
  27251. this._softwareSkinnedMeshes.reset();
  27252. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27253. var step = _a[_i];
  27254. step.action();
  27255. }
  27256. // Meshes
  27257. var meshes;
  27258. var len;
  27259. var checkIsEnabled = true;
  27260. // Determine mesh candidates
  27261. if (this._activeMeshCandidateProvider !== undefined) {
  27262. // Use _activeMeshCandidateProvider
  27263. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27264. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27265. if (meshes !== undefined) {
  27266. len = meshes.length;
  27267. }
  27268. else {
  27269. len = 0;
  27270. }
  27271. }
  27272. else if (this._selectionOctree !== undefined) {
  27273. // Octree
  27274. var selection = this._selectionOctree.select(this._frustumPlanes);
  27275. meshes = selection.data;
  27276. len = selection.length;
  27277. }
  27278. else {
  27279. // Full scene traversal
  27280. len = this.meshes.length;
  27281. meshes = this.meshes;
  27282. }
  27283. // Check each mesh
  27284. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27285. mesh = meshes[meshIndex];
  27286. if (mesh.isBlocked) {
  27287. continue;
  27288. }
  27289. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27290. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27291. continue;
  27292. }
  27293. mesh.computeWorldMatrix();
  27294. // Intersections
  27295. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27296. this._meshesForIntersections.pushNoDuplicate(mesh);
  27297. }
  27298. // Switch to current LOD
  27299. meshLOD = mesh.getLOD(this.activeCamera);
  27300. if (meshLOD === undefined || meshLOD === null) {
  27301. continue;
  27302. }
  27303. mesh._preActivate();
  27304. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27305. this._activeMeshes.push(mesh);
  27306. this.activeCamera._activeMeshes.push(mesh);
  27307. mesh._activate(this._renderId);
  27308. if (meshLOD !== mesh) {
  27309. meshLOD._activate(this._renderId);
  27310. }
  27311. this._activeMesh(mesh, meshLOD);
  27312. }
  27313. }
  27314. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27315. // Particle systems
  27316. if (this.particlesEnabled) {
  27317. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27318. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27319. var particleSystem = this.particleSystems[particleIndex];
  27320. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27321. continue;
  27322. }
  27323. var emitter = particleSystem.emitter;
  27324. if (!emitter.position || emitter.isEnabled()) {
  27325. this._activeParticleSystems.push(particleSystem);
  27326. particleSystem.animate();
  27327. this._renderingManager.dispatchParticles(particleSystem);
  27328. }
  27329. }
  27330. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27331. }
  27332. };
  27333. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27334. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27335. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27336. mesh.skeleton.prepare();
  27337. }
  27338. if (!mesh.computeBonesUsingShaders) {
  27339. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27340. }
  27341. }
  27342. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27343. var step = _a[_i];
  27344. step.action(sourceMesh, mesh);
  27345. }
  27346. if (mesh !== undefined && mesh !== null
  27347. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27348. // Submeshes Octrees
  27349. var len;
  27350. var subMeshes;
  27351. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27352. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27353. len = intersections.length;
  27354. subMeshes = intersections.data;
  27355. }
  27356. else {
  27357. subMeshes = mesh.subMeshes;
  27358. len = subMeshes.length;
  27359. }
  27360. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27361. subMesh = subMeshes[subIndex];
  27362. this._evaluateSubMesh(subMesh, mesh);
  27363. }
  27364. }
  27365. };
  27366. /**
  27367. * Update the transform matrix to update from the current active camera
  27368. * @param force defines a boolean used to force the update even if cache is up to date
  27369. */
  27370. Scene.prototype.updateTransformMatrix = function (force) {
  27371. if (!this.activeCamera) {
  27372. return;
  27373. }
  27374. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27375. };
  27376. /**
  27377. * 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)
  27378. * @param alternateCamera defines the camera to use
  27379. */
  27380. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27381. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27382. };
  27383. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27384. if (camera && camera._skipRendering) {
  27385. return;
  27386. }
  27387. var engine = this._engine;
  27388. this.activeCamera = camera;
  27389. if (!this.activeCamera)
  27390. throw new Error("Active camera not set");
  27391. // Viewport
  27392. engine.setViewport(this.activeCamera.viewport);
  27393. // Camera
  27394. this.resetCachedMaterial();
  27395. this._renderId++;
  27396. this.updateTransformMatrix();
  27397. if (camera._alternateCamera) {
  27398. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27399. this._alternateRendering = true;
  27400. }
  27401. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27402. // Meshes
  27403. this._evaluateActiveMeshes();
  27404. // Software skinning
  27405. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27406. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27407. mesh.applySkeleton(mesh.skeleton);
  27408. }
  27409. // Render targets
  27410. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27411. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27412. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27413. }
  27414. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27415. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27416. }
  27417. if (this.renderTargetsEnabled) {
  27418. this._intermediateRendering = true;
  27419. if (this._renderTargets.length > 0) {
  27420. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27421. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27422. var renderTarget = this._renderTargets.data[renderIndex];
  27423. if (renderTarget._shouldRender()) {
  27424. this._renderId++;
  27425. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27426. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27427. }
  27428. }
  27429. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27430. this._renderId++;
  27431. }
  27432. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27433. var step = _a[_i];
  27434. step.action(this.activeCamera);
  27435. }
  27436. this._intermediateRendering = false;
  27437. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27438. }
  27439. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27440. // Prepare Frame
  27441. if (this.postProcessManager) {
  27442. this.postProcessManager._prepareFrame();
  27443. }
  27444. // Before Camera Draw
  27445. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27446. var step = _c[_b];
  27447. step.action(this.activeCamera);
  27448. }
  27449. // Render
  27450. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27451. this._renderingManager.render(null, null, true, true);
  27452. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27453. // After Camera Draw
  27454. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27455. var step = _e[_d];
  27456. step.action(this.activeCamera);
  27457. }
  27458. // Finalize frame
  27459. if (this.postProcessManager) {
  27460. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27461. }
  27462. // Reset some special arrays
  27463. this._renderTargets.reset();
  27464. this._alternateRendering = false;
  27465. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27466. };
  27467. Scene.prototype._processSubCameras = function (camera) {
  27468. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27469. this._renderForCamera(camera);
  27470. return;
  27471. }
  27472. // rig cameras
  27473. for (var index = 0; index < camera._rigCameras.length; index++) {
  27474. this._renderForCamera(camera._rigCameras[index], camera);
  27475. }
  27476. this.activeCamera = camera;
  27477. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27478. };
  27479. Scene.prototype._checkIntersections = function () {
  27480. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27481. var sourceMesh = this._meshesForIntersections.data[index];
  27482. if (!sourceMesh.actionManager) {
  27483. continue;
  27484. }
  27485. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27486. var action = sourceMesh.actionManager.actions[actionIndex];
  27487. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27488. var parameters = action.getTriggerParameter();
  27489. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27490. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27491. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27492. if (areIntersecting && currentIntersectionInProgress === -1) {
  27493. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27494. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27495. sourceMesh._intersectionsInProgress.push(otherMesh);
  27496. }
  27497. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27498. sourceMesh._intersectionsInProgress.push(otherMesh);
  27499. }
  27500. }
  27501. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27502. //They intersected, and now they don't.
  27503. //is this trigger an exit trigger? execute an event.
  27504. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27505. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27506. }
  27507. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27508. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27509. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27510. return otherMesh === parameterMesh;
  27511. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27512. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27513. }
  27514. }
  27515. }
  27516. }
  27517. }
  27518. };
  27519. /**
  27520. * Render the scene
  27521. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27522. */
  27523. Scene.prototype.render = function (updateCameras) {
  27524. if (updateCameras === void 0) { updateCameras = true; }
  27525. if (this.isDisposed) {
  27526. return;
  27527. }
  27528. // Register components that have been associated lately to the scene.
  27529. this._registerTransientComponents();
  27530. this._activeParticles.fetchNewFrame();
  27531. this._totalVertices.fetchNewFrame();
  27532. this._activeIndices.fetchNewFrame();
  27533. this._activeBones.fetchNewFrame();
  27534. this._meshesForIntersections.reset();
  27535. this.resetCachedMaterial();
  27536. this.onBeforeAnimationsObservable.notifyObservers(this);
  27537. // Actions
  27538. if (this.actionManager) {
  27539. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27540. }
  27541. //Simplification Queue
  27542. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27543. this.simplificationQueue.executeNext();
  27544. }
  27545. if (this._engine.isDeterministicLockStep()) {
  27546. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27547. var defaultFPS = (60.0 / 1000.0);
  27548. var defaultFrameTime = 1000 / 60; // frame time in MS
  27549. if (this._physicsEngine) {
  27550. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27551. }
  27552. var stepsTaken = 0;
  27553. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27554. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27555. internalSteps = Math.min(internalSteps, maxSubSteps);
  27556. do {
  27557. this.onBeforeStepObservable.notifyObservers(this);
  27558. // Animations
  27559. this._animationRatio = defaultFrameTime * defaultFPS;
  27560. this._animate();
  27561. this.onAfterAnimationsObservable.notifyObservers(this);
  27562. // Physics
  27563. if (this._physicsEngine) {
  27564. this.onBeforePhysicsObservable.notifyObservers(this);
  27565. this._physicsEngine._step(defaultFrameTime / 1000);
  27566. this.onAfterPhysicsObservable.notifyObservers(this);
  27567. }
  27568. this.onAfterStepObservable.notifyObservers(this);
  27569. this._currentStepId++;
  27570. stepsTaken++;
  27571. deltaTime -= defaultFrameTime;
  27572. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27573. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27574. }
  27575. else {
  27576. // Animations
  27577. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27578. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27579. this._animate();
  27580. this.onAfterAnimationsObservable.notifyObservers(this);
  27581. // Physics
  27582. if (this._physicsEngine) {
  27583. this.onBeforePhysicsObservable.notifyObservers(this);
  27584. this._physicsEngine._step(deltaTime / 1000.0);
  27585. this.onAfterPhysicsObservable.notifyObservers(this);
  27586. }
  27587. }
  27588. // Before camera update steps
  27589. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27590. var step = _a[_i];
  27591. step.action();
  27592. }
  27593. // Update Cameras
  27594. if (updateCameras) {
  27595. if (this.activeCameras.length > 0) {
  27596. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27597. var camera = this.activeCameras[cameraIndex];
  27598. camera.update();
  27599. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27600. // rig cameras
  27601. for (var index = 0; index < camera._rigCameras.length; index++) {
  27602. camera._rigCameras[index].update();
  27603. }
  27604. }
  27605. }
  27606. }
  27607. else if (this.activeCamera) {
  27608. this.activeCamera.update();
  27609. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27610. // rig cameras
  27611. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27612. this.activeCamera._rigCameras[index].update();
  27613. }
  27614. }
  27615. }
  27616. }
  27617. // Before render
  27618. this.onBeforeRenderObservable.notifyObservers(this);
  27619. // Customs render targets
  27620. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27621. var engine = this.getEngine();
  27622. var currentActiveCamera = this.activeCamera;
  27623. if (this.renderTargetsEnabled) {
  27624. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27625. this._intermediateRendering = true;
  27626. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27627. var renderTarget = this.customRenderTargets[customIndex];
  27628. if (renderTarget._shouldRender()) {
  27629. this._renderId++;
  27630. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27631. if (!this.activeCamera)
  27632. throw new Error("Active camera not set");
  27633. // Viewport
  27634. engine.setViewport(this.activeCamera.viewport);
  27635. // Camera
  27636. this.updateTransformMatrix();
  27637. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27638. }
  27639. }
  27640. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27641. this._intermediateRendering = false;
  27642. this._renderId++;
  27643. }
  27644. // Restore back buffer
  27645. if (this.customRenderTargets.length > 0) {
  27646. engine.restoreDefaultFramebuffer();
  27647. }
  27648. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27649. this.activeCamera = currentActiveCamera;
  27650. // Procedural textures
  27651. if (this.proceduralTexturesEnabled) {
  27652. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27653. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27654. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27655. if (proceduralTexture._shouldRender()) {
  27656. proceduralTexture.render();
  27657. }
  27658. }
  27659. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27660. }
  27661. // Clear
  27662. if (this.autoClearDepthAndStencil || this.autoClear) {
  27663. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27664. }
  27665. // Shadows
  27666. if (this.shadowsEnabled) {
  27667. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27668. var light = this.lights[lightIndex];
  27669. var shadowGenerator = light.getShadowGenerator();
  27670. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27671. var shadowMap = (shadowGenerator.getShadowMap());
  27672. if (this.textures.indexOf(shadowMap) !== -1) {
  27673. this._renderTargets.push(shadowMap);
  27674. }
  27675. }
  27676. }
  27677. }
  27678. // Depth renderer
  27679. for (var key in this._depthRenderer) {
  27680. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27681. }
  27682. // Geometry renderer
  27683. if (this._geometryBufferRenderer) {
  27684. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27685. }
  27686. // RenderPipeline
  27687. if (this._postProcessRenderPipelineManager) {
  27688. this._postProcessRenderPipelineManager.update();
  27689. }
  27690. // Multi-cameras?
  27691. if (this.activeCameras.length > 0) {
  27692. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27693. if (cameraIndex > 0) {
  27694. this._engine.clear(null, false, true, true);
  27695. }
  27696. this._processSubCameras(this.activeCameras[cameraIndex]);
  27697. }
  27698. }
  27699. else {
  27700. if (!this.activeCamera) {
  27701. throw new Error("No camera defined");
  27702. }
  27703. this._processSubCameras(this.activeCamera);
  27704. }
  27705. // Intersection checks
  27706. this._checkIntersections();
  27707. // Update the audio listener attached to the camera
  27708. if (BABYLON.AudioEngine) {
  27709. this._updateAudioParameters();
  27710. }
  27711. // After render
  27712. if (this.afterRender) {
  27713. this.afterRender();
  27714. }
  27715. this.onAfterRenderObservable.notifyObservers(this);
  27716. // Cleaning
  27717. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27718. var data = this._toBeDisposed.data[index];
  27719. if (data) {
  27720. data.dispose();
  27721. }
  27722. this._toBeDisposed[index] = null;
  27723. }
  27724. this._toBeDisposed.reset();
  27725. if (this.dumpNextRenderTargets) {
  27726. this.dumpNextRenderTargets = false;
  27727. }
  27728. this._activeBones.addCount(0, true);
  27729. this._activeIndices.addCount(0, true);
  27730. this._activeParticles.addCount(0, true);
  27731. };
  27732. Scene.prototype._updateAudioParameters = function () {
  27733. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27734. return;
  27735. }
  27736. var listeningCamera;
  27737. var audioEngine = BABYLON.Engine.audioEngine;
  27738. if (this.activeCameras.length > 0) {
  27739. listeningCamera = this.activeCameras[0];
  27740. }
  27741. else {
  27742. listeningCamera = this.activeCamera;
  27743. }
  27744. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27745. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27746. // for VR cameras
  27747. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27748. listeningCamera = listeningCamera.rigCameras[0];
  27749. }
  27750. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27751. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27752. cameraDirection.normalize();
  27753. // To avoid some errors on GearVR
  27754. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27755. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27756. }
  27757. var i;
  27758. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27759. var sound = this.mainSoundTrack.soundCollection[i];
  27760. if (sound.useCustomAttenuation) {
  27761. sound.updateDistanceFromListener();
  27762. }
  27763. }
  27764. for (i = 0; i < this.soundTracks.length; i++) {
  27765. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27766. sound = this.soundTracks[i].soundCollection[j];
  27767. if (sound.useCustomAttenuation) {
  27768. sound.updateDistanceFromListener();
  27769. }
  27770. }
  27771. }
  27772. }
  27773. };
  27774. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27775. // Audio
  27776. /**
  27777. * Gets or sets if audio support is enabled
  27778. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27779. */
  27780. get: function () {
  27781. return this._audioEnabled;
  27782. },
  27783. set: function (value) {
  27784. this._audioEnabled = value;
  27785. if (BABYLON.AudioEngine) {
  27786. if (this._audioEnabled) {
  27787. this._enableAudio();
  27788. }
  27789. else {
  27790. this._disableAudio();
  27791. }
  27792. }
  27793. },
  27794. enumerable: true,
  27795. configurable: true
  27796. });
  27797. Scene.prototype._disableAudio = function () {
  27798. var i;
  27799. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27800. this.mainSoundTrack.soundCollection[i].pause();
  27801. }
  27802. for (i = 0; i < this.soundTracks.length; i++) {
  27803. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27804. this.soundTracks[i].soundCollection[j].pause();
  27805. }
  27806. }
  27807. };
  27808. Scene.prototype._enableAudio = function () {
  27809. var i;
  27810. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27811. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27812. this.mainSoundTrack.soundCollection[i].play();
  27813. }
  27814. }
  27815. for (i = 0; i < this.soundTracks.length; i++) {
  27816. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27817. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27818. this.soundTracks[i].soundCollection[j].play();
  27819. }
  27820. }
  27821. }
  27822. };
  27823. Object.defineProperty(Scene.prototype, "headphone", {
  27824. /**
  27825. * Gets or sets if audio will be output to headphones
  27826. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27827. */
  27828. get: function () {
  27829. return this._headphone;
  27830. },
  27831. set: function (value) {
  27832. this._headphone = value;
  27833. if (BABYLON.AudioEngine) {
  27834. if (this._headphone) {
  27835. this._switchAudioModeForHeadphones();
  27836. }
  27837. else {
  27838. this._switchAudioModeForNormalSpeakers();
  27839. }
  27840. }
  27841. },
  27842. enumerable: true,
  27843. configurable: true
  27844. });
  27845. Scene.prototype._switchAudioModeForHeadphones = function () {
  27846. this.mainSoundTrack.switchPanningModelToHRTF();
  27847. for (var i = 0; i < this.soundTracks.length; i++) {
  27848. this.soundTracks[i].switchPanningModelToHRTF();
  27849. }
  27850. };
  27851. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27852. this.mainSoundTrack.switchPanningModelToEqualPower();
  27853. for (var i = 0; i < this.soundTracks.length; i++) {
  27854. this.soundTracks[i].switchPanningModelToEqualPower();
  27855. }
  27856. };
  27857. /**
  27858. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27859. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27860. * @returns the created depth renderer
  27861. */
  27862. Scene.prototype.enableDepthRenderer = function (camera) {
  27863. camera = camera || this.activeCamera;
  27864. if (!camera) {
  27865. throw "No camera available to enable depth renderer";
  27866. }
  27867. if (!this._depthRenderer[camera.id]) {
  27868. var textureType = 0;
  27869. if (this._engine.getCaps().textureHalfFloatRender) {
  27870. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27871. }
  27872. else if (this._engine.getCaps().textureFloatRender) {
  27873. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27874. }
  27875. else {
  27876. throw "Depth renderer does not support int texture type";
  27877. }
  27878. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27879. }
  27880. return this._depthRenderer[camera.id];
  27881. };
  27882. /**
  27883. * Disables a depth renderer for a given camera
  27884. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27885. */
  27886. Scene.prototype.disableDepthRenderer = function (camera) {
  27887. camera = camera || this.activeCamera;
  27888. if (!camera || !this._depthRenderer[camera.id]) {
  27889. return;
  27890. }
  27891. this._depthRenderer[camera.id].dispose();
  27892. delete this._depthRenderer[camera.id];
  27893. };
  27894. /**
  27895. * Enables a GeometryBufferRender and associates it with the scene
  27896. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27897. * @returns the GeometryBufferRenderer
  27898. */
  27899. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27900. if (ratio === void 0) { ratio = 1; }
  27901. if (this._geometryBufferRenderer) {
  27902. return this._geometryBufferRenderer;
  27903. }
  27904. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27905. if (!this._geometryBufferRenderer.isSupported) {
  27906. this._geometryBufferRenderer = null;
  27907. }
  27908. return this._geometryBufferRenderer;
  27909. };
  27910. /**
  27911. * Disables the GeometryBufferRender associated with the scene
  27912. */
  27913. Scene.prototype.disableGeometryBufferRenderer = function () {
  27914. if (!this._geometryBufferRenderer) {
  27915. return;
  27916. }
  27917. this._geometryBufferRenderer.dispose();
  27918. this._geometryBufferRenderer = null;
  27919. };
  27920. /**
  27921. * Freeze all materials
  27922. * A frozen material will not be updatable but should be faster to render
  27923. */
  27924. Scene.prototype.freezeMaterials = function () {
  27925. for (var i = 0; i < this.materials.length; i++) {
  27926. this.materials[i].freeze();
  27927. }
  27928. };
  27929. /**
  27930. * Unfreeze all materials
  27931. * A frozen material will not be updatable but should be faster to render
  27932. */
  27933. Scene.prototype.unfreezeMaterials = function () {
  27934. for (var i = 0; i < this.materials.length; i++) {
  27935. this.materials[i].unfreeze();
  27936. }
  27937. };
  27938. /**
  27939. * Releases all held ressources
  27940. */
  27941. Scene.prototype.dispose = function () {
  27942. this.beforeRender = null;
  27943. this.afterRender = null;
  27944. this.skeletons = [];
  27945. this.morphTargetManagers = [];
  27946. this._transientComponents = [];
  27947. this._isReadyForMeshStage.clear();
  27948. this._beforeEvaluateActiveMeshStage.clear();
  27949. this._evaluateSubMeshStage.clear();
  27950. this._activeMeshStage.clear();
  27951. this._cameraDrawRenderTargetStage.clear();
  27952. this._beforeCameraDrawStage.clear();
  27953. this._beforeRenderingGroupDrawStage.clear();
  27954. this._afterRenderingGroupDrawStage.clear();
  27955. this._afterCameraDrawStage.clear();
  27956. this._beforeCameraUpdateStage.clear();
  27957. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27958. var component = _a[_i];
  27959. component.dispose();
  27960. }
  27961. this.importedMeshesFiles = new Array();
  27962. this.stopAllAnimations();
  27963. this.resetCachedMaterial();
  27964. for (var key in this._depthRenderer) {
  27965. this._depthRenderer[key].dispose();
  27966. }
  27967. // Smart arrays
  27968. if (this.activeCamera) {
  27969. this.activeCamera._activeMeshes.dispose();
  27970. this.activeCamera = null;
  27971. }
  27972. this._activeMeshes.dispose();
  27973. this._renderingManager.dispose();
  27974. this._processedMaterials.dispose();
  27975. this._activeParticleSystems.dispose();
  27976. this._activeSkeletons.dispose();
  27977. this._softwareSkinnedMeshes.dispose();
  27978. this._renderTargets.dispose();
  27979. this._registeredForLateAnimationBindings.dispose();
  27980. this._meshesForIntersections.dispose();
  27981. this._toBeDisposed.dispose();
  27982. // Abort active requests
  27983. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27984. var request = _c[_b];
  27985. request.abort();
  27986. }
  27987. // Debug layer
  27988. if (this._debugLayer) {
  27989. this._debugLayer.hide();
  27990. }
  27991. // Events
  27992. this.onDisposeObservable.notifyObservers(this);
  27993. this.onDisposeObservable.clear();
  27994. this.onBeforeRenderObservable.clear();
  27995. this.onAfterRenderObservable.clear();
  27996. this.onBeforeRenderTargetsRenderObservable.clear();
  27997. this.onAfterRenderTargetsRenderObservable.clear();
  27998. this.onAfterStepObservable.clear();
  27999. this.onBeforeStepObservable.clear();
  28000. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28001. this.onAfterActiveMeshesEvaluationObservable.clear();
  28002. this.onBeforeParticlesRenderingObservable.clear();
  28003. this.onAfterParticlesRenderingObservable.clear();
  28004. this.onBeforeSpritesRenderingObservable.clear();
  28005. this.onAfterSpritesRenderingObservable.clear();
  28006. this.onBeforeDrawPhaseObservable.clear();
  28007. this.onAfterDrawPhaseObservable.clear();
  28008. this.onBeforePhysicsObservable.clear();
  28009. this.onAfterPhysicsObservable.clear();
  28010. this.onBeforeAnimationsObservable.clear();
  28011. this.onAfterAnimationsObservable.clear();
  28012. this.onDataLoadedObservable.clear();
  28013. this.onBeforeRenderingGroupObservable.clear();
  28014. this.onAfterRenderingGroupObservable.clear();
  28015. this.detachControl();
  28016. // Release sounds & sounds tracks
  28017. if (BABYLON.AudioEngine) {
  28018. this.disposeSounds();
  28019. }
  28020. // VR Helper
  28021. if (this.VRHelper) {
  28022. this.VRHelper.dispose();
  28023. }
  28024. // Detach cameras
  28025. var canvas = this._engine.getRenderingCanvas();
  28026. if (canvas) {
  28027. var index;
  28028. for (index = 0; index < this.cameras.length; index++) {
  28029. this.cameras[index].detachControl(canvas);
  28030. }
  28031. }
  28032. // Release animation groups
  28033. while (this.animationGroups.length) {
  28034. this.animationGroups[0].dispose();
  28035. }
  28036. // Release lights
  28037. while (this.lights.length) {
  28038. this.lights[0].dispose();
  28039. }
  28040. // Release meshes
  28041. while (this.meshes.length) {
  28042. this.meshes[0].dispose(true);
  28043. }
  28044. while (this.transformNodes.length) {
  28045. this.removeTransformNode(this.transformNodes[0]);
  28046. }
  28047. // Release cameras
  28048. while (this.cameras.length) {
  28049. this.cameras[0].dispose();
  28050. }
  28051. // Release materials
  28052. if (this.defaultMaterial) {
  28053. this.defaultMaterial.dispose();
  28054. }
  28055. while (this.multiMaterials.length) {
  28056. this.multiMaterials[0].dispose();
  28057. }
  28058. while (this.materials.length) {
  28059. this.materials[0].dispose();
  28060. }
  28061. // Release particles
  28062. while (this.particleSystems.length) {
  28063. this.particleSystems[0].dispose();
  28064. }
  28065. // Release sprites
  28066. while (this.spriteManagers.length) {
  28067. this.spriteManagers[0].dispose();
  28068. }
  28069. // Release postProcesses
  28070. while (this.postProcesses.length) {
  28071. this.postProcesses[0].dispose();
  28072. }
  28073. // Release textures
  28074. while (this.textures.length) {
  28075. this.textures[0].dispose();
  28076. }
  28077. // Release UBO
  28078. this._sceneUbo.dispose();
  28079. if (this._alternateSceneUbo) {
  28080. this._alternateSceneUbo.dispose();
  28081. }
  28082. // Post-processes
  28083. this.postProcessManager.dispose();
  28084. if (this._postProcessRenderPipelineManager) {
  28085. this._postProcessRenderPipelineManager.dispose();
  28086. }
  28087. // Physics
  28088. if (this._physicsEngine) {
  28089. this.disablePhysicsEngine();
  28090. }
  28091. // Remove from engine
  28092. index = this._engine.scenes.indexOf(this);
  28093. if (index > -1) {
  28094. this._engine.scenes.splice(index, 1);
  28095. }
  28096. this._engine.wipeCaches(true);
  28097. this._isDisposed = true;
  28098. };
  28099. Object.defineProperty(Scene.prototype, "isDisposed", {
  28100. /**
  28101. * Gets if the scene is already disposed
  28102. */
  28103. get: function () {
  28104. return this._isDisposed;
  28105. },
  28106. enumerable: true,
  28107. configurable: true
  28108. });
  28109. /**
  28110. * Releases sounds & soundtracks
  28111. */
  28112. Scene.prototype.disposeSounds = function () {
  28113. if (!this._mainSoundTrack) {
  28114. return;
  28115. }
  28116. this.mainSoundTrack.dispose();
  28117. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28118. this.soundTracks[scIndex].dispose();
  28119. }
  28120. };
  28121. /**
  28122. * Call this function to reduce memory footprint of the scene.
  28123. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28124. */
  28125. Scene.prototype.clearCachedVertexData = function () {
  28126. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28127. var mesh = this.meshes[meshIndex];
  28128. var geometry = mesh.geometry;
  28129. if (geometry) {
  28130. geometry._indices = [];
  28131. for (var vbName in geometry._vertexBuffers) {
  28132. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28133. continue;
  28134. }
  28135. geometry._vertexBuffers[vbName]._buffer._data = null;
  28136. }
  28137. }
  28138. }
  28139. };
  28140. /**
  28141. * This function will remove the local cached buffer data from texture.
  28142. * It will save memory but will prevent the texture from being rebuilt
  28143. */
  28144. Scene.prototype.cleanCachedTextureBuffer = function () {
  28145. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28146. var baseTexture = _a[_i];
  28147. var buffer = baseTexture._buffer;
  28148. if (buffer) {
  28149. baseTexture._buffer = null;
  28150. }
  28151. }
  28152. };
  28153. // Octrees
  28154. /**
  28155. * Get the world extend vectors with an optional filter
  28156. *
  28157. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28158. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28159. */
  28160. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28161. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28162. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28163. filterPredicate = filterPredicate || (function () { return true; });
  28164. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28165. mesh.computeWorldMatrix(true);
  28166. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28167. return;
  28168. }
  28169. var boundingInfo = mesh.getBoundingInfo();
  28170. var minBox = boundingInfo.boundingBox.minimumWorld;
  28171. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28172. BABYLON.Tools.CheckExtends(minBox, min, max);
  28173. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28174. });
  28175. return {
  28176. min: min,
  28177. max: max
  28178. };
  28179. };
  28180. /**
  28181. * Creates or updates the octree used to boost selection (picking)
  28182. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28183. * @param maxCapacity defines the maximum capacity per leaf
  28184. * @param maxDepth defines the maximum depth of the octree
  28185. * @returns an octree of AbstractMesh
  28186. */
  28187. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28188. if (maxCapacity === void 0) { maxCapacity = 64; }
  28189. if (maxDepth === void 0) { maxDepth = 2; }
  28190. if (!this._selectionOctree) {
  28191. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28192. }
  28193. var worldExtends = this.getWorldExtends();
  28194. // Update octree
  28195. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28196. return this._selectionOctree;
  28197. };
  28198. // Picking
  28199. /**
  28200. * Creates a ray that can be used to pick in the scene
  28201. * @param x defines the x coordinate of the origin (on-screen)
  28202. * @param y defines the y coordinate of the origin (on-screen)
  28203. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28204. * @param camera defines the camera to use for the picking
  28205. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28206. * @returns a Ray
  28207. */
  28208. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28209. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28210. var result = BABYLON.Ray.Zero();
  28211. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28212. return result;
  28213. };
  28214. /**
  28215. * Creates a ray that can be used to pick in the scene
  28216. * @param x defines the x coordinate of the origin (on-screen)
  28217. * @param y defines the y coordinate of the origin (on-screen)
  28218. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28219. * @param result defines the ray where to store the picking ray
  28220. * @param camera defines the camera to use for the picking
  28221. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28222. * @returns the current scene
  28223. */
  28224. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28225. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28226. var engine = this._engine;
  28227. if (!camera) {
  28228. if (!this.activeCamera)
  28229. throw new Error("Active camera not set");
  28230. camera = this.activeCamera;
  28231. }
  28232. var cameraViewport = camera.viewport;
  28233. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28234. // Moving coordinates to local viewport world
  28235. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28236. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28237. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28238. return this;
  28239. };
  28240. /**
  28241. * Creates a ray that can be used to pick in the scene
  28242. * @param x defines the x coordinate of the origin (on-screen)
  28243. * @param y defines the y coordinate of the origin (on-screen)
  28244. * @param camera defines the camera to use for the picking
  28245. * @returns a Ray
  28246. */
  28247. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28248. var result = BABYLON.Ray.Zero();
  28249. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28250. return result;
  28251. };
  28252. /**
  28253. * Creates a ray that can be used to pick in the scene
  28254. * @param x defines the x coordinate of the origin (on-screen)
  28255. * @param y defines the y coordinate of the origin (on-screen)
  28256. * @param result defines the ray where to store the picking ray
  28257. * @param camera defines the camera to use for the picking
  28258. * @returns the current scene
  28259. */
  28260. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28261. if (!BABYLON.PickingInfo) {
  28262. return this;
  28263. }
  28264. var engine = this._engine;
  28265. if (!camera) {
  28266. if (!this.activeCamera)
  28267. throw new Error("Active camera not set");
  28268. camera = this.activeCamera;
  28269. }
  28270. var cameraViewport = camera.viewport;
  28271. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28272. var identity = BABYLON.Matrix.Identity();
  28273. // Moving coordinates to local viewport world
  28274. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28275. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28276. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28277. return this;
  28278. };
  28279. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28280. if (!BABYLON.PickingInfo) {
  28281. return null;
  28282. }
  28283. var pickingInfo = null;
  28284. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28285. var mesh = this.meshes[meshIndex];
  28286. if (predicate) {
  28287. if (!predicate(mesh)) {
  28288. continue;
  28289. }
  28290. }
  28291. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28292. continue;
  28293. }
  28294. var world = mesh.getWorldMatrix();
  28295. var ray = rayFunction(world);
  28296. var result = mesh.intersects(ray, fastCheck);
  28297. if (!result || !result.hit)
  28298. continue;
  28299. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28300. continue;
  28301. pickingInfo = result;
  28302. if (fastCheck) {
  28303. break;
  28304. }
  28305. }
  28306. return pickingInfo || new BABYLON.PickingInfo();
  28307. };
  28308. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28309. if (!BABYLON.PickingInfo) {
  28310. return null;
  28311. }
  28312. var pickingInfos = new Array();
  28313. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28314. var mesh = this.meshes[meshIndex];
  28315. if (predicate) {
  28316. if (!predicate(mesh)) {
  28317. continue;
  28318. }
  28319. }
  28320. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28321. continue;
  28322. }
  28323. var world = mesh.getWorldMatrix();
  28324. var ray = rayFunction(world);
  28325. var result = mesh.intersects(ray, false);
  28326. if (!result || !result.hit)
  28327. continue;
  28328. pickingInfos.push(result);
  28329. }
  28330. return pickingInfos;
  28331. };
  28332. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28333. if (!BABYLON.PickingInfo) {
  28334. return null;
  28335. }
  28336. var pickingInfo = null;
  28337. if (!camera) {
  28338. if (!this.activeCamera) {
  28339. return null;
  28340. }
  28341. camera = this.activeCamera;
  28342. }
  28343. if (this.spriteManagers.length > 0) {
  28344. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28345. var spriteManager = this.spriteManagers[spriteIndex];
  28346. if (!spriteManager.isPickable) {
  28347. continue;
  28348. }
  28349. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28350. if (!result || !result.hit)
  28351. continue;
  28352. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28353. continue;
  28354. pickingInfo = result;
  28355. if (fastCheck) {
  28356. break;
  28357. }
  28358. }
  28359. }
  28360. return pickingInfo || new BABYLON.PickingInfo();
  28361. };
  28362. /** Launch a ray to try to pick a mesh in the scene
  28363. * @param x position on screen
  28364. * @param y position on screen
  28365. * @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
  28366. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28367. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28368. * @returns a PickingInfo
  28369. */
  28370. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28371. var _this = this;
  28372. if (!BABYLON.PickingInfo) {
  28373. return null;
  28374. }
  28375. var result = this._internalPick(function (world) {
  28376. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28377. return _this._tempPickingRay;
  28378. }, predicate, fastCheck);
  28379. if (result) {
  28380. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28381. }
  28382. return result;
  28383. };
  28384. /** Launch a ray to try to pick a sprite in the scene
  28385. * @param x position on screen
  28386. * @param y position on screen
  28387. * @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
  28388. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28389. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28390. * @returns a PickingInfo
  28391. */
  28392. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28393. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28394. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28395. };
  28396. /** Use the given ray to pick a mesh in the scene
  28397. * @param ray The ray to use to pick meshes
  28398. * @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
  28399. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28400. * @returns a PickingInfo
  28401. */
  28402. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28403. var _this = this;
  28404. var result = this._internalPick(function (world) {
  28405. if (!_this._pickWithRayInverseMatrix) {
  28406. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28407. }
  28408. world.invertToRef(_this._pickWithRayInverseMatrix);
  28409. if (!_this._cachedRayForTransform) {
  28410. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28411. }
  28412. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28413. return _this._cachedRayForTransform;
  28414. }, predicate, fastCheck);
  28415. if (result) {
  28416. result.ray = ray;
  28417. }
  28418. return result;
  28419. };
  28420. /**
  28421. * Launch a ray to try to pick a mesh in the scene
  28422. * @param x X position on screen
  28423. * @param y Y position on screen
  28424. * @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
  28425. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28426. * @returns an array of PickingInfo
  28427. */
  28428. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28429. var _this = this;
  28430. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28431. };
  28432. /**
  28433. * Launch a ray to try to pick a mesh in the scene
  28434. * @param ray Ray to use
  28435. * @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
  28436. * @returns an array of PickingInfo
  28437. */
  28438. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28439. var _this = this;
  28440. return this._internalMultiPick(function (world) {
  28441. if (!_this._pickWithRayInverseMatrix) {
  28442. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28443. }
  28444. world.invertToRef(_this._pickWithRayInverseMatrix);
  28445. if (!_this._cachedRayForTransform) {
  28446. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28447. }
  28448. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28449. return _this._cachedRayForTransform;
  28450. }, predicate);
  28451. };
  28452. /**
  28453. * Force the value of meshUnderPointer
  28454. * @param mesh defines the mesh to use
  28455. */
  28456. Scene.prototype.setPointerOverMesh = function (mesh) {
  28457. if (this._pointerOverMesh === mesh) {
  28458. return;
  28459. }
  28460. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28461. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28462. }
  28463. this._pointerOverMesh = mesh;
  28464. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28465. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28466. }
  28467. };
  28468. /**
  28469. * Gets the mesh under the pointer
  28470. * @returns a Mesh or null if no mesh is under the pointer
  28471. */
  28472. Scene.prototype.getPointerOverMesh = function () {
  28473. return this._pointerOverMesh;
  28474. };
  28475. /**
  28476. * Force the sprite under the pointer
  28477. * @param sprite defines the sprite to use
  28478. */
  28479. Scene.prototype.setPointerOverSprite = function (sprite) {
  28480. if (this._pointerOverSprite === sprite) {
  28481. return;
  28482. }
  28483. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28484. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28485. }
  28486. this._pointerOverSprite = sprite;
  28487. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28488. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28489. }
  28490. };
  28491. /**
  28492. * Gets the sprite under the pointer
  28493. * @returns a Sprite or null if no sprite is under the pointer
  28494. */
  28495. Scene.prototype.getPointerOverSprite = function () {
  28496. return this._pointerOverSprite;
  28497. };
  28498. // Physics
  28499. /**
  28500. * Gets the current physics engine
  28501. * @returns a PhysicsEngine or null if none attached
  28502. */
  28503. Scene.prototype.getPhysicsEngine = function () {
  28504. return this._physicsEngine;
  28505. };
  28506. /**
  28507. * Enables physics to the current scene
  28508. * @param gravity defines the scene's gravity for the physics engine
  28509. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28510. * @return a boolean indicating if the physics engine was initialized
  28511. */
  28512. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28513. if (gravity === void 0) { gravity = null; }
  28514. if (this._physicsEngine) {
  28515. return true;
  28516. }
  28517. try {
  28518. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28519. return true;
  28520. }
  28521. catch (e) {
  28522. BABYLON.Tools.Error(e.message);
  28523. return false;
  28524. }
  28525. };
  28526. /**
  28527. * Disables and disposes the physics engine associated with the scene
  28528. */
  28529. Scene.prototype.disablePhysicsEngine = function () {
  28530. if (!this._physicsEngine) {
  28531. return;
  28532. }
  28533. this._physicsEngine.dispose();
  28534. this._physicsEngine = null;
  28535. };
  28536. /**
  28537. * Gets a boolean indicating if there is an active physics engine
  28538. * @returns a boolean indicating if there is an active physics engine
  28539. */
  28540. Scene.prototype.isPhysicsEnabled = function () {
  28541. return this._physicsEngine !== undefined;
  28542. };
  28543. /**
  28544. * Deletes a physics compound impostor
  28545. * @param compound defines the compound to delete
  28546. */
  28547. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28548. var mesh = compound.parts[0].mesh;
  28549. if (mesh.physicsImpostor) {
  28550. mesh.physicsImpostor.dispose( /*true*/);
  28551. mesh.physicsImpostor = null;
  28552. }
  28553. };
  28554. // Misc.
  28555. /** @hidden */
  28556. Scene.prototype._rebuildGeometries = function () {
  28557. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28558. var geometry = _a[_i];
  28559. geometry._rebuild();
  28560. }
  28561. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28562. var mesh = _c[_b];
  28563. mesh._rebuild();
  28564. }
  28565. if (this.postProcessManager) {
  28566. this.postProcessManager._rebuild();
  28567. }
  28568. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28569. var component = _e[_d];
  28570. component.rebuild();
  28571. }
  28572. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28573. var system = _g[_f];
  28574. system.rebuild();
  28575. }
  28576. if (this._postProcessRenderPipelineManager) {
  28577. this._postProcessRenderPipelineManager._rebuild();
  28578. }
  28579. };
  28580. /** @hidden */
  28581. Scene.prototype._rebuildTextures = function () {
  28582. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28583. var texture = _a[_i];
  28584. texture._rebuild();
  28585. }
  28586. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28587. };
  28588. /**
  28589. * Creates a default light for the scene.
  28590. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28591. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28592. */
  28593. Scene.prototype.createDefaultLight = function (replace) {
  28594. if (replace === void 0) { replace = false; }
  28595. // Dispose existing light in replace mode.
  28596. if (replace) {
  28597. if (this.lights) {
  28598. for (var i = 0; i < this.lights.length; i++) {
  28599. this.lights[i].dispose();
  28600. }
  28601. }
  28602. }
  28603. // Light
  28604. if (this.lights.length === 0) {
  28605. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28606. }
  28607. };
  28608. /**
  28609. * Creates a default camera for the scene.
  28610. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28611. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28612. * @param replace has default false, when true replaces the active camera in the scene
  28613. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28614. */
  28615. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28616. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28617. if (replace === void 0) { replace = false; }
  28618. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28619. // Dispose existing camera in replace mode.
  28620. if (replace) {
  28621. if (this.activeCamera) {
  28622. this.activeCamera.dispose();
  28623. this.activeCamera = null;
  28624. }
  28625. }
  28626. // Camera
  28627. if (!this.activeCamera) {
  28628. var worldExtends = this.getWorldExtends();
  28629. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28630. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28631. var camera;
  28632. var radius = worldSize.length() * 1.5;
  28633. // empty scene scenario!
  28634. if (!isFinite(radius)) {
  28635. radius = 1;
  28636. worldCenter.copyFromFloats(0, 0, 0);
  28637. }
  28638. if (createArcRotateCamera) {
  28639. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28640. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28641. arcRotateCamera.wheelPrecision = 100 / radius;
  28642. camera = arcRotateCamera;
  28643. }
  28644. else {
  28645. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28646. freeCamera.setTarget(worldCenter);
  28647. camera = freeCamera;
  28648. }
  28649. camera.minZ = radius * 0.01;
  28650. camera.maxZ = radius * 1000;
  28651. camera.speed = radius * 0.2;
  28652. this.activeCamera = camera;
  28653. var canvas = this.getEngine().getRenderingCanvas();
  28654. if (attachCameraControls && canvas) {
  28655. camera.attachControl(canvas);
  28656. }
  28657. }
  28658. };
  28659. /**
  28660. * Creates a default camera and a default light.
  28661. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28662. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28663. * @param replace has the default false, when true replaces the active camera/light in the scene
  28664. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28665. */
  28666. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28667. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28668. if (replace === void 0) { replace = false; }
  28669. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28670. this.createDefaultLight(replace);
  28671. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28672. };
  28673. /**
  28674. * Creates a new sky box
  28675. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28676. * @param environmentTexture defines the texture to use as environment texture
  28677. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28678. * @param scale defines the overall scale of the skybox
  28679. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28680. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28681. * @returns a new mesh holding the sky box
  28682. */
  28683. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28684. if (pbr === void 0) { pbr = false; }
  28685. if (scale === void 0) { scale = 1000; }
  28686. if (blur === void 0) { blur = 0; }
  28687. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28688. if (!environmentTexture) {
  28689. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28690. return null;
  28691. }
  28692. if (setGlobalEnvTexture) {
  28693. if (environmentTexture) {
  28694. this.environmentTexture = environmentTexture;
  28695. }
  28696. }
  28697. // Skybox
  28698. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28699. if (pbr) {
  28700. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28701. hdrSkyboxMaterial.backFaceCulling = false;
  28702. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28703. if (hdrSkyboxMaterial.reflectionTexture) {
  28704. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28705. }
  28706. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28707. hdrSkyboxMaterial.disableLighting = true;
  28708. hdrSkyboxMaterial.twoSidedLighting = true;
  28709. hdrSkybox.infiniteDistance = true;
  28710. hdrSkybox.material = hdrSkyboxMaterial;
  28711. }
  28712. else {
  28713. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28714. skyboxMaterial.backFaceCulling = false;
  28715. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28716. if (skyboxMaterial.reflectionTexture) {
  28717. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28718. }
  28719. skyboxMaterial.disableLighting = true;
  28720. hdrSkybox.infiniteDistance = true;
  28721. hdrSkybox.material = skyboxMaterial;
  28722. }
  28723. return hdrSkybox;
  28724. };
  28725. /**
  28726. * Creates a new environment
  28727. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28728. * @param options defines the options you can use to configure the environment
  28729. * @returns the new EnvironmentHelper
  28730. */
  28731. Scene.prototype.createDefaultEnvironment = function (options) {
  28732. if (BABYLON.EnvironmentHelper) {
  28733. return new BABYLON.EnvironmentHelper(options, this);
  28734. }
  28735. return null;
  28736. };
  28737. /**
  28738. * Creates a new VREXperienceHelper
  28739. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28740. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28741. * @returns a new VREXperienceHelper
  28742. */
  28743. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28744. if (webVROptions === void 0) { webVROptions = {}; }
  28745. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28746. };
  28747. // Tags
  28748. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28749. if (tagsQuery === undefined) {
  28750. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28751. return list;
  28752. }
  28753. var listByTags = [];
  28754. forEach = forEach || (function (item) { return; });
  28755. for (var i in list) {
  28756. var item = list[i];
  28757. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28758. listByTags.push(item);
  28759. forEach(item);
  28760. }
  28761. }
  28762. return listByTags;
  28763. };
  28764. /**
  28765. * Get a list of meshes by tags
  28766. * @param tagsQuery defines the tags query to use
  28767. * @param forEach defines a predicate used to filter results
  28768. * @returns an array of Mesh
  28769. */
  28770. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28771. return this._getByTags(this.meshes, tagsQuery, forEach);
  28772. };
  28773. /**
  28774. * Get a list of cameras by tags
  28775. * @param tagsQuery defines the tags query to use
  28776. * @param forEach defines a predicate used to filter results
  28777. * @returns an array of Camera
  28778. */
  28779. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28780. return this._getByTags(this.cameras, tagsQuery, forEach);
  28781. };
  28782. /**
  28783. * Get a list of lights by tags
  28784. * @param tagsQuery defines the tags query to use
  28785. * @param forEach defines a predicate used to filter results
  28786. * @returns an array of Light
  28787. */
  28788. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28789. return this._getByTags(this.lights, tagsQuery, forEach);
  28790. };
  28791. /**
  28792. * Get a list of materials by tags
  28793. * @param tagsQuery defines the tags query to use
  28794. * @param forEach defines a predicate used to filter results
  28795. * @returns an array of Material
  28796. */
  28797. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28798. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28799. };
  28800. /**
  28801. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28802. * This allowed control for front to back rendering or reversly depending of the special needs.
  28803. *
  28804. * @param renderingGroupId The rendering group id corresponding to its index
  28805. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28806. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28807. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28808. */
  28809. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28810. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28811. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28812. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28813. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28814. };
  28815. /**
  28816. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28817. *
  28818. * @param renderingGroupId The rendering group id corresponding to its index
  28819. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28820. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28821. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28822. */
  28823. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28824. if (depth === void 0) { depth = true; }
  28825. if (stencil === void 0) { stencil = true; }
  28826. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28827. };
  28828. /**
  28829. * Gets the current auto clear configuration for one rendering group of the rendering
  28830. * manager.
  28831. * @param index the rendering group index to get the information for
  28832. * @returns The auto clear setup for the requested rendering group
  28833. */
  28834. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28835. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28836. };
  28837. /**
  28838. * Will flag all materials as dirty to trigger new shader compilation
  28839. * @param flag defines the flag used to specify which material part must be marked as dirty
  28840. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28841. */
  28842. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28843. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28844. var material = _a[_i];
  28845. if (predicate && !predicate(material)) {
  28846. continue;
  28847. }
  28848. material.markAsDirty(flag);
  28849. }
  28850. };
  28851. /** @hidden */
  28852. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28853. var _this = this;
  28854. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28855. this._activeRequests.push(request);
  28856. request.onCompleteObservable.add(function (request) {
  28857. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28858. });
  28859. return request;
  28860. };
  28861. /** @hidden */
  28862. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28863. var _this = this;
  28864. return new Promise(function (resolve, reject) {
  28865. _this._loadFile(url, function (data) {
  28866. resolve(data);
  28867. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28868. reject(exception);
  28869. });
  28870. });
  28871. };
  28872. // Statics
  28873. Scene._FOGMODE_NONE = 0;
  28874. Scene._FOGMODE_EXP = 1;
  28875. Scene._FOGMODE_EXP2 = 2;
  28876. Scene._FOGMODE_LINEAR = 3;
  28877. Scene._uniqueIdCounter = 0;
  28878. /**
  28879. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28880. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28881. */
  28882. Scene.MinDeltaTime = 1.0;
  28883. /**
  28884. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28885. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28886. */
  28887. Scene.MaxDeltaTime = 1000.0;
  28888. /** The distance in pixel that you have to move to prevent some events */
  28889. Scene.DragMovementThreshold = 10; // in pixels
  28890. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28891. Scene.LongPressDelay = 500; // in milliseconds
  28892. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28893. Scene.DoubleClickDelay = 300; // in milliseconds
  28894. /** If you need to check double click without raising a single click at first click, enable this flag */
  28895. Scene.ExclusiveDoubleClickMode = false;
  28896. return Scene;
  28897. }(BABYLON.AbstractScene));
  28898. BABYLON.Scene = Scene;
  28899. })(BABYLON || (BABYLON = {}));
  28900. //# sourceMappingURL=babylon.scene.js.map
  28901. var BABYLON;
  28902. (function (BABYLON) {
  28903. /**
  28904. * Set of assets to keep when moving a scene into an asset container.
  28905. */
  28906. var KeepAssets = /** @class */ (function (_super) {
  28907. __extends(KeepAssets, _super);
  28908. function KeepAssets() {
  28909. return _super !== null && _super.apply(this, arguments) || this;
  28910. }
  28911. return KeepAssets;
  28912. }(BABYLON.AbstractScene));
  28913. BABYLON.KeepAssets = KeepAssets;
  28914. /**
  28915. * Container with a set of assets that can be added or removed from a scene.
  28916. */
  28917. var AssetContainer = /** @class */ (function (_super) {
  28918. __extends(AssetContainer, _super);
  28919. /**
  28920. * Instantiates an AssetContainer.
  28921. * @param scene The scene the AssetContainer belongs to.
  28922. */
  28923. function AssetContainer(scene) {
  28924. var _this = _super.call(this) || this;
  28925. _this.scene = scene;
  28926. return _this;
  28927. }
  28928. /**
  28929. * Adds all the assets from the container to the scene.
  28930. */
  28931. AssetContainer.prototype.addAllToScene = function () {
  28932. var _this = this;
  28933. this.cameras.forEach(function (o) {
  28934. _this.scene.addCamera(o);
  28935. });
  28936. this.lights.forEach(function (o) {
  28937. _this.scene.addLight(o);
  28938. });
  28939. this.meshes.forEach(function (o) {
  28940. _this.scene.addMesh(o);
  28941. });
  28942. this.skeletons.forEach(function (o) {
  28943. _this.scene.addSkeleton(o);
  28944. });
  28945. this.animations.forEach(function (o) {
  28946. _this.scene.addAnimation(o);
  28947. });
  28948. this.animationGroups.forEach(function (o) {
  28949. _this.scene.addAnimationGroup(o);
  28950. });
  28951. this.multiMaterials.forEach(function (o) {
  28952. _this.scene.addMultiMaterial(o);
  28953. });
  28954. this.materials.forEach(function (o) {
  28955. _this.scene.addMaterial(o);
  28956. });
  28957. this.morphTargetManagers.forEach(function (o) {
  28958. _this.scene.addMorphTargetManager(o);
  28959. });
  28960. this.geometries.forEach(function (o) {
  28961. _this.scene.addGeometry(o);
  28962. });
  28963. this.transformNodes.forEach(function (o) {
  28964. _this.scene.addTransformNode(o);
  28965. });
  28966. this.actionManagers.forEach(function (o) {
  28967. _this.scene.addActionManager(o);
  28968. });
  28969. this.sounds.forEach(function (o) {
  28970. o.play();
  28971. o.autoplay = true;
  28972. _this.scene.mainSoundTrack.AddSound(o);
  28973. });
  28974. this.textures.forEach(function (o) {
  28975. _this.scene.addTexture(o);
  28976. });
  28977. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28978. var component = _a[_i];
  28979. component.addFromContainer(this.scene);
  28980. }
  28981. };
  28982. /**
  28983. * Removes all the assets in the container from the scene
  28984. */
  28985. AssetContainer.prototype.removeAllFromScene = function () {
  28986. var _this = this;
  28987. this.cameras.forEach(function (o) {
  28988. _this.scene.removeCamera(o);
  28989. });
  28990. this.lights.forEach(function (o) {
  28991. _this.scene.removeLight(o);
  28992. });
  28993. this.meshes.forEach(function (o) {
  28994. _this.scene.removeMesh(o);
  28995. });
  28996. this.skeletons.forEach(function (o) {
  28997. _this.scene.removeSkeleton(o);
  28998. });
  28999. this.animations.forEach(function (o) {
  29000. _this.scene.removeAnimation(o);
  29001. });
  29002. this.animationGroups.forEach(function (o) {
  29003. _this.scene.removeAnimationGroup(o);
  29004. });
  29005. this.multiMaterials.forEach(function (o) {
  29006. _this.scene.removeMultiMaterial(o);
  29007. });
  29008. this.materials.forEach(function (o) {
  29009. _this.scene.removeMaterial(o);
  29010. });
  29011. this.morphTargetManagers.forEach(function (o) {
  29012. _this.scene.removeMorphTargetManager(o);
  29013. });
  29014. this.geometries.forEach(function (o) {
  29015. _this.scene.removeGeometry(o);
  29016. });
  29017. this.transformNodes.forEach(function (o) {
  29018. _this.scene.removeTransformNode(o);
  29019. });
  29020. this.actionManagers.forEach(function (o) {
  29021. _this.scene.removeActionManager(o);
  29022. });
  29023. this.sounds.forEach(function (o) {
  29024. o.stop();
  29025. o.autoplay = false;
  29026. _this.scene.mainSoundTrack.RemoveSound(o);
  29027. });
  29028. this.textures.forEach(function (o) {
  29029. _this.scene.removeTexture(o);
  29030. });
  29031. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29032. var component = _a[_i];
  29033. component.removeFromContainer(this.scene);
  29034. }
  29035. };
  29036. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29037. if (!sourceAssets) {
  29038. return;
  29039. }
  29040. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29041. var asset = sourceAssets_1[_i];
  29042. var move = true;
  29043. if (keepAssets) {
  29044. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29045. var keepAsset = keepAssets_1[_a];
  29046. if (asset === keepAsset) {
  29047. move = false;
  29048. break;
  29049. }
  29050. }
  29051. }
  29052. if (move) {
  29053. targetAssets.push(asset);
  29054. }
  29055. }
  29056. };
  29057. /**
  29058. * Removes all the assets contained in the scene and adds them to the container.
  29059. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29060. */
  29061. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29062. if (keepAssets === undefined) {
  29063. keepAssets = new KeepAssets();
  29064. }
  29065. for (var key in this) {
  29066. if (this.hasOwnProperty(key)) {
  29067. this[key] = this[key] || [];
  29068. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29069. }
  29070. }
  29071. this.removeAllFromScene();
  29072. };
  29073. /**
  29074. * 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.
  29075. * @returns the root mesh
  29076. */
  29077. AssetContainer.prototype.createRootMesh = function () {
  29078. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29079. this.meshes.forEach(function (m) {
  29080. if (!m.parent) {
  29081. rootMesh.addChild(m);
  29082. }
  29083. });
  29084. this.meshes.unshift(rootMesh);
  29085. return rootMesh;
  29086. };
  29087. return AssetContainer;
  29088. }(BABYLON.AbstractScene));
  29089. BABYLON.AssetContainer = AssetContainer;
  29090. })(BABYLON || (BABYLON = {}));
  29091. //# sourceMappingURL=babylon.assetContainer.js.map
  29092. var BABYLON;
  29093. (function (BABYLON) {
  29094. var Buffer = /** @class */ (function () {
  29095. /**
  29096. * Constructor
  29097. * @param engine the engine
  29098. * @param data the data to use for this buffer
  29099. * @param updatable whether the data is updatable
  29100. * @param stride the stride (optional)
  29101. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29102. * @param instanced whether the buffer is instanced (optional)
  29103. * @param useBytes set to true if the stride in in bytes (optional)
  29104. */
  29105. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29106. if (stride === void 0) { stride = 0; }
  29107. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29108. if (instanced === void 0) { instanced = false; }
  29109. if (useBytes === void 0) { useBytes = false; }
  29110. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29111. this._engine = engine.getScene().getEngine();
  29112. }
  29113. else {
  29114. this._engine = engine;
  29115. }
  29116. this._updatable = updatable;
  29117. this._instanced = instanced;
  29118. this._data = data;
  29119. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29120. if (!postponeInternalCreation) { // by default
  29121. this.create();
  29122. }
  29123. }
  29124. /**
  29125. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29126. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29127. * @param offset defines offset in the buffer (0 by default)
  29128. * @param size defines the size in floats of attributes (position is 3 for instance)
  29129. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29130. * @param instanced defines if the vertex buffer contains indexed data
  29131. * @param useBytes defines if the offset and stride are in bytes
  29132. * @returns the new vertex buffer
  29133. */
  29134. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29135. if (useBytes === void 0) { useBytes = false; }
  29136. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29137. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29138. // a lot of these parameters are ignored as they are overriden by the buffer
  29139. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29140. };
  29141. // Properties
  29142. Buffer.prototype.isUpdatable = function () {
  29143. return this._updatable;
  29144. };
  29145. Buffer.prototype.getData = function () {
  29146. return this._data;
  29147. };
  29148. Buffer.prototype.getBuffer = function () {
  29149. return this._buffer;
  29150. };
  29151. /**
  29152. * Gets the stride in float32 units (i.e. byte stride / 4).
  29153. * May not be an integer if the byte stride is not divisible by 4.
  29154. * DEPRECATED. Use byteStride instead.
  29155. * @returns the stride in float32 units
  29156. */
  29157. Buffer.prototype.getStrideSize = function () {
  29158. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29159. };
  29160. // Methods
  29161. Buffer.prototype.create = function (data) {
  29162. if (data === void 0) { data = null; }
  29163. if (!data && this._buffer) {
  29164. return; // nothing to do
  29165. }
  29166. data = data || this._data;
  29167. if (!data) {
  29168. return;
  29169. }
  29170. if (!this._buffer) { // create buffer
  29171. if (this._updatable) {
  29172. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29173. this._data = data;
  29174. }
  29175. else {
  29176. this._buffer = this._engine.createVertexBuffer(data);
  29177. }
  29178. }
  29179. else if (this._updatable) { // update buffer
  29180. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29181. this._data = data;
  29182. }
  29183. };
  29184. Buffer.prototype._rebuild = function () {
  29185. this._buffer = null;
  29186. this.create(this._data);
  29187. };
  29188. Buffer.prototype.update = function (data) {
  29189. this.create(data);
  29190. };
  29191. /**
  29192. * Updates the data directly.
  29193. * @param data the new data
  29194. * @param offset the new offset
  29195. * @param vertexCount the vertex count (optional)
  29196. * @param useBytes set to true if the offset is in bytes
  29197. */
  29198. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29199. if (useBytes === void 0) { useBytes = false; }
  29200. if (!this._buffer) {
  29201. return;
  29202. }
  29203. if (this._updatable) { // update buffer
  29204. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29205. this._data = null;
  29206. }
  29207. };
  29208. Buffer.prototype.dispose = function () {
  29209. if (!this._buffer) {
  29210. return;
  29211. }
  29212. if (this._engine._releaseBuffer(this._buffer)) {
  29213. this._buffer = null;
  29214. }
  29215. };
  29216. return Buffer;
  29217. }());
  29218. BABYLON.Buffer = Buffer;
  29219. })(BABYLON || (BABYLON = {}));
  29220. //# sourceMappingURL=babylon.buffer.js.map
  29221. var BABYLON;
  29222. (function (BABYLON) {
  29223. var VertexBuffer = /** @class */ (function () {
  29224. /**
  29225. * Constructor
  29226. * @param engine the engine
  29227. * @param data the data to use for this vertex buffer
  29228. * @param kind the vertex buffer kind
  29229. * @param updatable whether the data is updatable
  29230. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29231. * @param stride the stride (optional)
  29232. * @param instanced whether the buffer is instanced (optional)
  29233. * @param offset the offset of the data (optional)
  29234. * @param size the number of components (optional)
  29235. * @param type the type of the component (optional)
  29236. * @param normalized whether the data contains normalized data (optional)
  29237. * @param useBytes set to true if stride and offset are in bytes (optional)
  29238. */
  29239. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29240. if (normalized === void 0) { normalized = false; }
  29241. if (useBytes === void 0) { useBytes = false; }
  29242. if (data instanceof BABYLON.Buffer) {
  29243. this._buffer = data;
  29244. this._ownsBuffer = false;
  29245. }
  29246. else {
  29247. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29248. this._ownsBuffer = true;
  29249. }
  29250. this._kind = kind;
  29251. if (type == undefined) {
  29252. var data_1 = this.getData();
  29253. this.type = VertexBuffer.FLOAT;
  29254. if (data_1 instanceof Int8Array)
  29255. this.type = VertexBuffer.BYTE;
  29256. else if (data_1 instanceof Uint8Array)
  29257. this.type = VertexBuffer.UNSIGNED_BYTE;
  29258. else if (data_1 instanceof Int16Array)
  29259. this.type = VertexBuffer.SHORT;
  29260. else if (data_1 instanceof Uint16Array)
  29261. this.type = VertexBuffer.UNSIGNED_SHORT;
  29262. else if (data_1 instanceof Int32Array)
  29263. this.type = VertexBuffer.INT;
  29264. else if (data_1 instanceof Uint32Array)
  29265. this.type = VertexBuffer.UNSIGNED_INT;
  29266. }
  29267. else {
  29268. this.type = type;
  29269. }
  29270. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29271. if (useBytes) {
  29272. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29273. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29274. this.byteOffset = offset || 0;
  29275. }
  29276. else {
  29277. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29278. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29279. this.byteOffset = (offset || 0) * typeByteLength;
  29280. }
  29281. this.normalized = normalized;
  29282. this._instanced = instanced !== undefined ? instanced : false;
  29283. this._instanceDivisor = instanced ? 1 : 0;
  29284. }
  29285. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29286. /**
  29287. * Gets or sets the instance divisor when in instanced mode
  29288. */
  29289. get: function () {
  29290. return this._instanceDivisor;
  29291. },
  29292. set: function (value) {
  29293. this._instanceDivisor = value;
  29294. if (value == 0) {
  29295. this._instanced = false;
  29296. }
  29297. else {
  29298. this._instanced = true;
  29299. }
  29300. },
  29301. enumerable: true,
  29302. configurable: true
  29303. });
  29304. VertexBuffer.prototype._rebuild = function () {
  29305. if (!this._buffer) {
  29306. return;
  29307. }
  29308. this._buffer._rebuild();
  29309. };
  29310. /**
  29311. * Returns the kind of the VertexBuffer (string).
  29312. */
  29313. VertexBuffer.prototype.getKind = function () {
  29314. return this._kind;
  29315. };
  29316. // Properties
  29317. /**
  29318. * Boolean : is the VertexBuffer updatable ?
  29319. */
  29320. VertexBuffer.prototype.isUpdatable = function () {
  29321. return this._buffer.isUpdatable();
  29322. };
  29323. /**
  29324. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29325. */
  29326. VertexBuffer.prototype.getData = function () {
  29327. return this._buffer.getData();
  29328. };
  29329. /**
  29330. * Returns the WebGLBuffer associated to the VertexBuffer.
  29331. */
  29332. VertexBuffer.prototype.getBuffer = function () {
  29333. return this._buffer.getBuffer();
  29334. };
  29335. /**
  29336. * Returns the stride as a multiple of the type byte length.
  29337. * DEPRECATED. Use byteStride instead.
  29338. */
  29339. VertexBuffer.prototype.getStrideSize = function () {
  29340. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29341. };
  29342. /**
  29343. * Returns the offset as a multiple of the type byte length.
  29344. * DEPRECATED. Use byteOffset instead.
  29345. */
  29346. VertexBuffer.prototype.getOffset = function () {
  29347. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29348. };
  29349. /**
  29350. * Returns the number of components per vertex attribute (integer).
  29351. */
  29352. VertexBuffer.prototype.getSize = function () {
  29353. return this._size;
  29354. };
  29355. /**
  29356. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29357. */
  29358. VertexBuffer.prototype.getIsInstanced = function () {
  29359. return this._instanced;
  29360. };
  29361. /**
  29362. * Returns the instancing divisor, zero for non-instanced (integer).
  29363. */
  29364. VertexBuffer.prototype.getInstanceDivisor = function () {
  29365. return this._instanceDivisor;
  29366. };
  29367. // Methods
  29368. /**
  29369. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29370. * Returns the created WebGLBuffer.
  29371. */
  29372. VertexBuffer.prototype.create = function (data) {
  29373. return this._buffer.create(data);
  29374. };
  29375. /**
  29376. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29377. * This function will create a new buffer if the current one is not updatable
  29378. * Returns the updated WebGLBuffer.
  29379. */
  29380. VertexBuffer.prototype.update = function (data) {
  29381. return this._buffer.update(data);
  29382. };
  29383. /**
  29384. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29385. * Returns the directly updated WebGLBuffer.
  29386. * @param data the new data
  29387. * @param offset the new offset
  29388. * @param useBytes set to true if the offset is in bytes
  29389. */
  29390. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29391. if (useBytes === void 0) { useBytes = false; }
  29392. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29393. };
  29394. /**
  29395. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29396. */
  29397. VertexBuffer.prototype.dispose = function () {
  29398. if (this._ownsBuffer) {
  29399. this._buffer.dispose();
  29400. }
  29401. };
  29402. /**
  29403. * Enumerates each value of this vertex buffer as numbers.
  29404. * @param count the number of values to enumerate
  29405. * @param callback the callback function called for each value
  29406. */
  29407. VertexBuffer.prototype.forEach = function (count, callback) {
  29408. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29409. };
  29410. Object.defineProperty(VertexBuffer, "PositionKind", {
  29411. get: function () {
  29412. return VertexBuffer._PositionKind;
  29413. },
  29414. enumerable: true,
  29415. configurable: true
  29416. });
  29417. Object.defineProperty(VertexBuffer, "NormalKind", {
  29418. get: function () {
  29419. return VertexBuffer._NormalKind;
  29420. },
  29421. enumerable: true,
  29422. configurable: true
  29423. });
  29424. Object.defineProperty(VertexBuffer, "TangentKind", {
  29425. get: function () {
  29426. return VertexBuffer._TangentKind;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(VertexBuffer, "UVKind", {
  29432. get: function () {
  29433. return VertexBuffer._UVKind;
  29434. },
  29435. enumerable: true,
  29436. configurable: true
  29437. });
  29438. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29439. get: function () {
  29440. return VertexBuffer._UV2Kind;
  29441. },
  29442. enumerable: true,
  29443. configurable: true
  29444. });
  29445. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29446. get: function () {
  29447. return VertexBuffer._UV3Kind;
  29448. },
  29449. enumerable: true,
  29450. configurable: true
  29451. });
  29452. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29453. get: function () {
  29454. return VertexBuffer._UV4Kind;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29460. get: function () {
  29461. return VertexBuffer._UV5Kind;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29467. get: function () {
  29468. return VertexBuffer._UV6Kind;
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. Object.defineProperty(VertexBuffer, "ColorKind", {
  29474. get: function () {
  29475. return VertexBuffer._ColorKind;
  29476. },
  29477. enumerable: true,
  29478. configurable: true
  29479. });
  29480. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29481. get: function () {
  29482. return VertexBuffer._MatricesIndicesKind;
  29483. },
  29484. enumerable: true,
  29485. configurable: true
  29486. });
  29487. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29488. get: function () {
  29489. return VertexBuffer._MatricesWeightsKind;
  29490. },
  29491. enumerable: true,
  29492. configurable: true
  29493. });
  29494. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29495. get: function () {
  29496. return VertexBuffer._MatricesIndicesExtraKind;
  29497. },
  29498. enumerable: true,
  29499. configurable: true
  29500. });
  29501. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29502. get: function () {
  29503. return VertexBuffer._MatricesWeightsExtraKind;
  29504. },
  29505. enumerable: true,
  29506. configurable: true
  29507. });
  29508. /**
  29509. * Deduces the stride given a kind.
  29510. * @param kind The kind string to deduce
  29511. * @returns The deduced stride
  29512. */
  29513. VertexBuffer.DeduceStride = function (kind) {
  29514. switch (kind) {
  29515. case VertexBuffer.UVKind:
  29516. case VertexBuffer.UV2Kind:
  29517. case VertexBuffer.UV3Kind:
  29518. case VertexBuffer.UV4Kind:
  29519. case VertexBuffer.UV5Kind:
  29520. case VertexBuffer.UV6Kind:
  29521. return 2;
  29522. case VertexBuffer.NormalKind:
  29523. case VertexBuffer.PositionKind:
  29524. return 3;
  29525. case VertexBuffer.ColorKind:
  29526. case VertexBuffer.MatricesIndicesKind:
  29527. case VertexBuffer.MatricesIndicesExtraKind:
  29528. case VertexBuffer.MatricesWeightsKind:
  29529. case VertexBuffer.MatricesWeightsExtraKind:
  29530. case VertexBuffer.TangentKind:
  29531. return 4;
  29532. default:
  29533. throw new Error("Invalid kind '" + kind + "'");
  29534. }
  29535. };
  29536. /**
  29537. * Gets the byte length of the given type.
  29538. * @param type the type
  29539. * @returns the number of bytes
  29540. */
  29541. VertexBuffer.GetTypeByteLength = function (type) {
  29542. switch (type) {
  29543. case VertexBuffer.BYTE:
  29544. case VertexBuffer.UNSIGNED_BYTE:
  29545. return 1;
  29546. case VertexBuffer.SHORT:
  29547. case VertexBuffer.UNSIGNED_SHORT:
  29548. return 2;
  29549. case VertexBuffer.INT:
  29550. case VertexBuffer.FLOAT:
  29551. return 4;
  29552. default:
  29553. throw new Error("Invalid type '" + type + "'");
  29554. }
  29555. };
  29556. /**
  29557. * Enumerates each value of the given parameters as numbers.
  29558. * @param data the data to enumerate
  29559. * @param byteOffset the byte offset of the data
  29560. * @param byteStride the byte stride of the data
  29561. * @param componentCount the number of components per element
  29562. * @param componentType the type of the component
  29563. * @param count the total number of components
  29564. * @param normalized whether the data is normalized
  29565. * @param callback the callback function called for each value
  29566. */
  29567. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29568. if (data instanceof Array) {
  29569. var offset = byteOffset / 4;
  29570. var stride = byteStride / 4;
  29571. for (var index = 0; index < count; index += componentCount) {
  29572. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29573. callback(data[offset + componentIndex], index + componentIndex);
  29574. }
  29575. offset += stride;
  29576. }
  29577. }
  29578. else {
  29579. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29580. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29581. for (var index = 0; index < count; index += componentCount) {
  29582. var componentByteOffset = byteOffset;
  29583. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29584. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29585. callback(value, index + componentIndex);
  29586. componentByteOffset += componentByteLength;
  29587. }
  29588. byteOffset += byteStride;
  29589. }
  29590. }
  29591. };
  29592. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29593. switch (type) {
  29594. case VertexBuffer.BYTE: {
  29595. var value = dataView.getInt8(byteOffset);
  29596. if (normalized) {
  29597. value = Math.max(value / 127, -1);
  29598. }
  29599. return value;
  29600. }
  29601. case VertexBuffer.UNSIGNED_BYTE: {
  29602. var value = dataView.getUint8(byteOffset);
  29603. if (normalized) {
  29604. value = value / 255;
  29605. }
  29606. return value;
  29607. }
  29608. case VertexBuffer.SHORT: {
  29609. var value = dataView.getInt16(byteOffset, true);
  29610. if (normalized) {
  29611. value = Math.max(value / 16383, -1);
  29612. }
  29613. return value;
  29614. }
  29615. case VertexBuffer.UNSIGNED_SHORT: {
  29616. var value = dataView.getUint16(byteOffset, true);
  29617. if (normalized) {
  29618. value = value / 65535;
  29619. }
  29620. return value;
  29621. }
  29622. case VertexBuffer.FLOAT: {
  29623. return dataView.getFloat32(byteOffset, true);
  29624. }
  29625. default: {
  29626. throw new Error("Invalid component type " + type);
  29627. }
  29628. }
  29629. };
  29630. /**
  29631. * The byte type.
  29632. */
  29633. VertexBuffer.BYTE = 5120;
  29634. /**
  29635. * The unsigned byte type.
  29636. */
  29637. VertexBuffer.UNSIGNED_BYTE = 5121;
  29638. /**
  29639. * The short type.
  29640. */
  29641. VertexBuffer.SHORT = 5122;
  29642. /**
  29643. * The unsigned short type.
  29644. */
  29645. VertexBuffer.UNSIGNED_SHORT = 5123;
  29646. /**
  29647. * The integer type.
  29648. */
  29649. VertexBuffer.INT = 5124;
  29650. /**
  29651. * The unsigned integer type.
  29652. */
  29653. VertexBuffer.UNSIGNED_INT = 5125;
  29654. /**
  29655. * The float type.
  29656. */
  29657. VertexBuffer.FLOAT = 5126;
  29658. // Enums
  29659. VertexBuffer._PositionKind = "position";
  29660. VertexBuffer._NormalKind = "normal";
  29661. VertexBuffer._TangentKind = "tangent";
  29662. VertexBuffer._UVKind = "uv";
  29663. VertexBuffer._UV2Kind = "uv2";
  29664. VertexBuffer._UV3Kind = "uv3";
  29665. VertexBuffer._UV4Kind = "uv4";
  29666. VertexBuffer._UV5Kind = "uv5";
  29667. VertexBuffer._UV6Kind = "uv6";
  29668. VertexBuffer._ColorKind = "color";
  29669. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29670. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29671. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29672. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29673. return VertexBuffer;
  29674. }());
  29675. BABYLON.VertexBuffer = VertexBuffer;
  29676. })(BABYLON || (BABYLON = {}));
  29677. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29678. var BABYLON;
  29679. (function (BABYLON) {
  29680. /**
  29681. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29682. */
  29683. var DummyInternalTextureTracker = /** @class */ (function () {
  29684. function DummyInternalTextureTracker() {
  29685. /**
  29686. * Gets or set the previous tracker in the list
  29687. */
  29688. this.previous = null;
  29689. /**
  29690. * Gets or set the next tracker in the list
  29691. */
  29692. this.next = null;
  29693. }
  29694. return DummyInternalTextureTracker;
  29695. }());
  29696. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29697. })(BABYLON || (BABYLON = {}));
  29698. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29699. var BABYLON;
  29700. (function (BABYLON) {
  29701. /**
  29702. * Class used to store data associated with WebGL texture data for the engine
  29703. * This class should not be used directly
  29704. */
  29705. var InternalTexture = /** @class */ (function () {
  29706. /**
  29707. * Creates a new InternalTexture
  29708. * @param engine defines the engine to use
  29709. * @param dataSource defines the type of data that will be used
  29710. */
  29711. function InternalTexture(engine, dataSource) {
  29712. /**
  29713. * Observable called when the texture is loaded
  29714. */
  29715. this.onLoadedObservable = new BABYLON.Observable();
  29716. /**
  29717. * Gets or set the previous tracker in the list
  29718. */
  29719. this.previous = null;
  29720. /**
  29721. * Gets or set the next tracker in the list
  29722. */
  29723. this.next = null;
  29724. // Private
  29725. /** @hidden */
  29726. this._initialSlot = -1;
  29727. /** @hidden */
  29728. this._designatedSlot = -1;
  29729. /** @hidden */
  29730. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29731. /** @hidden */
  29732. this._comparisonFunction = 0;
  29733. /** @hidden */
  29734. this._sphericalPolynomial = null;
  29735. /** @hidden */
  29736. this._lodGenerationScale = 0;
  29737. /** @hidden */
  29738. this._lodGenerationOffset = 0;
  29739. /** @hidden */
  29740. this._isRGBD = false;
  29741. /** @hidden */
  29742. this._references = 1;
  29743. this._engine = engine;
  29744. this._dataSource = dataSource;
  29745. this._webGLTexture = engine._createTexture();
  29746. }
  29747. /**
  29748. * Gets the Engine the texture belongs to.
  29749. * @returns The babylon engine
  29750. */
  29751. InternalTexture.prototype.getEngine = function () {
  29752. return this._engine;
  29753. };
  29754. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29755. /**
  29756. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29757. */
  29758. get: function () {
  29759. return this._dataSource;
  29760. },
  29761. enumerable: true,
  29762. configurable: true
  29763. });
  29764. /**
  29765. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29766. */
  29767. InternalTexture.prototype.incrementReferences = function () {
  29768. this._references++;
  29769. };
  29770. /**
  29771. * Change the size of the texture (not the size of the content)
  29772. * @param width defines the new width
  29773. * @param height defines the new height
  29774. * @param depth defines the new depth (1 by default)
  29775. */
  29776. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29777. if (depth === void 0) { depth = 1; }
  29778. this.width = width;
  29779. this.height = height;
  29780. this.depth = depth;
  29781. this.baseWidth = width;
  29782. this.baseHeight = height;
  29783. this.baseDepth = depth;
  29784. this._size = width * height * depth;
  29785. };
  29786. /** @hidden */
  29787. InternalTexture.prototype._rebuild = function () {
  29788. var _this = this;
  29789. var proxy;
  29790. this.isReady = false;
  29791. this._cachedCoordinatesMode = null;
  29792. this._cachedWrapU = null;
  29793. this._cachedWrapV = null;
  29794. this._cachedAnisotropicFilteringLevel = null;
  29795. switch (this._dataSource) {
  29796. case InternalTexture.DATASOURCE_TEMP:
  29797. return;
  29798. case InternalTexture.DATASOURCE_URL:
  29799. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29800. _this.isReady = true;
  29801. }, null, this._buffer, undefined, this.format);
  29802. proxy._swapAndDie(this);
  29803. return;
  29804. case InternalTexture.DATASOURCE_RAW:
  29805. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29806. proxy._swapAndDie(this);
  29807. this.isReady = true;
  29808. return;
  29809. case InternalTexture.DATASOURCE_RAW3D:
  29810. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29811. proxy._swapAndDie(this);
  29812. this.isReady = true;
  29813. return;
  29814. case InternalTexture.DATASOURCE_DYNAMIC:
  29815. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29816. proxy._swapAndDie(this);
  29817. // The engine will make sure to update content so no need to flag it as isReady = true
  29818. return;
  29819. case InternalTexture.DATASOURCE_RENDERTARGET:
  29820. var options = new BABYLON.RenderTargetCreationOptions();
  29821. options.generateDepthBuffer = this._generateDepthBuffer;
  29822. options.generateMipMaps = this.generateMipMaps;
  29823. options.generateStencilBuffer = this._generateStencilBuffer;
  29824. options.samplingMode = this.samplingMode;
  29825. options.type = this.type;
  29826. if (this.isCube) {
  29827. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29828. }
  29829. else {
  29830. var size = {
  29831. width: this.width,
  29832. height: this.height
  29833. };
  29834. proxy = this._engine.createRenderTargetTexture(size, options);
  29835. }
  29836. proxy._swapAndDie(this);
  29837. this.isReady = true;
  29838. return;
  29839. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29840. var depthTextureOptions = {
  29841. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29842. comparisonFunction: this._comparisonFunction,
  29843. generateStencil: this._generateStencilBuffer,
  29844. isCube: this.isCube
  29845. };
  29846. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29847. proxy._swapAndDie(this);
  29848. this.isReady = true;
  29849. return;
  29850. case InternalTexture.DATASOURCE_CUBE:
  29851. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29852. _this.isReady = true;
  29853. }, null, this.format, this._extension);
  29854. proxy._swapAndDie(this);
  29855. return;
  29856. case InternalTexture.DATASOURCE_CUBERAW:
  29857. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29858. proxy._swapAndDie(this);
  29859. this.isReady = true;
  29860. return;
  29861. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29862. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29863. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29864. _this.isReady = true;
  29865. });
  29866. proxy._swapAndDie(this);
  29867. return;
  29868. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29869. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29870. if (proxy) {
  29871. proxy._swapAndDie(_this);
  29872. }
  29873. _this.isReady = true;
  29874. }, null, this.format, this._extension);
  29875. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29876. return;
  29877. }
  29878. };
  29879. InternalTexture.prototype._swapAndDie = function (target) {
  29880. target._webGLTexture = this._webGLTexture;
  29881. if (this._framebuffer) {
  29882. target._framebuffer = this._framebuffer;
  29883. }
  29884. if (this._depthStencilBuffer) {
  29885. target._depthStencilBuffer = this._depthStencilBuffer;
  29886. }
  29887. if (this._lodTextureHigh) {
  29888. if (target._lodTextureHigh) {
  29889. target._lodTextureHigh.dispose();
  29890. }
  29891. target._lodTextureHigh = this._lodTextureHigh;
  29892. }
  29893. if (this._lodTextureMid) {
  29894. if (target._lodTextureMid) {
  29895. target._lodTextureMid.dispose();
  29896. }
  29897. target._lodTextureMid = this._lodTextureMid;
  29898. }
  29899. if (this._lodTextureLow) {
  29900. if (target._lodTextureLow) {
  29901. target._lodTextureLow.dispose();
  29902. }
  29903. target._lodTextureLow = this._lodTextureLow;
  29904. }
  29905. var cache = this._engine.getLoadedTexturesCache();
  29906. var index = cache.indexOf(this);
  29907. if (index !== -1) {
  29908. cache.splice(index, 1);
  29909. }
  29910. };
  29911. /**
  29912. * Dispose the current allocated resources
  29913. */
  29914. InternalTexture.prototype.dispose = function () {
  29915. if (!this._webGLTexture) {
  29916. return;
  29917. }
  29918. this._references--;
  29919. if (this._references === 0) {
  29920. this._engine._releaseTexture(this);
  29921. this._webGLTexture = null;
  29922. this.previous = null;
  29923. this.next = null;
  29924. }
  29925. };
  29926. /**
  29927. * The source of the texture data is unknown
  29928. */
  29929. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29930. /**
  29931. * Texture data comes from an URL
  29932. */
  29933. InternalTexture.DATASOURCE_URL = 1;
  29934. /**
  29935. * Texture data is only used for temporary storage
  29936. */
  29937. InternalTexture.DATASOURCE_TEMP = 2;
  29938. /**
  29939. * Texture data comes from raw data (ArrayBuffer)
  29940. */
  29941. InternalTexture.DATASOURCE_RAW = 3;
  29942. /**
  29943. * Texture content is dynamic (video or dynamic texture)
  29944. */
  29945. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29946. /**
  29947. * Texture content is generated by rendering to it
  29948. */
  29949. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29950. /**
  29951. * Texture content is part of a multi render target process
  29952. */
  29953. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29954. /**
  29955. * Texture data comes from a cube data file
  29956. */
  29957. InternalTexture.DATASOURCE_CUBE = 7;
  29958. /**
  29959. * Texture data comes from a raw cube data
  29960. */
  29961. InternalTexture.DATASOURCE_CUBERAW = 8;
  29962. /**
  29963. * Texture data come from a prefiltered cube data file
  29964. */
  29965. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29966. /**
  29967. * Texture content is raw 3D data
  29968. */
  29969. InternalTexture.DATASOURCE_RAW3D = 10;
  29970. /**
  29971. * Texture content is a depth texture
  29972. */
  29973. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29974. /**
  29975. * Texture data comes from a raw cube data encoded with RGBD
  29976. */
  29977. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29978. return InternalTexture;
  29979. }());
  29980. BABYLON.InternalTexture = InternalTexture;
  29981. })(BABYLON || (BABYLON = {}));
  29982. //# sourceMappingURL=babylon.internalTexture.js.map
  29983. var BABYLON;
  29984. (function (BABYLON) {
  29985. var BaseTexture = /** @class */ (function () {
  29986. function BaseTexture(scene) {
  29987. this._hasAlpha = false;
  29988. this.getAlphaFromRGB = false;
  29989. this.level = 1;
  29990. this.coordinatesIndex = 0;
  29991. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29992. /**
  29993. * | Value | Type | Description |
  29994. * | ----- | ------------------ | ----------- |
  29995. * | 0 | CLAMP_ADDRESSMODE | |
  29996. * | 1 | WRAP_ADDRESSMODE | |
  29997. * | 2 | MIRROR_ADDRESSMODE | |
  29998. */
  29999. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30000. /**
  30001. * | Value | Type | Description |
  30002. * | ----- | ------------------ | ----------- |
  30003. * | 0 | CLAMP_ADDRESSMODE | |
  30004. * | 1 | WRAP_ADDRESSMODE | |
  30005. * | 2 | MIRROR_ADDRESSMODE | |
  30006. */
  30007. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30008. /**
  30009. * | Value | Type | Description |
  30010. * | ----- | ------------------ | ----------- |
  30011. * | 0 | CLAMP_ADDRESSMODE | |
  30012. * | 1 | WRAP_ADDRESSMODE | |
  30013. * | 2 | MIRROR_ADDRESSMODE | |
  30014. */
  30015. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30016. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30017. this.isCube = false;
  30018. this.is3D = false;
  30019. this.gammaSpace = true;
  30020. this.invertZ = false;
  30021. this.lodLevelInAlpha = false;
  30022. this.isRenderTarget = false;
  30023. this.animations = new Array();
  30024. /**
  30025. * An event triggered when the texture is disposed.
  30026. */
  30027. this.onDisposeObservable = new BABYLON.Observable();
  30028. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30029. this._cachedSize = BABYLON.Size.Zero();
  30030. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30031. if (this._scene) {
  30032. this._scene.textures.push(this);
  30033. }
  30034. this._uid = null;
  30035. }
  30036. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30037. get: function () {
  30038. return this._hasAlpha;
  30039. },
  30040. set: function (value) {
  30041. if (this._hasAlpha === value) {
  30042. return;
  30043. }
  30044. this._hasAlpha = value;
  30045. if (this._scene) {
  30046. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30047. }
  30048. },
  30049. enumerable: true,
  30050. configurable: true
  30051. });
  30052. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30053. get: function () {
  30054. return this._coordinatesMode;
  30055. },
  30056. /**
  30057. * How a texture is mapped.
  30058. *
  30059. * | Value | Type | Description |
  30060. * | ----- | ----------------------------------- | ----------- |
  30061. * | 0 | EXPLICIT_MODE | |
  30062. * | 1 | SPHERICAL_MODE | |
  30063. * | 2 | PLANAR_MODE | |
  30064. * | 3 | CUBIC_MODE | |
  30065. * | 4 | PROJECTION_MODE | |
  30066. * | 5 | SKYBOX_MODE | |
  30067. * | 6 | INVCUBIC_MODE | |
  30068. * | 7 | EQUIRECTANGULAR_MODE | |
  30069. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30070. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30071. */
  30072. set: function (value) {
  30073. if (this._coordinatesMode === value) {
  30074. return;
  30075. }
  30076. this._coordinatesMode = value;
  30077. if (this._scene) {
  30078. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30079. }
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30085. /**
  30086. * Gets whether or not the texture contains RGBD data.
  30087. */
  30088. get: function () {
  30089. return this._texture != null && this._texture._isRGBD;
  30090. },
  30091. enumerable: true,
  30092. configurable: true
  30093. });
  30094. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30095. get: function () {
  30096. if (this._texture)
  30097. return this._texture._lodGenerationOffset;
  30098. return 0.0;
  30099. },
  30100. set: function (value) {
  30101. if (this._texture)
  30102. this._texture._lodGenerationOffset = value;
  30103. },
  30104. enumerable: true,
  30105. configurable: true
  30106. });
  30107. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30108. get: function () {
  30109. if (this._texture)
  30110. return this._texture._lodGenerationScale;
  30111. return 0.0;
  30112. },
  30113. set: function (value) {
  30114. if (this._texture)
  30115. this._texture._lodGenerationScale = value;
  30116. },
  30117. enumerable: true,
  30118. configurable: true
  30119. });
  30120. Object.defineProperty(BaseTexture.prototype, "uid", {
  30121. get: function () {
  30122. if (!this._uid) {
  30123. this._uid = BABYLON.Tools.RandomId();
  30124. }
  30125. return this._uid;
  30126. },
  30127. enumerable: true,
  30128. configurable: true
  30129. });
  30130. BaseTexture.prototype.toString = function () {
  30131. return this.name;
  30132. };
  30133. BaseTexture.prototype.getClassName = function () {
  30134. return "BaseTexture";
  30135. };
  30136. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30137. set: function (callback) {
  30138. if (this._onDisposeObserver) {
  30139. this.onDisposeObservable.remove(this._onDisposeObserver);
  30140. }
  30141. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30147. get: function () {
  30148. return true;
  30149. },
  30150. enumerable: true,
  30151. configurable: true
  30152. });
  30153. BaseTexture.prototype.getScene = function () {
  30154. return this._scene;
  30155. };
  30156. BaseTexture.prototype.getTextureMatrix = function () {
  30157. return BABYLON.Matrix.IdentityReadOnly;
  30158. };
  30159. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30160. return BABYLON.Matrix.IdentityReadOnly;
  30161. };
  30162. BaseTexture.prototype.getInternalTexture = function () {
  30163. return this._texture;
  30164. };
  30165. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30166. return !this.isBlocking || this.isReady();
  30167. };
  30168. BaseTexture.prototype.isReady = function () {
  30169. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30170. this.delayLoad();
  30171. return false;
  30172. }
  30173. if (this._texture) {
  30174. return this._texture.isReady;
  30175. }
  30176. return false;
  30177. };
  30178. BaseTexture.prototype.getSize = function () {
  30179. if (this._texture) {
  30180. if (this._texture.width) {
  30181. this._cachedSize.width = this._texture.width;
  30182. this._cachedSize.height = this._texture.height;
  30183. return this._cachedSize;
  30184. }
  30185. if (this._texture._size) {
  30186. this._cachedSize.width = this._texture._size;
  30187. this._cachedSize.height = this._texture._size;
  30188. return this._cachedSize;
  30189. }
  30190. }
  30191. return this._cachedSize;
  30192. };
  30193. BaseTexture.prototype.getBaseSize = function () {
  30194. if (!this.isReady() || !this._texture)
  30195. return BABYLON.Size.Zero();
  30196. if (this._texture._size) {
  30197. return new BABYLON.Size(this._texture._size, this._texture._size);
  30198. }
  30199. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30200. };
  30201. BaseTexture.prototype.scale = function (ratio) {
  30202. };
  30203. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30204. get: function () {
  30205. return false;
  30206. },
  30207. enumerable: true,
  30208. configurable: true
  30209. });
  30210. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30211. if (!this._scene) {
  30212. return null;
  30213. }
  30214. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30215. for (var index = 0; index < texturesCache.length; index++) {
  30216. var texturesCacheEntry = texturesCache[index];
  30217. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30218. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30219. texturesCacheEntry.incrementReferences();
  30220. return texturesCacheEntry;
  30221. }
  30222. }
  30223. }
  30224. return null;
  30225. };
  30226. BaseTexture.prototype._rebuild = function () {
  30227. };
  30228. BaseTexture.prototype.delayLoad = function () {
  30229. };
  30230. BaseTexture.prototype.clone = function () {
  30231. return null;
  30232. };
  30233. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30234. get: function () {
  30235. if (!this._texture) {
  30236. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30237. }
  30238. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30244. get: function () {
  30245. if (!this._texture) {
  30246. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30247. }
  30248. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. /**
  30254. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30255. * This will returns an RGBA array buffer containing either in values (0-255) or
  30256. * float values (0-1) depending of the underlying buffer type.
  30257. * @param faceIndex The face of the texture to read (in case of cube texture)
  30258. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30259. * @returns The Array buffer containing the pixels data.
  30260. */
  30261. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30262. if (faceIndex === void 0) { faceIndex = 0; }
  30263. if (level === void 0) { level = 0; }
  30264. if (!this._texture) {
  30265. return null;
  30266. }
  30267. var size = this.getSize();
  30268. var width = size.width;
  30269. var height = size.height;
  30270. var scene = this.getScene();
  30271. if (!scene) {
  30272. return null;
  30273. }
  30274. var engine = scene.getEngine();
  30275. if (level != 0) {
  30276. width = width / Math.pow(2, level);
  30277. height = height / Math.pow(2, level);
  30278. width = Math.round(width);
  30279. height = Math.round(height);
  30280. }
  30281. if (this._texture.isCube) {
  30282. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30283. }
  30284. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30285. };
  30286. BaseTexture.prototype.releaseInternalTexture = function () {
  30287. if (this._texture) {
  30288. this._texture.dispose();
  30289. this._texture = null;
  30290. }
  30291. };
  30292. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30293. get: function () {
  30294. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30295. return null;
  30296. }
  30297. if (!this._texture._sphericalPolynomial) {
  30298. this._texture._sphericalPolynomial =
  30299. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30300. }
  30301. return this._texture._sphericalPolynomial;
  30302. },
  30303. set: function (value) {
  30304. if (this._texture) {
  30305. this._texture._sphericalPolynomial = value;
  30306. }
  30307. },
  30308. enumerable: true,
  30309. configurable: true
  30310. });
  30311. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30312. get: function () {
  30313. if (this._texture) {
  30314. return this._texture._lodTextureHigh;
  30315. }
  30316. return null;
  30317. },
  30318. enumerable: true,
  30319. configurable: true
  30320. });
  30321. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30322. get: function () {
  30323. if (this._texture) {
  30324. return this._texture._lodTextureMid;
  30325. }
  30326. return null;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30332. get: function () {
  30333. if (this._texture) {
  30334. return this._texture._lodTextureLow;
  30335. }
  30336. return null;
  30337. },
  30338. enumerable: true,
  30339. configurable: true
  30340. });
  30341. BaseTexture.prototype.dispose = function () {
  30342. if (!this._scene) {
  30343. return;
  30344. }
  30345. // Animations
  30346. this._scene.stopAnimation(this);
  30347. // Remove from scene
  30348. this._scene._removePendingData(this);
  30349. var index = this._scene.textures.indexOf(this);
  30350. if (index >= 0) {
  30351. this._scene.textures.splice(index, 1);
  30352. }
  30353. if (this._texture === undefined) {
  30354. return;
  30355. }
  30356. // Release
  30357. this.releaseInternalTexture();
  30358. // Callback
  30359. this.onDisposeObservable.notifyObservers(this);
  30360. this.onDisposeObservable.clear();
  30361. };
  30362. BaseTexture.prototype.serialize = function () {
  30363. if (!this.name) {
  30364. return null;
  30365. }
  30366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30367. // Animations
  30368. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30369. return serializationObject;
  30370. };
  30371. BaseTexture.WhenAllReady = function (textures, callback) {
  30372. var numRemaining = textures.length;
  30373. if (numRemaining === 0) {
  30374. callback();
  30375. return;
  30376. }
  30377. var _loop_1 = function () {
  30378. texture = textures[i];
  30379. if (texture.isReady()) {
  30380. if (--numRemaining === 0) {
  30381. callback();
  30382. }
  30383. }
  30384. else {
  30385. onLoadObservable = texture.onLoadObservable;
  30386. var onLoadCallback_1 = function () {
  30387. onLoadObservable.removeCallback(onLoadCallback_1);
  30388. if (--numRemaining === 0) {
  30389. callback();
  30390. }
  30391. };
  30392. onLoadObservable.add(onLoadCallback_1);
  30393. }
  30394. };
  30395. var texture, onLoadObservable;
  30396. for (var i = 0; i < textures.length; i++) {
  30397. _loop_1();
  30398. }
  30399. };
  30400. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30401. __decorate([
  30402. BABYLON.serialize()
  30403. ], BaseTexture.prototype, "name", void 0);
  30404. __decorate([
  30405. BABYLON.serialize("hasAlpha")
  30406. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30407. __decorate([
  30408. BABYLON.serialize()
  30409. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30410. __decorate([
  30411. BABYLON.serialize()
  30412. ], BaseTexture.prototype, "level", void 0);
  30413. __decorate([
  30414. BABYLON.serialize()
  30415. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30416. __decorate([
  30417. BABYLON.serialize("coordinatesMode")
  30418. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30419. __decorate([
  30420. BABYLON.serialize()
  30421. ], BaseTexture.prototype, "wrapU", void 0);
  30422. __decorate([
  30423. BABYLON.serialize()
  30424. ], BaseTexture.prototype, "wrapV", void 0);
  30425. __decorate([
  30426. BABYLON.serialize()
  30427. ], BaseTexture.prototype, "wrapR", void 0);
  30428. __decorate([
  30429. BABYLON.serialize()
  30430. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30431. __decorate([
  30432. BABYLON.serialize()
  30433. ], BaseTexture.prototype, "isCube", void 0);
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], BaseTexture.prototype, "is3D", void 0);
  30437. __decorate([
  30438. BABYLON.serialize()
  30439. ], BaseTexture.prototype, "gammaSpace", void 0);
  30440. __decorate([
  30441. BABYLON.serialize()
  30442. ], BaseTexture.prototype, "invertZ", void 0);
  30443. __decorate([
  30444. BABYLON.serialize()
  30445. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30446. __decorate([
  30447. BABYLON.serialize()
  30448. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30449. __decorate([
  30450. BABYLON.serialize()
  30451. ], BaseTexture.prototype, "lodGenerationScale", null);
  30452. __decorate([
  30453. BABYLON.serialize()
  30454. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30455. return BaseTexture;
  30456. }());
  30457. BABYLON.BaseTexture = BaseTexture;
  30458. })(BABYLON || (BABYLON = {}));
  30459. //# sourceMappingURL=babylon.baseTexture.js.map
  30460. var BABYLON;
  30461. (function (BABYLON) {
  30462. var Texture = /** @class */ (function (_super) {
  30463. __extends(Texture, _super);
  30464. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30465. if (noMipmap === void 0) { noMipmap = false; }
  30466. if (invertY === void 0) { invertY = true; }
  30467. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30468. if (onLoad === void 0) { onLoad = null; }
  30469. if (onError === void 0) { onError = null; }
  30470. if (buffer === void 0) { buffer = null; }
  30471. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30472. var _this = _super.call(this, scene) || this;
  30473. _this.uOffset = 0;
  30474. _this.vOffset = 0;
  30475. _this.uScale = 1.0;
  30476. _this.vScale = 1.0;
  30477. _this.uAng = 0;
  30478. _this.vAng = 0;
  30479. _this.wAng = 0;
  30480. /**
  30481. * Defines the center of rotation (U)
  30482. */
  30483. _this.uRotationCenter = 0.5;
  30484. /**
  30485. * Defines the center of rotation (V)
  30486. */
  30487. _this.vRotationCenter = 0.5;
  30488. /**
  30489. * Defines the center of rotation (W)
  30490. */
  30491. _this.wRotationCenter = 0.5;
  30492. _this._isBlocking = true;
  30493. _this.name = url || "";
  30494. _this.url = url;
  30495. _this._noMipmap = noMipmap;
  30496. _this._invertY = invertY;
  30497. _this._samplingMode = samplingMode;
  30498. _this._buffer = buffer;
  30499. _this._deleteBuffer = deleteBuffer;
  30500. if (format) {
  30501. _this._format = format;
  30502. }
  30503. scene = _this.getScene();
  30504. if (!scene) {
  30505. return _this;
  30506. }
  30507. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30508. var load = function () {
  30509. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30510. _this.onLoadObservable.notifyObservers(_this);
  30511. }
  30512. if (onLoad) {
  30513. onLoad();
  30514. }
  30515. if (!_this.isBlocking && scene) {
  30516. scene.resetCachedMaterial();
  30517. }
  30518. };
  30519. if (!_this.url) {
  30520. _this._delayedOnLoad = load;
  30521. _this._delayedOnError = onError;
  30522. return _this;
  30523. }
  30524. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30525. if (!_this._texture) {
  30526. if (!scene.useDelayedTextureLoading) {
  30527. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30528. if (deleteBuffer) {
  30529. delete _this._buffer;
  30530. }
  30531. }
  30532. else {
  30533. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30534. _this._delayedOnLoad = load;
  30535. _this._delayedOnError = onError;
  30536. }
  30537. }
  30538. else {
  30539. if (_this._texture.isReady) {
  30540. BABYLON.Tools.SetImmediate(function () { return load(); });
  30541. }
  30542. else {
  30543. _this._texture.onLoadedObservable.add(load);
  30544. }
  30545. }
  30546. return _this;
  30547. }
  30548. Object.defineProperty(Texture.prototype, "noMipmap", {
  30549. get: function () {
  30550. return this._noMipmap;
  30551. },
  30552. enumerable: true,
  30553. configurable: true
  30554. });
  30555. Object.defineProperty(Texture.prototype, "isBlocking", {
  30556. get: function () {
  30557. return this._isBlocking;
  30558. },
  30559. set: function (value) {
  30560. this._isBlocking = value;
  30561. },
  30562. enumerable: true,
  30563. configurable: true
  30564. });
  30565. Object.defineProperty(Texture.prototype, "samplingMode", {
  30566. get: function () {
  30567. return this._samplingMode;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. /**
  30573. * Update the url (and optional buffer) of this texture if url was null during construction.
  30574. * @param url the url of the texture
  30575. * @param buffer the buffer of the texture (defaults to null)
  30576. */
  30577. Texture.prototype.updateURL = function (url, buffer) {
  30578. if (buffer === void 0) { buffer = null; }
  30579. if (this.url) {
  30580. throw new Error("URL is already set");
  30581. }
  30582. this.url = url;
  30583. this._buffer = buffer;
  30584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30585. this.delayLoad();
  30586. };
  30587. Texture.prototype.delayLoad = function () {
  30588. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30589. return;
  30590. }
  30591. var scene = this.getScene();
  30592. if (!scene) {
  30593. return;
  30594. }
  30595. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30596. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30597. if (!this._texture) {
  30598. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30599. if (this._deleteBuffer) {
  30600. delete this._buffer;
  30601. }
  30602. }
  30603. else {
  30604. if (this._delayedOnLoad) {
  30605. if (this._texture.isReady) {
  30606. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30607. }
  30608. else {
  30609. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30610. }
  30611. }
  30612. }
  30613. this._delayedOnLoad = null;
  30614. this._delayedOnError = null;
  30615. };
  30616. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30617. if (!this._texture) {
  30618. return;
  30619. }
  30620. var scene = this.getScene();
  30621. if (!scene) {
  30622. return;
  30623. }
  30624. this._samplingMode = samplingMode;
  30625. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30626. };
  30627. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30628. x *= this.uScale;
  30629. y *= this.vScale;
  30630. x -= this.uRotationCenter * this.uScale;
  30631. y -= this.vRotationCenter * this.vScale;
  30632. z -= this.wRotationCenter;
  30633. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30634. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30635. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30636. t.z += this.wRotationCenter;
  30637. };
  30638. Texture.prototype.getTextureMatrix = function () {
  30639. var _this = this;
  30640. if (this.uOffset === this._cachedUOffset &&
  30641. this.vOffset === this._cachedVOffset &&
  30642. this.uScale === this._cachedUScale &&
  30643. this.vScale === this._cachedVScale &&
  30644. this.uAng === this._cachedUAng &&
  30645. this.vAng === this._cachedVAng &&
  30646. this.wAng === this._cachedWAng) {
  30647. return this._cachedTextureMatrix;
  30648. }
  30649. this._cachedUOffset = this.uOffset;
  30650. this._cachedVOffset = this.vOffset;
  30651. this._cachedUScale = this.uScale;
  30652. this._cachedVScale = this.vScale;
  30653. this._cachedUAng = this.uAng;
  30654. this._cachedVAng = this.vAng;
  30655. this._cachedWAng = this.wAng;
  30656. if (!this._cachedTextureMatrix) {
  30657. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30658. this._rowGenerationMatrix = new BABYLON.Matrix();
  30659. this._t0 = BABYLON.Vector3.Zero();
  30660. this._t1 = BABYLON.Vector3.Zero();
  30661. this._t2 = BABYLON.Vector3.Zero();
  30662. }
  30663. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30664. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30665. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30666. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30667. this._t1.subtractInPlace(this._t0);
  30668. this._t2.subtractInPlace(this._t0);
  30669. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30670. this._cachedTextureMatrix.m[0] = this._t1.x;
  30671. this._cachedTextureMatrix.m[1] = this._t1.y;
  30672. this._cachedTextureMatrix.m[2] = this._t1.z;
  30673. this._cachedTextureMatrix.m[4] = this._t2.x;
  30674. this._cachedTextureMatrix.m[5] = this._t2.y;
  30675. this._cachedTextureMatrix.m[6] = this._t2.z;
  30676. this._cachedTextureMatrix.m[8] = this._t0.x;
  30677. this._cachedTextureMatrix.m[9] = this._t0.y;
  30678. this._cachedTextureMatrix.m[10] = this._t0.z;
  30679. var scene = this.getScene();
  30680. if (!scene) {
  30681. return this._cachedTextureMatrix;
  30682. }
  30683. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30684. return mat.hasTexture(_this);
  30685. });
  30686. return this._cachedTextureMatrix;
  30687. };
  30688. Texture.prototype.getReflectionTextureMatrix = function () {
  30689. var _this = this;
  30690. var scene = this.getScene();
  30691. if (!scene) {
  30692. return this._cachedTextureMatrix;
  30693. }
  30694. if (this.uOffset === this._cachedUOffset &&
  30695. this.vOffset === this._cachedVOffset &&
  30696. this.uScale === this._cachedUScale &&
  30697. this.vScale === this._cachedVScale &&
  30698. this.coordinatesMode === this._cachedCoordinatesMode) {
  30699. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30700. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30701. return this._cachedTextureMatrix;
  30702. }
  30703. }
  30704. else {
  30705. return this._cachedTextureMatrix;
  30706. }
  30707. }
  30708. if (!this._cachedTextureMatrix) {
  30709. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30710. }
  30711. if (!this._projectionModeMatrix) {
  30712. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30713. }
  30714. this._cachedUOffset = this.uOffset;
  30715. this._cachedVOffset = this.vOffset;
  30716. this._cachedUScale = this.uScale;
  30717. this._cachedVScale = this.vScale;
  30718. this._cachedCoordinatesMode = this.coordinatesMode;
  30719. switch (this.coordinatesMode) {
  30720. case Texture.PLANAR_MODE:
  30721. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30722. this._cachedTextureMatrix[0] = this.uScale;
  30723. this._cachedTextureMatrix[5] = this.vScale;
  30724. this._cachedTextureMatrix[12] = this.uOffset;
  30725. this._cachedTextureMatrix[13] = this.vOffset;
  30726. break;
  30727. case Texture.PROJECTION_MODE:
  30728. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30729. this._projectionModeMatrix.m[0] = 0.5;
  30730. this._projectionModeMatrix.m[5] = -0.5;
  30731. this._projectionModeMatrix.m[10] = 0.0;
  30732. this._projectionModeMatrix.m[12] = 0.5;
  30733. this._projectionModeMatrix.m[13] = 0.5;
  30734. this._projectionModeMatrix.m[14] = 1.0;
  30735. this._projectionModeMatrix.m[15] = 1.0;
  30736. var projectionMatrix = scene.getProjectionMatrix();
  30737. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30738. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30739. break;
  30740. default:
  30741. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30742. break;
  30743. }
  30744. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30745. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30746. });
  30747. return this._cachedTextureMatrix;
  30748. };
  30749. Texture.prototype.clone = function () {
  30750. var _this = this;
  30751. return BABYLON.SerializationHelper.Clone(function () {
  30752. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30753. }, this);
  30754. };
  30755. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30756. get: function () {
  30757. if (!this._onLoadObservable) {
  30758. this._onLoadObservable = new BABYLON.Observable();
  30759. }
  30760. return this._onLoadObservable;
  30761. },
  30762. enumerable: true,
  30763. configurable: true
  30764. });
  30765. Texture.prototype.serialize = function () {
  30766. var serializationObject = _super.prototype.serialize.call(this);
  30767. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30768. serializationObject.base64String = this._buffer;
  30769. serializationObject.name = serializationObject.name.replace("data:", "");
  30770. }
  30771. serializationObject.invertY = this._invertY;
  30772. serializationObject.samplingMode = this.samplingMode;
  30773. return serializationObject;
  30774. };
  30775. Texture.prototype.getClassName = function () {
  30776. return "Texture";
  30777. };
  30778. Texture.prototype.dispose = function () {
  30779. _super.prototype.dispose.call(this);
  30780. if (this._onLoadObservable) {
  30781. this._onLoadObservable.clear();
  30782. this._onLoadObservable = null;
  30783. }
  30784. this._delayedOnLoad = null;
  30785. this._delayedOnError = null;
  30786. };
  30787. // Statics
  30788. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30789. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30790. if (onLoad === void 0) { onLoad = null; }
  30791. if (onError === void 0) { onError = null; }
  30792. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30793. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30794. };
  30795. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30796. if (parsedTexture.customType) {
  30797. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30798. // Update Sampling Mode
  30799. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30800. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30801. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30802. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30803. }
  30804. }
  30805. return parsedCustomTexture;
  30806. }
  30807. if (parsedTexture.isCube) {
  30808. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30809. }
  30810. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30811. return null;
  30812. }
  30813. var texture = BABYLON.SerializationHelper.Parse(function () {
  30814. var generateMipMaps = true;
  30815. if (parsedTexture.noMipmap) {
  30816. generateMipMaps = false;
  30817. }
  30818. if (parsedTexture.mirrorPlane) {
  30819. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30820. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30821. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30822. return mirrorTexture;
  30823. }
  30824. else if (parsedTexture.isRenderTarget) {
  30825. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30826. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30827. return renderTargetTexture;
  30828. }
  30829. else {
  30830. var texture;
  30831. if (parsedTexture.base64String) {
  30832. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30833. }
  30834. else {
  30835. var url = rootUrl + parsedTexture.name;
  30836. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30837. url = parsedTexture.url;
  30838. }
  30839. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30840. }
  30841. return texture;
  30842. }
  30843. }, parsedTexture, scene);
  30844. // Update Sampling Mode
  30845. if (parsedTexture.samplingMode) {
  30846. var sampling = parsedTexture.samplingMode;
  30847. if (texture._samplingMode !== sampling) {
  30848. texture.updateSamplingMode(sampling);
  30849. }
  30850. }
  30851. // Animations
  30852. if (parsedTexture.animations) {
  30853. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30854. var parsedAnimation = parsedTexture.animations[animationIndex];
  30855. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30856. }
  30857. }
  30858. return texture;
  30859. };
  30860. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30861. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30862. if (noMipmap === void 0) { noMipmap = false; }
  30863. if (invertY === void 0) { invertY = true; }
  30864. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30865. if (onLoad === void 0) { onLoad = null; }
  30866. if (onError === void 0) { onError = null; }
  30867. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30868. if (name.substr(0, 5) !== "data:") {
  30869. name = "data:" + name;
  30870. }
  30871. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30872. };
  30873. // Constants
  30874. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30875. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30876. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30877. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30878. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30879. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30880. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30881. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30882. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30883. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30884. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30885. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30886. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30887. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30888. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30889. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30890. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30891. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30892. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30893. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30894. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30895. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30896. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30897. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30898. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30899. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30900. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30901. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30902. /**
  30903. * 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
  30904. */
  30905. Texture.UseSerializedUrlIfAny = false;
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "url", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], Texture.prototype, "uOffset", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], Texture.prototype, "vOffset", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], Texture.prototype, "uScale", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], Texture.prototype, "vScale", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], Texture.prototype, "uAng", void 0);
  30924. __decorate([
  30925. BABYLON.serialize()
  30926. ], Texture.prototype, "vAng", void 0);
  30927. __decorate([
  30928. BABYLON.serialize()
  30929. ], Texture.prototype, "wAng", void 0);
  30930. __decorate([
  30931. BABYLON.serialize()
  30932. ], Texture.prototype, "uRotationCenter", void 0);
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], Texture.prototype, "vRotationCenter", void 0);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], Texture.prototype, "wRotationCenter", void 0);
  30939. __decorate([
  30940. BABYLON.serialize()
  30941. ], Texture.prototype, "isBlocking", null);
  30942. return Texture;
  30943. }(BABYLON.BaseTexture));
  30944. BABYLON.Texture = Texture;
  30945. })(BABYLON || (BABYLON = {}));
  30946. //# sourceMappingURL=babylon.texture.js.map
  30947. var BABYLON;
  30948. (function (BABYLON) {
  30949. /**
  30950. * @hidden
  30951. **/
  30952. var _InstancesBatch = /** @class */ (function () {
  30953. function _InstancesBatch() {
  30954. this.mustReturn = false;
  30955. this.visibleInstances = new Array();
  30956. this.renderSelf = new Array();
  30957. }
  30958. return _InstancesBatch;
  30959. }());
  30960. BABYLON._InstancesBatch = _InstancesBatch;
  30961. var Mesh = /** @class */ (function (_super) {
  30962. __extends(Mesh, _super);
  30963. /**
  30964. * @constructor
  30965. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30966. * @param {Scene} scene The scene to add this mesh to.
  30967. * @param {Node} parent The parent of this mesh, if it has one
  30968. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30969. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30970. * When false, achieved by calling a clone(), also passing False.
  30971. * This will make creation of children, recursive.
  30972. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30973. */
  30974. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30975. if (scene === void 0) { scene = null; }
  30976. if (parent === void 0) { parent = null; }
  30977. if (source === void 0) { source = null; }
  30978. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30979. var _this = _super.call(this, name, scene) || this;
  30980. // Events
  30981. /**
  30982. * An event triggered before rendering the mesh
  30983. */
  30984. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30985. /**
  30986. * An event triggered after rendering the mesh
  30987. */
  30988. _this.onAfterRenderObservable = new BABYLON.Observable();
  30989. /**
  30990. * An event triggered before drawing the mesh
  30991. */
  30992. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30993. // Members
  30994. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30995. _this.instances = new Array();
  30996. _this._LODLevels = new Array();
  30997. _this._visibleInstances = {};
  30998. _this._renderIdForInstances = new Array();
  30999. _this._batchCache = new _InstancesBatch();
  31000. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31001. // Use by builder only to know what orientation were the mesh build in.
  31002. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31003. _this.overrideMaterialSideOrientation = null;
  31004. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31005. // Will be used to save a source mesh reference, If any
  31006. _this._source = null;
  31007. scene = _this.getScene();
  31008. if (source) {
  31009. // Geometry
  31010. if (source._geometry) {
  31011. source._geometry.applyToMesh(_this);
  31012. }
  31013. // Deep copy
  31014. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31015. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31016. // Source mesh
  31017. _this._source = source;
  31018. // Metadata
  31019. if (source.metadata && source.metadata.clone) {
  31020. _this.metadata = source.metadata.clone();
  31021. }
  31022. else {
  31023. _this.metadata = source.metadata;
  31024. }
  31025. // Tags
  31026. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31027. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31028. }
  31029. // Parent
  31030. _this.parent = source.parent;
  31031. // Pivot
  31032. _this.setPivotMatrix(source.getPivotMatrix());
  31033. _this.id = name + "." + source.id;
  31034. // Material
  31035. _this.material = source.material;
  31036. var index;
  31037. if (!doNotCloneChildren) {
  31038. // Children
  31039. var directDescendants = source.getDescendants(true);
  31040. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31041. var child = directDescendants[index_1];
  31042. if (child.clone) {
  31043. child.clone(name + "." + child.name, _this);
  31044. }
  31045. }
  31046. }
  31047. // Physics clone
  31048. var physicsEngine = _this.getScene().getPhysicsEngine();
  31049. if (clonePhysicsImpostor && physicsEngine) {
  31050. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31051. if (impostor) {
  31052. _this.physicsImpostor = impostor.clone(_this);
  31053. }
  31054. }
  31055. // Particles
  31056. for (index = 0; index < scene.particleSystems.length; index++) {
  31057. var system = scene.particleSystems[index];
  31058. if (system.emitter === source) {
  31059. system.clone(system.name, _this);
  31060. }
  31061. }
  31062. _this.refreshBoundingInfo();
  31063. _this.computeWorldMatrix(true);
  31064. }
  31065. // Parent
  31066. if (parent !== null) {
  31067. _this.parent = parent;
  31068. }
  31069. return _this;
  31070. }
  31071. Object.defineProperty(Mesh, "FRONTSIDE", {
  31072. /**
  31073. * Mesh side orientation : usually the external or front surface
  31074. */
  31075. get: function () {
  31076. return Mesh._FRONTSIDE;
  31077. },
  31078. enumerable: true,
  31079. configurable: true
  31080. });
  31081. Object.defineProperty(Mesh, "BACKSIDE", {
  31082. /**
  31083. * Mesh side orientation : usually the internal or back surface
  31084. */
  31085. get: function () {
  31086. return Mesh._BACKSIDE;
  31087. },
  31088. enumerable: true,
  31089. configurable: true
  31090. });
  31091. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31092. /**
  31093. * Mesh side orientation : both internal and external or front and back surfaces
  31094. */
  31095. get: function () {
  31096. return Mesh._DOUBLESIDE;
  31097. },
  31098. enumerable: true,
  31099. configurable: true
  31100. });
  31101. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31102. /**
  31103. * Mesh side orientation : by default, `FRONTSIDE`
  31104. */
  31105. get: function () {
  31106. return Mesh._DEFAULTSIDE;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. Object.defineProperty(Mesh, "NO_CAP", {
  31112. /**
  31113. * Mesh cap setting : no cap
  31114. */
  31115. get: function () {
  31116. return Mesh._NO_CAP;
  31117. },
  31118. enumerable: true,
  31119. configurable: true
  31120. });
  31121. Object.defineProperty(Mesh, "CAP_START", {
  31122. /**
  31123. * Mesh cap setting : one cap at the beginning of the mesh
  31124. */
  31125. get: function () {
  31126. return Mesh._CAP_START;
  31127. },
  31128. enumerable: true,
  31129. configurable: true
  31130. });
  31131. Object.defineProperty(Mesh, "CAP_END", {
  31132. /**
  31133. * Mesh cap setting : one cap at the end of the mesh
  31134. */
  31135. get: function () {
  31136. return Mesh._CAP_END;
  31137. },
  31138. enumerable: true,
  31139. configurable: true
  31140. });
  31141. Object.defineProperty(Mesh, "CAP_ALL", {
  31142. /**
  31143. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31144. */
  31145. get: function () {
  31146. return Mesh._CAP_ALL;
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31152. set: function (callback) {
  31153. if (this._onBeforeDrawObserver) {
  31154. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31155. }
  31156. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31157. },
  31158. enumerable: true,
  31159. configurable: true
  31160. });
  31161. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31162. get: function () {
  31163. return this._morphTargetManager;
  31164. },
  31165. set: function (value) {
  31166. if (this._morphTargetManager === value) {
  31167. return;
  31168. }
  31169. this._morphTargetManager = value;
  31170. this._syncGeometryWithMorphTargetManager();
  31171. },
  31172. enumerable: true,
  31173. configurable: true
  31174. });
  31175. Object.defineProperty(Mesh.prototype, "source", {
  31176. get: function () {
  31177. return this._source;
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31183. get: function () {
  31184. return this._unIndexed;
  31185. },
  31186. set: function (value) {
  31187. if (this._unIndexed !== value) {
  31188. this._unIndexed = value;
  31189. this._markSubMeshesAsAttributesDirty();
  31190. }
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. // Methods
  31196. /**
  31197. * Returns the string "Mesh".
  31198. */
  31199. Mesh.prototype.getClassName = function () {
  31200. return "Mesh";
  31201. };
  31202. /**
  31203. * Returns a string.
  31204. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31205. */
  31206. Mesh.prototype.toString = function (fullDetails) {
  31207. var ret = _super.prototype.toString.call(this, fullDetails);
  31208. ret += ", n vertices: " + this.getTotalVertices();
  31209. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31210. if (this.animations) {
  31211. for (var i = 0; i < this.animations.length; i++) {
  31212. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31213. }
  31214. }
  31215. if (fullDetails) {
  31216. if (this._geometry) {
  31217. var ib = this.getIndices();
  31218. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31219. if (vb && ib) {
  31220. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31221. }
  31222. }
  31223. else {
  31224. ret += ", flat shading: UNKNOWN";
  31225. }
  31226. }
  31227. return ret;
  31228. };
  31229. Mesh.prototype._unBindEffect = function () {
  31230. _super.prototype._unBindEffect.call(this);
  31231. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31232. var instance = _a[_i];
  31233. instance._unBindEffect();
  31234. }
  31235. };
  31236. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31237. /**
  31238. * True if the mesh has some Levels Of Details (LOD).
  31239. * Returns a boolean.
  31240. */
  31241. get: function () {
  31242. return this._LODLevels.length > 0;
  31243. },
  31244. enumerable: true,
  31245. configurable: true
  31246. });
  31247. /**
  31248. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31249. * @returns an array of {BABYLON.MeshLODLevel}
  31250. */
  31251. Mesh.prototype.getLODLevels = function () {
  31252. return this._LODLevels;
  31253. };
  31254. Mesh.prototype._sortLODLevels = function () {
  31255. this._LODLevels.sort(function (a, b) {
  31256. if (a.distance < b.distance) {
  31257. return 1;
  31258. }
  31259. if (a.distance > b.distance) {
  31260. return -1;
  31261. }
  31262. return 0;
  31263. });
  31264. };
  31265. /**
  31266. * Add a mesh as LOD level triggered at the given distance.
  31267. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31268. * @param distance The distance from the center of the object to show this level
  31269. * @param mesh The mesh to be added as LOD level (can be null)
  31270. * @return This mesh (for chaining)
  31271. */
  31272. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31273. if (mesh && mesh._masterMesh) {
  31274. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31275. return this;
  31276. }
  31277. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31278. this._LODLevels.push(level);
  31279. if (mesh) {
  31280. mesh._masterMesh = this;
  31281. }
  31282. this._sortLODLevels();
  31283. return this;
  31284. };
  31285. /**
  31286. * Returns the LOD level mesh at the passed distance or null if not found.
  31287. * It is related to the method `addLODLevel(distance, mesh)`.
  31288. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31289. * Returns an object Mesh or `null`.
  31290. */
  31291. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31292. for (var index = 0; index < this._LODLevels.length; index++) {
  31293. var level = this._LODLevels[index];
  31294. if (level.distance === distance) {
  31295. return level.mesh;
  31296. }
  31297. }
  31298. return null;
  31299. };
  31300. /**
  31301. * Remove a mesh from the LOD array
  31302. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31303. * @param {Mesh} mesh The mesh to be removed.
  31304. * @return {Mesh} This mesh (for chaining)
  31305. */
  31306. Mesh.prototype.removeLODLevel = function (mesh) {
  31307. for (var index = 0; index < this._LODLevels.length; index++) {
  31308. if (this._LODLevels[index].mesh === mesh) {
  31309. this._LODLevels.splice(index, 1);
  31310. if (mesh) {
  31311. mesh._masterMesh = null;
  31312. }
  31313. }
  31314. }
  31315. this._sortLODLevels();
  31316. return this;
  31317. };
  31318. /**
  31319. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31320. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31321. */
  31322. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31323. if (!this._LODLevels || this._LODLevels.length === 0) {
  31324. return this;
  31325. }
  31326. var bSphere;
  31327. if (boundingSphere) {
  31328. bSphere = boundingSphere;
  31329. }
  31330. else {
  31331. var boundingInfo = this.getBoundingInfo();
  31332. bSphere = boundingInfo.boundingSphere;
  31333. }
  31334. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31335. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31336. if (this.onLODLevelSelection) {
  31337. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31338. }
  31339. return this;
  31340. }
  31341. for (var index = 0; index < this._LODLevels.length; index++) {
  31342. var level = this._LODLevels[index];
  31343. if (level.distance < distanceToCamera) {
  31344. if (level.mesh) {
  31345. level.mesh._preActivate();
  31346. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31347. }
  31348. if (this.onLODLevelSelection) {
  31349. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31350. }
  31351. return level.mesh;
  31352. }
  31353. }
  31354. if (this.onLODLevelSelection) {
  31355. this.onLODLevelSelection(distanceToCamera, this, this);
  31356. }
  31357. return this;
  31358. };
  31359. Object.defineProperty(Mesh.prototype, "geometry", {
  31360. /**
  31361. * Returns the mesh internal Geometry object.
  31362. */
  31363. get: function () {
  31364. return this._geometry;
  31365. },
  31366. enumerable: true,
  31367. configurable: true
  31368. });
  31369. /**
  31370. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31371. */
  31372. Mesh.prototype.getTotalVertices = function () {
  31373. if (this._geometry === null || this._geometry === undefined) {
  31374. return 0;
  31375. }
  31376. return this._geometry.getTotalVertices();
  31377. };
  31378. /**
  31379. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31380. * 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.
  31381. * You can force the copy with forceCopy === true
  31382. * Returns null if the mesh has no geometry or no vertex buffer.
  31383. * Possible `kind` values :
  31384. * - BABYLON.VertexBuffer.PositionKind
  31385. * - BABYLON.VertexBuffer.UVKind
  31386. * - BABYLON.VertexBuffer.UV2Kind
  31387. * - BABYLON.VertexBuffer.UV3Kind
  31388. * - BABYLON.VertexBuffer.UV4Kind
  31389. * - BABYLON.VertexBuffer.UV5Kind
  31390. * - BABYLON.VertexBuffer.UV6Kind
  31391. * - BABYLON.VertexBuffer.ColorKind
  31392. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31393. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31394. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31395. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31396. */
  31397. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31398. if (!this._geometry) {
  31399. return null;
  31400. }
  31401. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31402. };
  31403. /**
  31404. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31405. * Returns `null` if the mesh has no geometry.
  31406. * Possible `kind` values :
  31407. * - BABYLON.VertexBuffer.PositionKind
  31408. * - BABYLON.VertexBuffer.UVKind
  31409. * - BABYLON.VertexBuffer.UV2Kind
  31410. * - BABYLON.VertexBuffer.UV3Kind
  31411. * - BABYLON.VertexBuffer.UV4Kind
  31412. * - BABYLON.VertexBuffer.UV5Kind
  31413. * - BABYLON.VertexBuffer.UV6Kind
  31414. * - BABYLON.VertexBuffer.ColorKind
  31415. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31416. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31417. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31418. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31419. */
  31420. Mesh.prototype.getVertexBuffer = function (kind) {
  31421. if (!this._geometry) {
  31422. return null;
  31423. }
  31424. return this._geometry.getVertexBuffer(kind);
  31425. };
  31426. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31427. if (!this._geometry) {
  31428. if (this._delayInfo) {
  31429. return this._delayInfo.indexOf(kind) !== -1;
  31430. }
  31431. return false;
  31432. }
  31433. return this._geometry.isVerticesDataPresent(kind);
  31434. };
  31435. /**
  31436. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31437. * Possible `kind` values :
  31438. * - BABYLON.VertexBuffer.PositionKind
  31439. * - BABYLON.VertexBuffer.UVKind
  31440. * - BABYLON.VertexBuffer.UV2Kind
  31441. * - BABYLON.VertexBuffer.UV3Kind
  31442. * - BABYLON.VertexBuffer.UV4Kind
  31443. * - BABYLON.VertexBuffer.UV5Kind
  31444. * - BABYLON.VertexBuffer.UV6Kind
  31445. * - BABYLON.VertexBuffer.ColorKind
  31446. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31447. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31448. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31449. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31450. */
  31451. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31452. if (!this._geometry) {
  31453. if (this._delayInfo) {
  31454. return this._delayInfo.indexOf(kind) !== -1;
  31455. }
  31456. return false;
  31457. }
  31458. return this._geometry.isVertexBufferUpdatable(kind);
  31459. };
  31460. /**
  31461. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31462. * Possible `kind` values :
  31463. * - BABYLON.VertexBuffer.PositionKind
  31464. * - BABYLON.VertexBuffer.UVKind
  31465. * - BABYLON.VertexBuffer.UV2Kind
  31466. * - BABYLON.VertexBuffer.UV3Kind
  31467. * - BABYLON.VertexBuffer.UV4Kind
  31468. * - BABYLON.VertexBuffer.UV5Kind
  31469. * - BABYLON.VertexBuffer.UV6Kind
  31470. * - BABYLON.VertexBuffer.ColorKind
  31471. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31472. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31473. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31474. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31475. */
  31476. Mesh.prototype.getVerticesDataKinds = function () {
  31477. if (!this._geometry) {
  31478. var result = new Array();
  31479. if (this._delayInfo) {
  31480. this._delayInfo.forEach(function (kind, index, array) {
  31481. result.push(kind);
  31482. });
  31483. }
  31484. return result;
  31485. }
  31486. return this._geometry.getVerticesDataKinds();
  31487. };
  31488. /**
  31489. * Returns a positive integer : the total number of indices in this mesh geometry.
  31490. * Returns zero if the mesh has no geometry.
  31491. */
  31492. Mesh.prototype.getTotalIndices = function () {
  31493. if (!this._geometry) {
  31494. return 0;
  31495. }
  31496. return this._geometry.getTotalIndices();
  31497. };
  31498. /**
  31499. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31500. * 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.
  31501. * Returns an empty array if the mesh has no geometry.
  31502. */
  31503. Mesh.prototype.getIndices = function (copyWhenShared) {
  31504. if (!this._geometry) {
  31505. return [];
  31506. }
  31507. return this._geometry.getIndices(copyWhenShared);
  31508. };
  31509. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31510. get: function () {
  31511. return this._masterMesh !== null && this._masterMesh !== undefined;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. /**
  31517. * Determine if the current mesh is ready to be rendered
  31518. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31519. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31520. * @returns true if all associated assets are ready (material, textures, shaders)
  31521. */
  31522. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31523. if (completeCheck === void 0) { completeCheck = false; }
  31524. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31525. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31526. return false;
  31527. }
  31528. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31529. return false;
  31530. }
  31531. if (!this.subMeshes || this.subMeshes.length === 0) {
  31532. return true;
  31533. }
  31534. if (!completeCheck) {
  31535. return true;
  31536. }
  31537. var engine = this.getEngine();
  31538. var scene = this.getScene();
  31539. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31540. this.computeWorldMatrix();
  31541. var mat = this.material || scene.defaultMaterial;
  31542. if (mat) {
  31543. if (mat.storeEffectOnSubMeshes) {
  31544. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31545. var subMesh = _a[_i];
  31546. var effectiveMaterial = subMesh.getMaterial();
  31547. if (effectiveMaterial) {
  31548. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31549. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31550. return false;
  31551. }
  31552. }
  31553. else {
  31554. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31555. return false;
  31556. }
  31557. }
  31558. }
  31559. }
  31560. }
  31561. else {
  31562. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31563. return false;
  31564. }
  31565. }
  31566. }
  31567. // Shadows
  31568. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31569. var light = _c[_b];
  31570. var generator = light.getShadowGenerator();
  31571. if (generator) {
  31572. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31573. var subMesh = _e[_d];
  31574. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31575. return false;
  31576. }
  31577. }
  31578. }
  31579. }
  31580. // LOD
  31581. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31582. var lod = _g[_f];
  31583. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31584. return false;
  31585. }
  31586. }
  31587. return true;
  31588. };
  31589. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31590. /**
  31591. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31592. * This property is pertinent only for updatable parametric shapes.
  31593. */
  31594. get: function () {
  31595. return this._areNormalsFrozen;
  31596. },
  31597. enumerable: true,
  31598. configurable: true
  31599. });
  31600. /**
  31601. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31602. * It has no effect at all on other shapes.
  31603. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31604. * Returns the Mesh.
  31605. */
  31606. Mesh.prototype.freezeNormals = function () {
  31607. this._areNormalsFrozen = true;
  31608. return this;
  31609. };
  31610. /**
  31611. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31612. * It has no effect at all on other shapes.
  31613. * It reactivates the mesh normals computation if it was previously frozen.
  31614. * Returns the Mesh.
  31615. */
  31616. Mesh.prototype.unfreezeNormals = function () {
  31617. this._areNormalsFrozen = false;
  31618. return this;
  31619. };
  31620. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31621. /**
  31622. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31623. */
  31624. set: function (count) {
  31625. this._overridenInstanceCount = count;
  31626. },
  31627. enumerable: true,
  31628. configurable: true
  31629. });
  31630. // Methods
  31631. Mesh.prototype._preActivate = function () {
  31632. var sceneRenderId = this.getScene().getRenderId();
  31633. if (this._preActivateId === sceneRenderId) {
  31634. return this;
  31635. }
  31636. this._preActivateId = sceneRenderId;
  31637. this._visibleInstances = null;
  31638. return this;
  31639. };
  31640. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31641. if (this._visibleInstances) {
  31642. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31643. }
  31644. return this;
  31645. };
  31646. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31647. if (!this._visibleInstances) {
  31648. this._visibleInstances = {};
  31649. this._visibleInstances.defaultRenderId = renderId;
  31650. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31651. }
  31652. if (!this._visibleInstances[renderId]) {
  31653. this._visibleInstances[renderId] = new Array();
  31654. }
  31655. this._visibleInstances[renderId].push(instance);
  31656. return this;
  31657. };
  31658. /**
  31659. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31660. * This means the mesh underlying bounding box and sphere are recomputed.
  31661. * Returns the Mesh.
  31662. */
  31663. Mesh.prototype.refreshBoundingInfo = function () {
  31664. return this._refreshBoundingInfo(false);
  31665. };
  31666. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31667. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31668. return this;
  31669. }
  31670. var data = this._getPositionData(applySkeleton);
  31671. if (data) {
  31672. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31673. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31674. }
  31675. if (this.subMeshes) {
  31676. for (var index = 0; index < this.subMeshes.length; index++) {
  31677. this.subMeshes[index].refreshBoundingInfo();
  31678. }
  31679. }
  31680. this._updateBoundingInfo();
  31681. return this;
  31682. };
  31683. Mesh.prototype._getPositionData = function (applySkeleton) {
  31684. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31685. if (data && applySkeleton && this.skeleton) {
  31686. data = BABYLON.Tools.Slice(data);
  31687. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31688. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31689. if (matricesWeightsData && matricesIndicesData) {
  31690. var needExtras = this.numBoneInfluencers > 4;
  31691. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31692. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31693. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31694. var tempVector = BABYLON.Tmp.Vector3[0];
  31695. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31696. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31697. var matWeightIdx = 0;
  31698. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31699. finalMatrix.reset();
  31700. var inf;
  31701. var weight;
  31702. for (inf = 0; inf < 4; inf++) {
  31703. weight = matricesWeightsData[matWeightIdx + inf];
  31704. if (weight > 0) {
  31705. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31706. finalMatrix.addToSelf(tempMatrix);
  31707. }
  31708. }
  31709. if (needExtras) {
  31710. for (inf = 0; inf < 4; inf++) {
  31711. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31712. if (weight > 0) {
  31713. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31714. finalMatrix.addToSelf(tempMatrix);
  31715. }
  31716. }
  31717. }
  31718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31719. tempVector.toArray(data, index);
  31720. }
  31721. }
  31722. }
  31723. return data;
  31724. };
  31725. Mesh.prototype._createGlobalSubMesh = function (force) {
  31726. var totalVertices = this.getTotalVertices();
  31727. if (!totalVertices || !this.getIndices()) {
  31728. return null;
  31729. }
  31730. // Check if we need to recreate the submeshes
  31731. if (this.subMeshes && this.subMeshes.length > 0) {
  31732. var ib = this.getIndices();
  31733. if (!ib) {
  31734. return null;
  31735. }
  31736. var totalIndices = ib.length;
  31737. var needToRecreate = false;
  31738. if (force) {
  31739. needToRecreate = true;
  31740. }
  31741. else {
  31742. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31743. var submesh = _a[_i];
  31744. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31745. needToRecreate = true;
  31746. break;
  31747. }
  31748. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31749. needToRecreate = true;
  31750. break;
  31751. }
  31752. }
  31753. }
  31754. if (!needToRecreate) {
  31755. return this.subMeshes[0];
  31756. }
  31757. }
  31758. this.releaseSubMeshes();
  31759. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31760. };
  31761. Mesh.prototype.subdivide = function (count) {
  31762. if (count < 1) {
  31763. return;
  31764. }
  31765. var totalIndices = this.getTotalIndices();
  31766. var subdivisionSize = (totalIndices / count) | 0;
  31767. var offset = 0;
  31768. // Ensure that subdivisionSize is a multiple of 3
  31769. while (subdivisionSize % 3 !== 0) {
  31770. subdivisionSize++;
  31771. }
  31772. this.releaseSubMeshes();
  31773. for (var index = 0; index < count; index++) {
  31774. if (offset >= totalIndices) {
  31775. break;
  31776. }
  31777. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31778. offset += subdivisionSize;
  31779. }
  31780. this.synchronizeInstances();
  31781. };
  31782. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31783. if (updatable === void 0) { updatable = false; }
  31784. if (!this._geometry) {
  31785. var vertexData = new BABYLON.VertexData();
  31786. vertexData.set(data, kind);
  31787. var scene = this.getScene();
  31788. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31789. }
  31790. else {
  31791. this._geometry.setVerticesData(kind, data, updatable, stride);
  31792. }
  31793. return this;
  31794. };
  31795. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31796. if (updatable === void 0) { updatable = true; }
  31797. var vb = this.getVertexBuffer(kind);
  31798. if (!vb || vb.isUpdatable() === updatable) {
  31799. return;
  31800. }
  31801. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31802. };
  31803. /**
  31804. * Sets the mesh VertexBuffer.
  31805. * Returns the Mesh.
  31806. */
  31807. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31808. if (!this._geometry) {
  31809. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31810. }
  31811. this._geometry.setVerticesBuffer(buffer);
  31812. return this;
  31813. };
  31814. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31815. if (!this._geometry) {
  31816. return this;
  31817. }
  31818. if (!makeItUnique) {
  31819. this._geometry.updateVerticesData(kind, data, updateExtends);
  31820. }
  31821. else {
  31822. this.makeGeometryUnique();
  31823. this.updateVerticesData(kind, data, updateExtends, false);
  31824. }
  31825. return this;
  31826. };
  31827. /**
  31828. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31829. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31830. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31831. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31832. * Returns the Mesh.
  31833. */
  31834. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31835. if (computeNormals === void 0) { computeNormals = true; }
  31836. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31837. if (!positions) {
  31838. return this;
  31839. }
  31840. positionFunction(positions);
  31841. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31842. if (computeNormals) {
  31843. var indices = this.getIndices();
  31844. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31845. if (!normals) {
  31846. return this;
  31847. }
  31848. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31849. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31850. }
  31851. return this;
  31852. };
  31853. /**
  31854. * Creates a un-shared specific occurence of the geometry for the mesh.
  31855. * Returns the Mesh.
  31856. */
  31857. Mesh.prototype.makeGeometryUnique = function () {
  31858. if (!this._geometry) {
  31859. return this;
  31860. }
  31861. var oldGeometry = this._geometry;
  31862. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31863. oldGeometry.releaseForMesh(this, true);
  31864. geometry.applyToMesh(this);
  31865. return this;
  31866. };
  31867. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31868. if (totalVertices === void 0) { totalVertices = null; }
  31869. if (updatable === void 0) { updatable = false; }
  31870. if (!this._geometry) {
  31871. var vertexData = new BABYLON.VertexData();
  31872. vertexData.indices = indices;
  31873. var scene = this.getScene();
  31874. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31875. }
  31876. else {
  31877. this._geometry.setIndices(indices, totalVertices, updatable);
  31878. }
  31879. return this;
  31880. };
  31881. /**
  31882. * Update the current index buffer
  31883. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31884. * Returns the Mesh.
  31885. */
  31886. Mesh.prototype.updateIndices = function (indices, offset) {
  31887. if (!this._geometry) {
  31888. return this;
  31889. }
  31890. this._geometry.updateIndices(indices, offset);
  31891. return this;
  31892. };
  31893. /**
  31894. * Invert the geometry to move from a right handed system to a left handed one.
  31895. * Returns the Mesh.
  31896. */
  31897. Mesh.prototype.toLeftHanded = function () {
  31898. if (!this._geometry) {
  31899. return this;
  31900. }
  31901. this._geometry.toLeftHanded();
  31902. return this;
  31903. };
  31904. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31905. if (!this._geometry) {
  31906. return this;
  31907. }
  31908. var engine = this.getScene().getEngine();
  31909. // Wireframe
  31910. var indexToBind;
  31911. if (this._unIndexed) {
  31912. indexToBind = null;
  31913. }
  31914. else {
  31915. switch (fillMode) {
  31916. case BABYLON.Material.PointFillMode:
  31917. indexToBind = null;
  31918. break;
  31919. case BABYLON.Material.WireFrameFillMode:
  31920. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31921. break;
  31922. default:
  31923. case BABYLON.Material.TriangleFillMode:
  31924. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31925. break;
  31926. }
  31927. }
  31928. // VBOs
  31929. this._geometry._bind(effect, indexToBind);
  31930. return this;
  31931. };
  31932. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31933. if (alternate === void 0) { alternate = false; }
  31934. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31935. return this;
  31936. }
  31937. this.onBeforeDrawObservable.notifyObservers(this);
  31938. var scene = this.getScene();
  31939. var engine = scene.getEngine();
  31940. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31941. // or triangles as points
  31942. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31943. }
  31944. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31945. // Triangles as wireframe
  31946. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31947. }
  31948. else {
  31949. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31950. }
  31951. if (scene._isAlternateRenderingEnabled && !alternate) {
  31952. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31953. if (!effect || !scene.activeCamera) {
  31954. return this;
  31955. }
  31956. scene._switchToAlternateCameraConfiguration(true);
  31957. this._effectiveMaterial.bindView(effect);
  31958. this._effectiveMaterial.bindViewProjection(effect);
  31959. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31960. this._draw(subMesh, fillMode, instancesCount, true);
  31961. engine.setViewport(scene.activeCamera.viewport);
  31962. scene._switchToAlternateCameraConfiguration(false);
  31963. this._effectiveMaterial.bindView(effect);
  31964. this._effectiveMaterial.bindViewProjection(effect);
  31965. }
  31966. return this;
  31967. };
  31968. /**
  31969. * Registers for this mesh a javascript function called just before the rendering process.
  31970. * This function is passed the current mesh.
  31971. * Return the Mesh.
  31972. */
  31973. Mesh.prototype.registerBeforeRender = function (func) {
  31974. this.onBeforeRenderObservable.add(func);
  31975. return this;
  31976. };
  31977. /**
  31978. * Disposes a previously registered javascript function called before the rendering.
  31979. * This function is passed the current mesh.
  31980. * Returns the Mesh.
  31981. */
  31982. Mesh.prototype.unregisterBeforeRender = function (func) {
  31983. this.onBeforeRenderObservable.removeCallback(func);
  31984. return this;
  31985. };
  31986. /**
  31987. * Registers for this mesh a javascript function called just after the rendering is complete.
  31988. * This function is passed the current mesh.
  31989. * Returns the Mesh.
  31990. */
  31991. Mesh.prototype.registerAfterRender = function (func) {
  31992. this.onAfterRenderObservable.add(func);
  31993. return this;
  31994. };
  31995. /**
  31996. * Disposes a previously registered javascript function called after the rendering.
  31997. * This function is passed the current mesh.
  31998. * Return the Mesh.
  31999. */
  32000. Mesh.prototype.unregisterAfterRender = function (func) {
  32001. this.onAfterRenderObservable.removeCallback(func);
  32002. return this;
  32003. };
  32004. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32005. var scene = this.getScene();
  32006. this._batchCache.mustReturn = false;
  32007. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32008. this._batchCache.visibleInstances[subMeshId] = null;
  32009. if (this._visibleInstances) {
  32010. var currentRenderId = scene.getRenderId();
  32011. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32012. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32013. var selfRenderId = this._renderId;
  32014. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32015. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32016. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32017. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32018. }
  32019. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32020. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32021. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32022. this._batchCache.mustReturn = true;
  32023. return this._batchCache;
  32024. }
  32025. if (currentRenderId !== selfRenderId) {
  32026. this._batchCache.renderSelf[subMeshId] = false;
  32027. }
  32028. }
  32029. this._renderIdForInstances[subMeshId] = currentRenderId;
  32030. }
  32031. return this._batchCache;
  32032. };
  32033. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32034. var visibleInstances = batch.visibleInstances[subMesh._id];
  32035. if (!visibleInstances) {
  32036. return this;
  32037. }
  32038. var matricesCount = visibleInstances.length + 1;
  32039. var bufferSize = matricesCount * 16 * 4;
  32040. var currentInstancesBufferSize = this._instancesBufferSize;
  32041. var instancesBuffer = this._instancesBuffer;
  32042. while (this._instancesBufferSize < bufferSize) {
  32043. this._instancesBufferSize *= 2;
  32044. }
  32045. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32046. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32047. }
  32048. var offset = 0;
  32049. var instancesCount = 0;
  32050. var world = this.getWorldMatrix();
  32051. if (batch.renderSelf[subMesh._id]) {
  32052. world.copyToArray(this._instancesData, offset);
  32053. offset += 16;
  32054. instancesCount++;
  32055. }
  32056. if (visibleInstances) {
  32057. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32058. var instance = visibleInstances[instanceIndex];
  32059. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32060. offset += 16;
  32061. instancesCount++;
  32062. }
  32063. }
  32064. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32065. if (instancesBuffer) {
  32066. instancesBuffer.dispose();
  32067. }
  32068. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32069. this._instancesBuffer = instancesBuffer;
  32070. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32071. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32072. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32073. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32074. }
  32075. else {
  32076. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32077. }
  32078. this._bind(subMesh, effect, fillMode);
  32079. this._draw(subMesh, fillMode, instancesCount);
  32080. engine.unbindInstanceAttributes();
  32081. return this;
  32082. };
  32083. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32084. var scene = this.getScene();
  32085. var engine = scene.getEngine();
  32086. if (hardwareInstancedRendering) {
  32087. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32088. }
  32089. else {
  32090. if (batch.renderSelf[subMesh._id]) {
  32091. // Draw
  32092. if (onBeforeDraw) {
  32093. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32094. }
  32095. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32096. }
  32097. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32098. if (visibleInstancesForSubMesh) {
  32099. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32100. var instance = visibleInstancesForSubMesh[instanceIndex];
  32101. // World
  32102. var world = instance.getWorldMatrix();
  32103. if (onBeforeDraw) {
  32104. onBeforeDraw(true, world, effectiveMaterial);
  32105. }
  32106. // Draw
  32107. this._draw(subMesh, fillMode);
  32108. }
  32109. }
  32110. }
  32111. return this;
  32112. };
  32113. /**
  32114. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32115. * @param subMesh defines the subMesh to render
  32116. * @param enableAlphaMode defines if alpha mode can be changed
  32117. * @returns the current mesh
  32118. */
  32119. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32120. this._checkOcclusionQuery();
  32121. if (this._isOccluded) {
  32122. return this;
  32123. }
  32124. var scene = this.getScene();
  32125. // Managing instances
  32126. var batch = this._getInstancesRenderList(subMesh._id);
  32127. if (batch.mustReturn) {
  32128. return this;
  32129. }
  32130. // Checking geometry state
  32131. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32132. return this;
  32133. }
  32134. this.onBeforeRenderObservable.notifyObservers(this);
  32135. var engine = scene.getEngine();
  32136. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32137. // Material
  32138. var material = subMesh.getMaterial();
  32139. if (!material) {
  32140. return this;
  32141. }
  32142. this._effectiveMaterial = material;
  32143. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32144. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32145. return this;
  32146. }
  32147. }
  32148. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32149. return this;
  32150. }
  32151. // Alpha mode
  32152. if (enableAlphaMode) {
  32153. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32154. }
  32155. // Outline - step 1
  32156. var savedDepthWrite = engine.getDepthWrite();
  32157. if (this.renderOutline) {
  32158. engine.setDepthWrite(false);
  32159. scene.getOutlineRenderer().render(subMesh, batch);
  32160. engine.setDepthWrite(savedDepthWrite);
  32161. }
  32162. var effect;
  32163. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32164. effect = subMesh.effect;
  32165. }
  32166. else {
  32167. effect = this._effectiveMaterial.getEffect();
  32168. }
  32169. if (!effect) {
  32170. return this;
  32171. }
  32172. var sideOrientation = this.overrideMaterialSideOrientation;
  32173. if (sideOrientation == null) {
  32174. sideOrientation = this._effectiveMaterial.sideOrientation;
  32175. if (this._getWorldMatrixDeterminant() < 0) {
  32176. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32177. }
  32178. }
  32179. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32180. if (this._effectiveMaterial.forceDepthWrite) {
  32181. engine.setDepthWrite(true);
  32182. }
  32183. // Bind
  32184. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32185. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32186. this._bind(subMesh, effect, fillMode);
  32187. }
  32188. var world = this.getWorldMatrix();
  32189. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32190. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32191. }
  32192. else {
  32193. this._effectiveMaterial.bind(world, this);
  32194. }
  32195. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32196. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32197. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32198. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32199. }
  32200. // Draw
  32201. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32202. // Unbind
  32203. this._effectiveMaterial.unbind();
  32204. // Outline - step 2
  32205. if (this.renderOutline && savedDepthWrite) {
  32206. engine.setDepthWrite(true);
  32207. engine.setColorWrite(false);
  32208. scene.getOutlineRenderer().render(subMesh, batch);
  32209. engine.setColorWrite(true);
  32210. }
  32211. // Overlay
  32212. if (this.renderOverlay) {
  32213. var currentMode = engine.getAlphaMode();
  32214. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32215. scene.getOutlineRenderer().render(subMesh, batch, true);
  32216. engine.setAlphaMode(currentMode);
  32217. }
  32218. this.onAfterRenderObservable.notifyObservers(this);
  32219. return this;
  32220. };
  32221. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32222. if (isInstance && effectiveMaterial) {
  32223. effectiveMaterial.bindOnlyWorldMatrix(world);
  32224. }
  32225. };
  32226. /**
  32227. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32228. */
  32229. Mesh.prototype.getEmittedParticleSystems = function () {
  32230. var results = new Array();
  32231. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32232. var particleSystem = this.getScene().particleSystems[index];
  32233. if (particleSystem.emitter === this) {
  32234. results.push(particleSystem);
  32235. }
  32236. }
  32237. return results;
  32238. };
  32239. /**
  32240. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32241. */
  32242. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32243. var results = new Array();
  32244. var descendants = this.getDescendants();
  32245. descendants.push(this);
  32246. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32247. var particleSystem = this.getScene().particleSystems[index];
  32248. var emitter = particleSystem.emitter;
  32249. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32250. results.push(particleSystem);
  32251. }
  32252. }
  32253. return results;
  32254. };
  32255. /**
  32256. * Normalize matrix weights so that all vertices have a total weight set to 1
  32257. */
  32258. Mesh.prototype.cleanMatrixWeights = function () {
  32259. var epsilon = 1e-3;
  32260. var noInfluenceBoneIndex = 0.0;
  32261. if (this.skeleton) {
  32262. noInfluenceBoneIndex = this.skeleton.bones.length;
  32263. }
  32264. else {
  32265. return;
  32266. }
  32267. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32268. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32269. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32270. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32271. var influencers = this.numBoneInfluencers;
  32272. var size = matricesWeights.length;
  32273. for (var i = 0; i < size; i += 4) {
  32274. var weight = 0.0;
  32275. var firstZeroWeight = -1;
  32276. for (var j = 0; j < 4; j++) {
  32277. var w = matricesWeights[i + j];
  32278. weight += w;
  32279. if (w < epsilon && firstZeroWeight < 0) {
  32280. firstZeroWeight = j;
  32281. }
  32282. }
  32283. if (matricesWeightsExtra) {
  32284. for (var j = 0; j < 4; j++) {
  32285. var w = matricesWeightsExtra[i + j];
  32286. weight += w;
  32287. if (w < epsilon && firstZeroWeight < 0) {
  32288. firstZeroWeight = j + 4;
  32289. }
  32290. }
  32291. }
  32292. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32293. firstZeroWeight = influencers - 1;
  32294. }
  32295. if (weight > epsilon) {
  32296. var mweight = 1.0 / weight;
  32297. for (var j = 0; j < 4; j++) {
  32298. matricesWeights[i + j] *= mweight;
  32299. }
  32300. if (matricesWeightsExtra) {
  32301. for (var j = 0; j < 4; j++) {
  32302. matricesWeightsExtra[i + j] *= mweight;
  32303. }
  32304. }
  32305. }
  32306. else {
  32307. if (firstZeroWeight >= 4) {
  32308. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32309. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32310. }
  32311. else {
  32312. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32313. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32314. }
  32315. }
  32316. }
  32317. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32318. if (matricesIndicesExtra) {
  32319. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32320. }
  32321. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32322. if (matricesWeightsExtra) {
  32323. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32324. }
  32325. };
  32326. Mesh.prototype._checkDelayState = function () {
  32327. var scene = this.getScene();
  32328. if (this._geometry) {
  32329. this._geometry.load(scene);
  32330. }
  32331. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32332. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32333. this._queueLoad(scene);
  32334. }
  32335. return this;
  32336. };
  32337. Mesh.prototype._queueLoad = function (scene) {
  32338. var _this = this;
  32339. scene._addPendingData(this);
  32340. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32341. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32342. if (data instanceof ArrayBuffer) {
  32343. _this._delayLoadingFunction(data, _this);
  32344. }
  32345. else {
  32346. _this._delayLoadingFunction(JSON.parse(data), _this);
  32347. }
  32348. _this.instances.forEach(function (instance) {
  32349. instance._syncSubMeshes();
  32350. });
  32351. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32352. scene._removePendingData(_this);
  32353. }, function () { }, scene.database, getBinaryData);
  32354. return this;
  32355. };
  32356. /**
  32357. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32358. */
  32359. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32360. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32361. return false;
  32362. }
  32363. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32364. return false;
  32365. }
  32366. this._checkDelayState();
  32367. return true;
  32368. };
  32369. /**
  32370. * Sets the mesh material by the material or multiMaterial `id` property.
  32371. * The material `id` is a string identifying the material or the multiMaterial.
  32372. * This method returns the Mesh.
  32373. */
  32374. Mesh.prototype.setMaterialByID = function (id) {
  32375. var materials = this.getScene().materials;
  32376. var index;
  32377. for (index = materials.length - 1; index > -1; index--) {
  32378. if (materials[index].id === id) {
  32379. this.material = materials[index];
  32380. return this;
  32381. }
  32382. }
  32383. // Multi
  32384. var multiMaterials = this.getScene().multiMaterials;
  32385. for (index = multiMaterials.length - 1; index > -1; index--) {
  32386. if (multiMaterials[index].id === id) {
  32387. this.material = multiMaterials[index];
  32388. return this;
  32389. }
  32390. }
  32391. return this;
  32392. };
  32393. /**
  32394. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32395. */
  32396. Mesh.prototype.getAnimatables = function () {
  32397. var results = new Array();
  32398. if (this.material) {
  32399. results.push(this.material);
  32400. }
  32401. if (this.skeleton) {
  32402. results.push(this.skeleton);
  32403. }
  32404. return results;
  32405. };
  32406. /**
  32407. * Modifies the mesh geometry according to the passed transformation matrix.
  32408. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32409. * The mesh normals are modified accordingly the same transformation.
  32410. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32411. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32412. * Returns the Mesh.
  32413. */
  32414. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32415. // Position
  32416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32417. return this;
  32418. }
  32419. var submeshes = this.subMeshes.splice(0);
  32420. this._resetPointsArrayCache();
  32421. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32422. var temp = new Array();
  32423. var index;
  32424. for (index = 0; index < data.length; index += 3) {
  32425. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32426. }
  32427. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32428. // Normals
  32429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32430. return this;
  32431. }
  32432. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32433. temp = [];
  32434. for (index = 0; index < data.length; index += 3) {
  32435. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32436. }
  32437. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32438. // flip faces?
  32439. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32440. this.flipFaces();
  32441. }
  32442. // Restore submeshes
  32443. this.releaseSubMeshes();
  32444. this.subMeshes = submeshes;
  32445. return this;
  32446. };
  32447. /**
  32448. * Modifies the mesh geometry according to its own current World Matrix.
  32449. * The mesh World Matrix is then reset.
  32450. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32451. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32452. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32453. * Returns the Mesh.
  32454. */
  32455. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32456. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32457. this.scaling.copyFromFloats(1, 1, 1);
  32458. this.position.copyFromFloats(0, 0, 0);
  32459. this.rotation.copyFromFloats(0, 0, 0);
  32460. //only if quaternion is already set
  32461. if (this.rotationQuaternion) {
  32462. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32463. }
  32464. this._worldMatrix = BABYLON.Matrix.Identity();
  32465. return this;
  32466. };
  32467. Object.defineProperty(Mesh.prototype, "_positions", {
  32468. // Cache
  32469. get: function () {
  32470. if (this._geometry) {
  32471. return this._geometry._positions;
  32472. }
  32473. return null;
  32474. },
  32475. enumerable: true,
  32476. configurable: true
  32477. });
  32478. Mesh.prototype._resetPointsArrayCache = function () {
  32479. if (this._geometry) {
  32480. this._geometry._resetPointsArrayCache();
  32481. }
  32482. return this;
  32483. };
  32484. Mesh.prototype._generatePointsArray = function () {
  32485. if (this._geometry) {
  32486. return this._geometry._generatePointsArray();
  32487. }
  32488. return false;
  32489. };
  32490. /**
  32491. * Returns a new Mesh object generated from the current mesh properties.
  32492. * This method must not get confused with createInstance().
  32493. * The parameter `name` is a string, the name given to the new mesh.
  32494. * The optional parameter `newParent` can be any Node object (default `null`).
  32495. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32496. * 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.
  32497. */
  32498. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32499. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32500. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32501. };
  32502. /**
  32503. * Releases resources associated with this mesh.
  32504. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32505. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32506. */
  32507. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32508. var _this = this;
  32509. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32510. this.morphTargetManager = null;
  32511. if (this._geometry) {
  32512. this._geometry.releaseForMesh(this, true);
  32513. }
  32514. // Sources
  32515. var meshes = this.getScene().meshes;
  32516. meshes.forEach(function (abstractMesh) {
  32517. var mesh = abstractMesh;
  32518. if (mesh._source && mesh._source === _this) {
  32519. mesh._source = null;
  32520. }
  32521. });
  32522. this._source = null;
  32523. // Instances
  32524. if (this._instancesBuffer) {
  32525. this._instancesBuffer.dispose();
  32526. this._instancesBuffer = null;
  32527. }
  32528. while (this.instances.length) {
  32529. this.instances[0].dispose();
  32530. }
  32531. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32532. };
  32533. /**
  32534. * Modifies the mesh geometry according to a displacement map.
  32535. * 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.
  32536. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32537. * This method returns nothing.
  32538. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32539. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32540. * 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.
  32541. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32542. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32543. *
  32544. * Returns the Mesh.
  32545. */
  32546. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32547. var _this = this;
  32548. var scene = this.getScene();
  32549. var onload = function (img) {
  32550. // Getting height map data
  32551. var canvas = document.createElement("canvas");
  32552. var context = canvas.getContext("2d");
  32553. var heightMapWidth = img.width;
  32554. var heightMapHeight = img.height;
  32555. canvas.width = heightMapWidth;
  32556. canvas.height = heightMapHeight;
  32557. context.drawImage(img, 0, 0);
  32558. // Create VertexData from map data
  32559. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32560. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32561. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32562. //execute success callback, if set
  32563. if (onSuccess) {
  32564. onSuccess(_this);
  32565. }
  32566. };
  32567. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32568. return this;
  32569. };
  32570. /**
  32571. * Modifies the mesh geometry according to a displacementMap buffer.
  32572. * 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.
  32573. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32574. * This method returns nothing.
  32575. * 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.
  32576. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32577. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32578. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32579. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32580. *
  32581. * Returns the Mesh.
  32582. */
  32583. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32584. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32585. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32586. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32587. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32588. return this;
  32589. }
  32590. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32591. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32592. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32593. var position = BABYLON.Vector3.Zero();
  32594. var normal = BABYLON.Vector3.Zero();
  32595. var uv = BABYLON.Vector2.Zero();
  32596. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32597. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32598. for (var index = 0; index < positions.length; index += 3) {
  32599. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32600. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32601. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32602. // Compute height
  32603. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32604. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32605. var pos = (u + v * heightMapWidth) * 4;
  32606. var r = buffer[pos] / 255.0;
  32607. var g = buffer[pos + 1] / 255.0;
  32608. var b = buffer[pos + 2] / 255.0;
  32609. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32610. normal.normalize();
  32611. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32612. position = position.add(normal);
  32613. position.toArray(positions, index);
  32614. }
  32615. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32616. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32617. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32618. return this;
  32619. };
  32620. /**
  32621. * Modify the mesh to get a flat shading rendering.
  32622. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32623. * This method returns the Mesh.
  32624. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32625. */
  32626. Mesh.prototype.convertToFlatShadedMesh = function () {
  32627. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32628. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32629. var kinds = this.getVerticesDataKinds();
  32630. var vbs = {};
  32631. var data = {};
  32632. var newdata = {};
  32633. var updatableNormals = false;
  32634. var kindIndex;
  32635. var kind;
  32636. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32637. kind = kinds[kindIndex];
  32638. var vertexBuffer = this.getVertexBuffer(kind);
  32639. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32640. updatableNormals = vertexBuffer.isUpdatable();
  32641. kinds.splice(kindIndex, 1);
  32642. kindIndex--;
  32643. continue;
  32644. }
  32645. vbs[kind] = vertexBuffer;
  32646. data[kind] = vbs[kind].getData();
  32647. newdata[kind] = [];
  32648. }
  32649. // Save previous submeshes
  32650. var previousSubmeshes = this.subMeshes.slice(0);
  32651. var indices = this.getIndices();
  32652. var totalIndices = this.getTotalIndices();
  32653. // Generating unique vertices per face
  32654. var index;
  32655. for (index = 0; index < totalIndices; index++) {
  32656. var vertexIndex = indices[index];
  32657. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32658. kind = kinds[kindIndex];
  32659. var stride = vbs[kind].getStrideSize();
  32660. for (var offset = 0; offset < stride; offset++) {
  32661. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32662. }
  32663. }
  32664. }
  32665. // Updating faces & normal
  32666. var normals = [];
  32667. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32668. for (index = 0; index < totalIndices; index += 3) {
  32669. indices[index] = index;
  32670. indices[index + 1] = index + 1;
  32671. indices[index + 2] = index + 2;
  32672. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32673. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32674. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32675. var p1p2 = p1.subtract(p2);
  32676. var p3p2 = p3.subtract(p2);
  32677. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32678. // Store same normals for every vertex
  32679. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32680. normals.push(normal.x);
  32681. normals.push(normal.y);
  32682. normals.push(normal.z);
  32683. }
  32684. }
  32685. this.setIndices(indices);
  32686. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32687. // Updating vertex buffers
  32688. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32689. kind = kinds[kindIndex];
  32690. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32691. }
  32692. // Updating submeshes
  32693. this.releaseSubMeshes();
  32694. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32695. var previousOne = previousSubmeshes[submeshIndex];
  32696. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32697. }
  32698. this.synchronizeInstances();
  32699. return this;
  32700. };
  32701. /**
  32702. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32703. * In other words, more vertices, no more indices and a single bigger VBO.
  32704. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32705. * Returns the Mesh.
  32706. */
  32707. Mesh.prototype.convertToUnIndexedMesh = function () {
  32708. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32709. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32710. var kinds = this.getVerticesDataKinds();
  32711. var vbs = {};
  32712. var data = {};
  32713. var newdata = {};
  32714. var kindIndex;
  32715. var kind;
  32716. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32717. kind = kinds[kindIndex];
  32718. var vertexBuffer = this.getVertexBuffer(kind);
  32719. vbs[kind] = vertexBuffer;
  32720. data[kind] = vbs[kind].getData();
  32721. newdata[kind] = [];
  32722. }
  32723. // Save previous submeshes
  32724. var previousSubmeshes = this.subMeshes.slice(0);
  32725. var indices = this.getIndices();
  32726. var totalIndices = this.getTotalIndices();
  32727. // Generating unique vertices per face
  32728. var index;
  32729. for (index = 0; index < totalIndices; index++) {
  32730. var vertexIndex = indices[index];
  32731. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32732. kind = kinds[kindIndex];
  32733. var stride = vbs[kind].getStrideSize();
  32734. for (var offset = 0; offset < stride; offset++) {
  32735. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32736. }
  32737. }
  32738. }
  32739. // Updating indices
  32740. for (index = 0; index < totalIndices; index += 3) {
  32741. indices[index] = index;
  32742. indices[index + 1] = index + 1;
  32743. indices[index + 2] = index + 2;
  32744. }
  32745. this.setIndices(indices);
  32746. // Updating vertex buffers
  32747. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32748. kind = kinds[kindIndex];
  32749. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32750. }
  32751. // Updating submeshes
  32752. this.releaseSubMeshes();
  32753. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32754. var previousOne = previousSubmeshes[submeshIndex];
  32755. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32756. }
  32757. this._unIndexed = true;
  32758. this.synchronizeInstances();
  32759. return this;
  32760. };
  32761. /**
  32762. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32763. * This method returns the Mesh.
  32764. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32765. */
  32766. Mesh.prototype.flipFaces = function (flipNormals) {
  32767. if (flipNormals === void 0) { flipNormals = false; }
  32768. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32769. var i;
  32770. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32771. for (i = 0; i < vertex_data.normals.length; i++) {
  32772. vertex_data.normals[i] *= -1;
  32773. }
  32774. }
  32775. if (vertex_data.indices) {
  32776. var temp;
  32777. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32778. // reassign indices
  32779. temp = vertex_data.indices[i + 1];
  32780. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32781. vertex_data.indices[i + 2] = temp;
  32782. }
  32783. }
  32784. vertex_data.applyToMesh(this);
  32785. return this;
  32786. };
  32787. // Instances
  32788. /**
  32789. * Creates a new InstancedMesh object from the mesh model.
  32790. * An instance shares the same properties and the same material than its model.
  32791. * Only these properties of each instance can then be set individually :
  32792. * - position
  32793. * - rotation
  32794. * - rotationQuaternion
  32795. * - setPivotMatrix
  32796. * - scaling
  32797. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32798. * Warning : this method is not supported for Line mesh and LineSystem
  32799. */
  32800. Mesh.prototype.createInstance = function (name) {
  32801. return new BABYLON.InstancedMesh(name, this);
  32802. };
  32803. /**
  32804. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32805. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32806. * This method returns the Mesh.
  32807. */
  32808. Mesh.prototype.synchronizeInstances = function () {
  32809. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32810. var instance = this.instances[instanceIndex];
  32811. instance._syncSubMeshes();
  32812. }
  32813. return this;
  32814. };
  32815. /**
  32816. * Simplify the mesh according to the given array of settings.
  32817. * Function will return immediately and will simplify async. It returns the Mesh.
  32818. * @param settings a collection of simplification settings.
  32819. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32820. * @param type the type of simplification to run.
  32821. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32822. */
  32823. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32824. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32825. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32826. this.getScene().simplificationQueue.addTask({
  32827. settings: settings,
  32828. parallelProcessing: parallelProcessing,
  32829. mesh: this,
  32830. simplificationType: simplificationType,
  32831. successCallback: successCallback
  32832. });
  32833. return this;
  32834. };
  32835. /**
  32836. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32837. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32838. * This should be used together with the simplification to avoid disappearing triangles.
  32839. * Returns the Mesh.
  32840. * @param successCallback an optional success callback to be called after the optimization finished.
  32841. */
  32842. Mesh.prototype.optimizeIndices = function (successCallback) {
  32843. var _this = this;
  32844. var indices = this.getIndices();
  32845. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32846. if (!positions || !indices) {
  32847. return this;
  32848. }
  32849. var vectorPositions = new Array();
  32850. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32851. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32852. }
  32853. var dupes = new Array();
  32854. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32855. var realPos = vectorPositions.length - 1 - iteration;
  32856. var testedPosition = vectorPositions[realPos];
  32857. for (var j = 0; j < realPos; ++j) {
  32858. var againstPosition = vectorPositions[j];
  32859. if (testedPosition.equals(againstPosition)) {
  32860. dupes[realPos] = j;
  32861. break;
  32862. }
  32863. }
  32864. }, function () {
  32865. for (var i = 0; i < indices.length; ++i) {
  32866. indices[i] = dupes[indices[i]] || indices[i];
  32867. }
  32868. //indices are now reordered
  32869. var originalSubMeshes = _this.subMeshes.slice(0);
  32870. _this.setIndices(indices);
  32871. _this.subMeshes = originalSubMeshes;
  32872. if (successCallback) {
  32873. successCallback(_this);
  32874. }
  32875. });
  32876. return this;
  32877. };
  32878. Mesh.prototype.serialize = function (serializationObject) {
  32879. serializationObject.name = this.name;
  32880. serializationObject.id = this.id;
  32881. serializationObject.type = this.getClassName();
  32882. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32883. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32884. }
  32885. serializationObject.position = this.position.asArray();
  32886. if (this.rotationQuaternion) {
  32887. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32888. }
  32889. else if (this.rotation) {
  32890. serializationObject.rotation = this.rotation.asArray();
  32891. }
  32892. serializationObject.scaling = this.scaling.asArray();
  32893. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32894. serializationObject.isEnabled = this.isEnabled(false);
  32895. serializationObject.isVisible = this.isVisible;
  32896. serializationObject.infiniteDistance = this.infiniteDistance;
  32897. serializationObject.pickable = this.isPickable;
  32898. serializationObject.receiveShadows = this.receiveShadows;
  32899. serializationObject.billboardMode = this.billboardMode;
  32900. serializationObject.visibility = this.visibility;
  32901. serializationObject.checkCollisions = this.checkCollisions;
  32902. serializationObject.isBlocker = this.isBlocker;
  32903. // Parent
  32904. if (this.parent) {
  32905. serializationObject.parentId = this.parent.id;
  32906. }
  32907. // Geometry
  32908. serializationObject.isUnIndexed = this.isUnIndexed;
  32909. var geometry = this._geometry;
  32910. if (geometry) {
  32911. var geometryId = geometry.id;
  32912. serializationObject.geometryId = geometryId;
  32913. // SubMeshes
  32914. serializationObject.subMeshes = [];
  32915. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32916. var subMesh = this.subMeshes[subIndex];
  32917. serializationObject.subMeshes.push({
  32918. materialIndex: subMesh.materialIndex,
  32919. verticesStart: subMesh.verticesStart,
  32920. verticesCount: subMesh.verticesCount,
  32921. indexStart: subMesh.indexStart,
  32922. indexCount: subMesh.indexCount
  32923. });
  32924. }
  32925. }
  32926. // Material
  32927. if (this.material) {
  32928. serializationObject.materialId = this.material.id;
  32929. }
  32930. else {
  32931. this.material = null;
  32932. }
  32933. // Morph targets
  32934. if (this.morphTargetManager) {
  32935. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32936. }
  32937. // Skeleton
  32938. if (this.skeleton) {
  32939. serializationObject.skeletonId = this.skeleton.id;
  32940. }
  32941. // Physics
  32942. //TODO implement correct serialization for physics impostors.
  32943. var impostor = this.getPhysicsImpostor();
  32944. if (impostor) {
  32945. serializationObject.physicsMass = impostor.getParam("mass");
  32946. serializationObject.physicsFriction = impostor.getParam("friction");
  32947. serializationObject.physicsRestitution = impostor.getParam("mass");
  32948. serializationObject.physicsImpostor = impostor.type;
  32949. }
  32950. // Metadata
  32951. if (this.metadata) {
  32952. serializationObject.metadata = this.metadata;
  32953. }
  32954. // Instances
  32955. serializationObject.instances = [];
  32956. for (var index = 0; index < this.instances.length; index++) {
  32957. var instance = this.instances[index];
  32958. var serializationInstance = {
  32959. name: instance.name,
  32960. id: instance.id,
  32961. position: instance.position.asArray(),
  32962. scaling: instance.scaling.asArray()
  32963. };
  32964. if (instance.rotationQuaternion) {
  32965. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32966. }
  32967. else if (instance.rotation) {
  32968. serializationInstance.rotation = instance.rotation.asArray();
  32969. }
  32970. serializationObject.instances.push(serializationInstance);
  32971. // Animations
  32972. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32973. serializationInstance.ranges = instance.serializeAnimationRanges();
  32974. }
  32975. //
  32976. // Animations
  32977. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32978. serializationObject.ranges = this.serializeAnimationRanges();
  32979. // Layer mask
  32980. serializationObject.layerMask = this.layerMask;
  32981. // Alpha
  32982. serializationObject.alphaIndex = this.alphaIndex;
  32983. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32984. // Overlay
  32985. serializationObject.overlayAlpha = this.overlayAlpha;
  32986. serializationObject.overlayColor = this.overlayColor.asArray();
  32987. serializationObject.renderOverlay = this.renderOverlay;
  32988. // Fog
  32989. serializationObject.applyFog = this.applyFog;
  32990. // Action Manager
  32991. if (this.actionManager) {
  32992. serializationObject.actions = this.actionManager.serialize(this.name);
  32993. }
  32994. };
  32995. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32996. if (!this.geometry) {
  32997. return;
  32998. }
  32999. this._markSubMeshesAsAttributesDirty();
  33000. var morphTargetManager = this._morphTargetManager;
  33001. if (morphTargetManager && morphTargetManager.vertexCount) {
  33002. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33003. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33004. this.morphTargetManager = null;
  33005. return;
  33006. }
  33007. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33008. var morphTarget = morphTargetManager.getActiveTarget(index);
  33009. var positions = morphTarget.getPositions();
  33010. if (!positions) {
  33011. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33012. return;
  33013. }
  33014. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33015. var normals = morphTarget.getNormals();
  33016. if (normals) {
  33017. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33018. }
  33019. var tangents = morphTarget.getTangents();
  33020. if (tangents) {
  33021. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33022. }
  33023. }
  33024. }
  33025. else {
  33026. var index = 0;
  33027. // Positions
  33028. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33029. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33030. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33031. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33032. }
  33033. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33034. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33035. }
  33036. index++;
  33037. }
  33038. }
  33039. };
  33040. // Statics
  33041. /**
  33042. * Returns a new Mesh object parsed from the source provided.
  33043. * The parameter `parsedMesh` is the source.
  33044. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33045. */
  33046. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33047. var mesh;
  33048. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33049. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33050. }
  33051. else {
  33052. mesh = new Mesh(parsedMesh.name, scene);
  33053. }
  33054. mesh.id = parsedMesh.id;
  33055. if (BABYLON.Tags) {
  33056. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33057. }
  33058. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33059. if (parsedMesh.metadata !== undefined) {
  33060. mesh.metadata = parsedMesh.metadata;
  33061. }
  33062. if (parsedMesh.rotationQuaternion) {
  33063. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33064. }
  33065. else if (parsedMesh.rotation) {
  33066. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33067. }
  33068. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33069. if (parsedMesh.localMatrix) {
  33070. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33071. }
  33072. else if (parsedMesh.pivotMatrix) {
  33073. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33074. }
  33075. mesh.setEnabled(parsedMesh.isEnabled);
  33076. mesh.isVisible = parsedMesh.isVisible;
  33077. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33078. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33079. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33080. if (parsedMesh.applyFog !== undefined) {
  33081. mesh.applyFog = parsedMesh.applyFog;
  33082. }
  33083. if (parsedMesh.pickable !== undefined) {
  33084. mesh.isPickable = parsedMesh.pickable;
  33085. }
  33086. if (parsedMesh.alphaIndex !== undefined) {
  33087. mesh.alphaIndex = parsedMesh.alphaIndex;
  33088. }
  33089. mesh.receiveShadows = parsedMesh.receiveShadows;
  33090. mesh.billboardMode = parsedMesh.billboardMode;
  33091. if (parsedMesh.visibility !== undefined) {
  33092. mesh.visibility = parsedMesh.visibility;
  33093. }
  33094. mesh.checkCollisions = parsedMesh.checkCollisions;
  33095. if (parsedMesh.isBlocker !== undefined) {
  33096. mesh.isBlocker = parsedMesh.isBlocker;
  33097. }
  33098. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33099. // freezeWorldMatrix
  33100. if (parsedMesh.freezeWorldMatrix) {
  33101. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33102. }
  33103. // Parent
  33104. if (parsedMesh.parentId) {
  33105. mesh._waitingParentId = parsedMesh.parentId;
  33106. }
  33107. // Actions
  33108. if (parsedMesh.actions !== undefined) {
  33109. mesh._waitingActions = parsedMesh.actions;
  33110. }
  33111. // Overlay
  33112. if (parsedMesh.overlayAlpha !== undefined) {
  33113. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33114. }
  33115. if (parsedMesh.overlayColor !== undefined) {
  33116. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33117. }
  33118. if (parsedMesh.renderOverlay !== undefined) {
  33119. mesh.renderOverlay = parsedMesh.renderOverlay;
  33120. }
  33121. // Geometry
  33122. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33123. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33124. if (parsedMesh.delayLoadingFile) {
  33125. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33126. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33127. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33128. if (parsedMesh._binaryInfo) {
  33129. mesh._binaryInfo = parsedMesh._binaryInfo;
  33130. }
  33131. mesh._delayInfo = [];
  33132. if (parsedMesh.hasUVs) {
  33133. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33134. }
  33135. if (parsedMesh.hasUVs2) {
  33136. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33137. }
  33138. if (parsedMesh.hasUVs3) {
  33139. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33140. }
  33141. if (parsedMesh.hasUVs4) {
  33142. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33143. }
  33144. if (parsedMesh.hasUVs5) {
  33145. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33146. }
  33147. if (parsedMesh.hasUVs6) {
  33148. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33149. }
  33150. if (parsedMesh.hasColors) {
  33151. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33152. }
  33153. if (parsedMesh.hasMatricesIndices) {
  33154. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33155. }
  33156. if (parsedMesh.hasMatricesWeights) {
  33157. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33158. }
  33159. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33160. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33161. mesh._checkDelayState();
  33162. }
  33163. }
  33164. else {
  33165. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33166. }
  33167. // Material
  33168. if (parsedMesh.materialId) {
  33169. mesh.setMaterialByID(parsedMesh.materialId);
  33170. }
  33171. else {
  33172. mesh.material = null;
  33173. }
  33174. // Morph targets
  33175. if (parsedMesh.morphTargetManagerId > -1) {
  33176. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33177. }
  33178. // Skeleton
  33179. if (parsedMesh.skeletonId > -1) {
  33180. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33181. if (parsedMesh.numBoneInfluencers) {
  33182. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33183. }
  33184. }
  33185. // Animations
  33186. if (parsedMesh.animations) {
  33187. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33188. var parsedAnimation = parsedMesh.animations[animationIndex];
  33189. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33190. }
  33191. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33192. }
  33193. if (parsedMesh.autoAnimate) {
  33194. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33195. }
  33196. // Layer Mask
  33197. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33198. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33199. }
  33200. else {
  33201. mesh.layerMask = 0x0FFFFFFF;
  33202. }
  33203. // Physics
  33204. if (parsedMesh.physicsImpostor) {
  33205. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33206. mass: parsedMesh.physicsMass,
  33207. friction: parsedMesh.physicsFriction,
  33208. restitution: parsedMesh.physicsRestitution
  33209. }, scene);
  33210. }
  33211. // Instances
  33212. if (parsedMesh.instances) {
  33213. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33214. var parsedInstance = parsedMesh.instances[index];
  33215. var instance = mesh.createInstance(parsedInstance.name);
  33216. if (parsedInstance.id) {
  33217. instance.id = parsedInstance.id;
  33218. }
  33219. if (BABYLON.Tags) {
  33220. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33221. }
  33222. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33223. if (parsedInstance.parentId) {
  33224. instance._waitingParentId = parsedInstance.parentId;
  33225. }
  33226. if (parsedInstance.rotationQuaternion) {
  33227. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33228. }
  33229. else if (parsedInstance.rotation) {
  33230. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33231. }
  33232. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33233. instance.checkCollisions = mesh.checkCollisions;
  33234. if (parsedMesh.animations) {
  33235. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33236. parsedAnimation = parsedMesh.animations[animationIndex];
  33237. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33238. }
  33239. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33240. if (parsedMesh.autoAnimate) {
  33241. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33242. }
  33243. }
  33244. }
  33245. }
  33246. return mesh;
  33247. };
  33248. /**
  33249. * Creates a ribbon mesh.
  33250. * Please consider using the same method from the MeshBuilder class instead.
  33251. * 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.
  33252. *
  33253. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33254. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33255. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33256. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33257. * 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.
  33258. * 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.
  33259. * 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
  33260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33261. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33263. */
  33264. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33265. if (closeArray === void 0) { closeArray = false; }
  33266. if (updatable === void 0) { updatable = false; }
  33267. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33268. pathArray: pathArray,
  33269. closeArray: closeArray,
  33270. closePath: closePath,
  33271. offset: offset,
  33272. updatable: updatable,
  33273. sideOrientation: sideOrientation,
  33274. instance: instance
  33275. }, scene);
  33276. };
  33277. /**
  33278. * Creates a plane polygonal mesh. By default, this is a disc.
  33279. * Please consider using the same method from the MeshBuilder class instead.
  33280. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33281. * 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.
  33282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33283. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33285. */
  33286. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33287. if (scene === void 0) { scene = null; }
  33288. var options = {
  33289. radius: radius,
  33290. tessellation: tessellation,
  33291. sideOrientation: sideOrientation,
  33292. updatable: updatable
  33293. };
  33294. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33295. };
  33296. /**
  33297. * Creates a box mesh.
  33298. * Please consider using the same method from the MeshBuilder class instead.
  33299. * The parameter `size` sets the size (float) of each box side (default 1).
  33300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33301. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33303. */
  33304. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33305. if (scene === void 0) { scene = null; }
  33306. var options = {
  33307. size: size,
  33308. sideOrientation: sideOrientation,
  33309. updatable: updatable
  33310. };
  33311. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33312. };
  33313. /**
  33314. * Creates a sphere mesh.
  33315. * Please consider using the same method from the MeshBuilder class instead.
  33316. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33317. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33319. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33321. */
  33322. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33323. var options = {
  33324. segments: segments,
  33325. diameterX: diameter,
  33326. diameterY: diameter,
  33327. diameterZ: diameter,
  33328. sideOrientation: sideOrientation,
  33329. updatable: updatable
  33330. };
  33331. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33332. };
  33333. /**
  33334. * Creates a cylinder or a cone mesh.
  33335. * Please consider using the same method from the MeshBuilder class instead.
  33336. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33337. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33338. * 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.
  33339. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33340. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33342. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33344. */
  33345. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33346. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33347. if (scene !== undefined) {
  33348. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33349. updatable = scene;
  33350. }
  33351. scene = subdivisions;
  33352. subdivisions = 1;
  33353. }
  33354. var options = {
  33355. height: height,
  33356. diameterTop: diameterTop,
  33357. diameterBottom: diameterBottom,
  33358. tessellation: tessellation,
  33359. subdivisions: subdivisions,
  33360. sideOrientation: sideOrientation,
  33361. updatable: updatable
  33362. };
  33363. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33364. };
  33365. // Torus (Code from SharpDX.org)
  33366. /**
  33367. * Creates a torus mesh.
  33368. * Please consider using the same method from the MeshBuilder class instead.
  33369. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33370. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33371. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33373. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33375. */
  33376. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33377. var options = {
  33378. diameter: diameter,
  33379. thickness: thickness,
  33380. tessellation: tessellation,
  33381. sideOrientation: sideOrientation,
  33382. updatable: updatable
  33383. };
  33384. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33385. };
  33386. /**
  33387. * Creates a torus knot mesh.
  33388. * Please consider using the same method from the MeshBuilder class instead.
  33389. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33390. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33391. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33392. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33394. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33396. */
  33397. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33398. var options = {
  33399. radius: radius,
  33400. tube: tube,
  33401. radialSegments: radialSegments,
  33402. tubularSegments: tubularSegments,
  33403. p: p,
  33404. q: q,
  33405. sideOrientation: sideOrientation,
  33406. updatable: updatable
  33407. };
  33408. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33409. };
  33410. /**
  33411. * Creates a line mesh.
  33412. * Please consider using the same method from the MeshBuilder class instead.
  33413. * 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.
  33414. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33415. * The parameter `points` is an array successive Vector3.
  33416. * 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
  33417. * When updating an instance, remember that only point positions can change, not the number of points.
  33418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33419. */
  33420. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33421. if (scene === void 0) { scene = null; }
  33422. if (updatable === void 0) { updatable = false; }
  33423. if (instance === void 0) { instance = null; }
  33424. var options = {
  33425. points: points,
  33426. updatable: updatable,
  33427. instance: instance
  33428. };
  33429. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33430. };
  33431. /**
  33432. * Creates a dashed line mesh.
  33433. * Please consider using the same method from the MeshBuilder class instead.
  33434. * 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.
  33435. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33436. * The parameter `points` is an array successive Vector3.
  33437. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33438. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33439. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33440. * 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
  33441. * When updating an instance, remember that only point positions can change, not the number of points.
  33442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33443. */
  33444. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33445. if (scene === void 0) { scene = null; }
  33446. var options = {
  33447. points: points,
  33448. dashSize: dashSize,
  33449. gapSize: gapSize,
  33450. dashNb: dashNb,
  33451. updatable: updatable,
  33452. instance: instance
  33453. };
  33454. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33455. };
  33456. /**
  33457. * Creates a polygon mesh.
  33458. * Please consider using the same method from the MeshBuilder class instead.
  33459. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33460. * 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.
  33461. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33463. * Remember you can only change the shape positions, not their number when updating a polygon.
  33464. */
  33465. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33466. var options = {
  33467. shape: shape,
  33468. holes: holes,
  33469. updatable: updatable,
  33470. sideOrientation: sideOrientation
  33471. };
  33472. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33473. };
  33474. /**
  33475. * Creates an extruded polygon mesh, with depth in the Y direction.
  33476. * Please consider using the same method from the MeshBuilder class instead.
  33477. */
  33478. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33479. var options = {
  33480. shape: shape,
  33481. holes: holes,
  33482. depth: depth,
  33483. updatable: updatable,
  33484. sideOrientation: sideOrientation
  33485. };
  33486. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33487. };
  33488. /**
  33489. * Creates an extruded shape mesh.
  33490. * 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.
  33491. * Please consider using the same method from the MeshBuilder class instead.
  33492. *
  33493. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33494. * 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
  33495. * extruded along the Z axis.
  33496. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33497. * 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.
  33498. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33499. * 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
  33500. * 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
  33501. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33503. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33505. */
  33506. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33507. if (scene === void 0) { scene = null; }
  33508. var options = {
  33509. shape: shape,
  33510. path: path,
  33511. scale: scale,
  33512. rotation: rotation,
  33513. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33514. sideOrientation: sideOrientation,
  33515. instance: instance,
  33516. updatable: updatable
  33517. };
  33518. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33519. };
  33520. /**
  33521. * Creates an custom extruded shape mesh.
  33522. * 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.
  33523. * Please consider using the same method from the MeshBuilder class instead.
  33524. *
  33525. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33526. * 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
  33527. * extruded along the Z axis.
  33528. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33529. * 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
  33530. * and the distance of this point from the begining of the path :
  33531. * ```javascript
  33532. * var rotationFunction = function(i, distance) {
  33533. * // do things
  33534. * return rotationValue; }
  33535. * ```
  33536. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33537. * 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
  33538. * and the distance of this point from the begining of the path :
  33539. * ```javascript
  33540. * var scaleFunction = function(i, distance) {
  33541. * // do things
  33542. * return scaleValue;}
  33543. * ```
  33544. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33545. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33546. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33547. * 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
  33548. * 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
  33549. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33551. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33555. var options = {
  33556. shape: shape,
  33557. path: path,
  33558. scaleFunction: scaleFunction,
  33559. rotationFunction: rotationFunction,
  33560. ribbonCloseArray: ribbonCloseArray,
  33561. ribbonClosePath: ribbonClosePath,
  33562. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33563. sideOrientation: sideOrientation,
  33564. instance: instance,
  33565. updatable: updatable
  33566. };
  33567. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33568. };
  33569. /**
  33570. * Creates lathe mesh.
  33571. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33572. * Please consider using the same method from the MeshBuilder class instead.
  33573. * 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
  33574. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33575. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33576. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33578. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33580. */
  33581. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33582. var options = {
  33583. shape: shape,
  33584. radius: radius,
  33585. tessellation: tessellation,
  33586. sideOrientation: sideOrientation,
  33587. updatable: updatable
  33588. };
  33589. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33590. };
  33591. /**
  33592. * Creates a plane mesh.
  33593. * Please consider using the same method from the MeshBuilder class instead.
  33594. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33595. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33596. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33598. */
  33599. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33600. var options = {
  33601. size: size,
  33602. width: size,
  33603. height: size,
  33604. sideOrientation: sideOrientation,
  33605. updatable: updatable
  33606. };
  33607. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33608. };
  33609. /**
  33610. * Creates a ground mesh.
  33611. * Please consider using the same method from the MeshBuilder class instead.
  33612. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33613. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33615. */
  33616. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33617. var options = {
  33618. width: width,
  33619. height: height,
  33620. subdivisions: subdivisions,
  33621. updatable: updatable
  33622. };
  33623. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33624. };
  33625. /**
  33626. * Creates a tiled ground mesh.
  33627. * Please consider using the same method from the MeshBuilder class instead.
  33628. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33629. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33630. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33631. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33632. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33633. * numbers of subdivisions on the ground width and height of each tile.
  33634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33635. */
  33636. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33637. var options = {
  33638. xmin: xmin,
  33639. zmin: zmin,
  33640. xmax: xmax,
  33641. zmax: zmax,
  33642. subdivisions: subdivisions,
  33643. precision: precision,
  33644. updatable: updatable
  33645. };
  33646. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33647. };
  33648. /**
  33649. * Creates a ground mesh from a height map.
  33650. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33651. * Please consider using the same method from the MeshBuilder class instead.
  33652. * The parameter `url` sets the URL of the height map image resource.
  33653. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33654. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33655. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33656. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33657. * 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).
  33658. * This function is passed the newly built mesh :
  33659. * ```javascript
  33660. * function(mesh) { // do things
  33661. * return; }
  33662. * ```
  33663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33664. */
  33665. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33666. var options = {
  33667. width: width,
  33668. height: height,
  33669. subdivisions: subdivisions,
  33670. minHeight: minHeight,
  33671. maxHeight: maxHeight,
  33672. updatable: updatable,
  33673. onReady: onReady
  33674. };
  33675. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33676. };
  33677. /**
  33678. * Creates a tube mesh.
  33679. * 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.
  33680. * Please consider using the same method from the MeshBuilder class instead.
  33681. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33682. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33683. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33684. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33685. * 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.
  33686. * It must return a radius value (positive float) :
  33687. * ```javascript
  33688. * var radiusFunction = function(i, distance) {
  33689. * // do things
  33690. * return radius; }
  33691. * ```
  33692. * 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
  33693. * 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
  33694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33695. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33697. */
  33698. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33699. var options = {
  33700. path: path,
  33701. radius: radius,
  33702. tessellation: tessellation,
  33703. radiusFunction: radiusFunction,
  33704. arc: 1,
  33705. cap: cap,
  33706. updatable: updatable,
  33707. sideOrientation: sideOrientation,
  33708. instance: instance
  33709. };
  33710. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33711. };
  33712. /**
  33713. * Creates a polyhedron mesh.
  33714. * Please consider using the same method from the MeshBuilder class instead.
  33715. * 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
  33716. * to choose the wanted type.
  33717. * The parameter `size` (positive float, default 1) sets the polygon size.
  33718. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33719. * 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`.
  33720. * 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
  33721. * 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)`).
  33722. * 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
  33723. * 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.
  33724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33725. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33727. */
  33728. Mesh.CreatePolyhedron = function (name, options, scene) {
  33729. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33730. };
  33731. /**
  33732. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33733. * Please consider using the same method from the MeshBuilder class instead.
  33734. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33735. * 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`).
  33736. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33737. * 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.
  33738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33739. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33741. */
  33742. Mesh.CreateIcoSphere = function (name, options, scene) {
  33743. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33744. };
  33745. /**
  33746. * Creates a decal mesh.
  33747. * Please consider using the same method from the MeshBuilder class instead.
  33748. * 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.
  33749. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33750. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33751. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33752. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33753. */
  33754. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33755. var options = {
  33756. position: position,
  33757. normal: normal,
  33758. size: size,
  33759. angle: angle
  33760. };
  33761. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33762. };
  33763. // Skeletons
  33764. /**
  33765. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33766. */
  33767. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33768. if (!this._sourcePositions) {
  33769. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33770. if (!source) {
  33771. return this._sourcePositions;
  33772. }
  33773. this._sourcePositions = new Float32Array(source);
  33774. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33775. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33776. }
  33777. }
  33778. return this._sourcePositions;
  33779. };
  33780. /**
  33781. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33782. */
  33783. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33784. if (!this._sourceNormals) {
  33785. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33786. if (!source) {
  33787. return this._sourceNormals;
  33788. }
  33789. this._sourceNormals = new Float32Array(source);
  33790. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33791. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33792. }
  33793. }
  33794. return this._sourceNormals;
  33795. };
  33796. /**
  33797. * Updates the vertex buffer by applying transformation from the bones.
  33798. * Returns the Mesh.
  33799. *
  33800. * @param {skeleton} skeleton to apply
  33801. */
  33802. Mesh.prototype.applySkeleton = function (skeleton) {
  33803. if (!this.geometry) {
  33804. return this;
  33805. }
  33806. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33807. return this;
  33808. }
  33809. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33810. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33811. return this;
  33812. }
  33813. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33814. return this;
  33815. }
  33816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33817. return this;
  33818. }
  33819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33820. return this;
  33821. }
  33822. if (!this._sourcePositions) {
  33823. var submeshes = this.subMeshes.slice();
  33824. this.setPositionsForCPUSkinning();
  33825. this.subMeshes = submeshes;
  33826. }
  33827. if (!this._sourceNormals) {
  33828. this.setNormalsForCPUSkinning();
  33829. }
  33830. // positionsData checks for not being Float32Array will only pass at most once
  33831. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33832. if (!positionsData) {
  33833. return this;
  33834. }
  33835. if (!(positionsData instanceof Float32Array)) {
  33836. positionsData = new Float32Array(positionsData);
  33837. }
  33838. // normalsData checks for not being Float32Array will only pass at most once
  33839. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33840. if (!normalsData) {
  33841. return this;
  33842. }
  33843. if (!(normalsData instanceof Float32Array)) {
  33844. normalsData = new Float32Array(normalsData);
  33845. }
  33846. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33847. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33848. if (!matricesWeightsData || !matricesIndicesData) {
  33849. return this;
  33850. }
  33851. var needExtras = this.numBoneInfluencers > 4;
  33852. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33853. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33854. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33855. var tempVector3 = BABYLON.Vector3.Zero();
  33856. var finalMatrix = new BABYLON.Matrix();
  33857. var tempMatrix = new BABYLON.Matrix();
  33858. var matWeightIdx = 0;
  33859. var inf;
  33860. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33861. var weight;
  33862. for (inf = 0; inf < 4; inf++) {
  33863. weight = matricesWeightsData[matWeightIdx + inf];
  33864. if (weight > 0) {
  33865. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33866. finalMatrix.addToSelf(tempMatrix);
  33867. }
  33868. }
  33869. if (needExtras) {
  33870. for (inf = 0; inf < 4; inf++) {
  33871. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33872. if (weight > 0) {
  33873. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33874. finalMatrix.addToSelf(tempMatrix);
  33875. }
  33876. }
  33877. }
  33878. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33879. tempVector3.toArray(positionsData, index);
  33880. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33881. tempVector3.toArray(normalsData, index);
  33882. finalMatrix.reset();
  33883. }
  33884. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33885. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33886. return this;
  33887. };
  33888. // Tools
  33889. /**
  33890. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33891. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33892. */
  33893. Mesh.MinMax = function (meshes) {
  33894. var minVector = null;
  33895. var maxVector = null;
  33896. meshes.forEach(function (mesh, index, array) {
  33897. var boundingInfo = mesh.getBoundingInfo();
  33898. var boundingBox = boundingInfo.boundingBox;
  33899. if (!minVector || !maxVector) {
  33900. minVector = boundingBox.minimumWorld;
  33901. maxVector = boundingBox.maximumWorld;
  33902. }
  33903. else {
  33904. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33905. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33906. }
  33907. });
  33908. if (!minVector || !maxVector) {
  33909. return {
  33910. min: BABYLON.Vector3.Zero(),
  33911. max: BABYLON.Vector3.Zero()
  33912. };
  33913. }
  33914. return {
  33915. min: minVector,
  33916. max: maxVector
  33917. };
  33918. };
  33919. /**
  33920. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33921. */
  33922. Mesh.Center = function (meshesOrMinMaxVector) {
  33923. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33924. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33925. };
  33926. /**
  33927. * Merge the array of meshes into a single mesh for performance reasons.
  33928. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33929. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33930. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33931. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33932. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33933. */
  33934. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33935. if (disposeSource === void 0) { disposeSource = true; }
  33936. var index;
  33937. if (!allow32BitsIndices) {
  33938. var totalVertices = 0;
  33939. // Counting vertices
  33940. for (index = 0; index < meshes.length; index++) {
  33941. if (meshes[index]) {
  33942. totalVertices += meshes[index].getTotalVertices();
  33943. if (totalVertices > 65536) {
  33944. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33945. return null;
  33946. }
  33947. }
  33948. }
  33949. }
  33950. // Merge
  33951. var vertexData = null;
  33952. var otherVertexData;
  33953. var indiceArray = new Array();
  33954. var source = null;
  33955. for (index = 0; index < meshes.length; index++) {
  33956. if (meshes[index]) {
  33957. meshes[index].computeWorldMatrix(true);
  33958. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33959. otherVertexData.transform(meshes[index].getWorldMatrix());
  33960. if (vertexData) {
  33961. vertexData.merge(otherVertexData);
  33962. }
  33963. else {
  33964. vertexData = otherVertexData;
  33965. source = meshes[index];
  33966. }
  33967. if (subdivideWithSubMeshes) {
  33968. indiceArray.push(meshes[index].getTotalIndices());
  33969. }
  33970. }
  33971. }
  33972. source = source;
  33973. if (!meshSubclass) {
  33974. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33975. }
  33976. vertexData.applyToMesh(meshSubclass);
  33977. // Setting properties
  33978. meshSubclass.material = source.material;
  33979. meshSubclass.checkCollisions = source.checkCollisions;
  33980. // Cleaning
  33981. if (disposeSource) {
  33982. for (index = 0; index < meshes.length; index++) {
  33983. if (meshes[index]) {
  33984. meshes[index].dispose();
  33985. }
  33986. }
  33987. }
  33988. // Subdivide
  33989. if (subdivideWithSubMeshes) {
  33990. //-- removal of global submesh
  33991. meshSubclass.releaseSubMeshes();
  33992. index = 0;
  33993. var offset = 0;
  33994. //-- apply subdivision according to index table
  33995. while (index < indiceArray.length) {
  33996. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33997. offset += indiceArray[index];
  33998. index++;
  33999. }
  34000. }
  34001. return meshSubclass;
  34002. };
  34003. // Consts
  34004. Mesh._FRONTSIDE = 0;
  34005. Mesh._BACKSIDE = 1;
  34006. Mesh._DOUBLESIDE = 2;
  34007. Mesh._DEFAULTSIDE = 0;
  34008. Mesh._NO_CAP = 0;
  34009. Mesh._CAP_START = 1;
  34010. Mesh._CAP_END = 2;
  34011. Mesh._CAP_ALL = 3;
  34012. return Mesh;
  34013. }(BABYLON.AbstractMesh));
  34014. BABYLON.Mesh = Mesh;
  34015. })(BABYLON || (BABYLON = {}));
  34016. //# sourceMappingURL=babylon.mesh.js.map
  34017. var BABYLON;
  34018. (function (BABYLON) {
  34019. var BaseSubMesh = /** @class */ (function () {
  34020. function BaseSubMesh() {
  34021. }
  34022. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34023. get: function () {
  34024. return this._materialEffect;
  34025. },
  34026. enumerable: true,
  34027. configurable: true
  34028. });
  34029. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34030. if (defines === void 0) { defines = null; }
  34031. if (this._materialEffect === effect) {
  34032. if (!effect) {
  34033. this._materialDefines = null;
  34034. }
  34035. return;
  34036. }
  34037. this._materialDefines = defines;
  34038. this._materialEffect = effect;
  34039. };
  34040. return BaseSubMesh;
  34041. }());
  34042. BABYLON.BaseSubMesh = BaseSubMesh;
  34043. var SubMesh = /** @class */ (function (_super) {
  34044. __extends(SubMesh, _super);
  34045. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34046. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34047. var _this = _super.call(this) || this;
  34048. _this.materialIndex = materialIndex;
  34049. _this.verticesStart = verticesStart;
  34050. _this.verticesCount = verticesCount;
  34051. _this.indexStart = indexStart;
  34052. _this.indexCount = indexCount;
  34053. _this._renderId = 0;
  34054. _this._mesh = mesh;
  34055. _this._renderingMesh = renderingMesh || mesh;
  34056. mesh.subMeshes.push(_this);
  34057. _this._trianglePlanes = [];
  34058. _this._id = mesh.subMeshes.length - 1;
  34059. if (createBoundingBox) {
  34060. _this.refreshBoundingInfo();
  34061. mesh.computeWorldMatrix(true);
  34062. }
  34063. return _this;
  34064. }
  34065. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34066. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34067. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34068. };
  34069. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34070. get: function () {
  34071. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34072. },
  34073. enumerable: true,
  34074. configurable: true
  34075. });
  34076. /**
  34077. * Returns the submesh BoudingInfo object.
  34078. */
  34079. SubMesh.prototype.getBoundingInfo = function () {
  34080. if (this.IsGlobal) {
  34081. return this._mesh.getBoundingInfo();
  34082. }
  34083. return this._boundingInfo;
  34084. };
  34085. /**
  34086. * Sets the submesh BoundingInfo.
  34087. * Return the SubMesh.
  34088. */
  34089. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34090. this._boundingInfo = boundingInfo;
  34091. return this;
  34092. };
  34093. /**
  34094. * Returns the mesh of the current submesh.
  34095. */
  34096. SubMesh.prototype.getMesh = function () {
  34097. return this._mesh;
  34098. };
  34099. /**
  34100. * Returns the rendering mesh of the submesh.
  34101. */
  34102. SubMesh.prototype.getRenderingMesh = function () {
  34103. return this._renderingMesh;
  34104. };
  34105. /**
  34106. * Returns the submesh material.
  34107. */
  34108. SubMesh.prototype.getMaterial = function () {
  34109. var rootMaterial = this._renderingMesh.material;
  34110. if (rootMaterial === null || rootMaterial === undefined) {
  34111. return this._mesh.getScene().defaultMaterial;
  34112. }
  34113. else if (rootMaterial.getSubMaterial) {
  34114. var multiMaterial = rootMaterial;
  34115. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34116. if (this._currentMaterial !== effectiveMaterial) {
  34117. this._currentMaterial = effectiveMaterial;
  34118. this._materialDefines = null;
  34119. }
  34120. return effectiveMaterial;
  34121. }
  34122. return rootMaterial;
  34123. };
  34124. // Methods
  34125. /**
  34126. * Sets a new updated BoundingInfo object to the submesh.
  34127. * Returns the SubMesh.
  34128. */
  34129. SubMesh.prototype.refreshBoundingInfo = function () {
  34130. this._lastColliderWorldVertices = null;
  34131. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34132. return this;
  34133. }
  34134. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34135. if (!data) {
  34136. this._boundingInfo = this._mesh.getBoundingInfo();
  34137. return this;
  34138. }
  34139. var indices = this._renderingMesh.getIndices();
  34140. var extend;
  34141. //is this the only submesh?
  34142. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34143. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34144. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34145. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34146. }
  34147. else {
  34148. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34149. }
  34150. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34151. return this;
  34152. };
  34153. SubMesh.prototype._checkCollision = function (collider) {
  34154. var boundingInfo = this.getBoundingInfo();
  34155. return boundingInfo._checkCollision(collider);
  34156. };
  34157. /**
  34158. * Updates the submesh BoundingInfo.
  34159. * Returns the Submesh.
  34160. */
  34161. SubMesh.prototype.updateBoundingInfo = function (world) {
  34162. var boundingInfo = this.getBoundingInfo();
  34163. if (!boundingInfo) {
  34164. this.refreshBoundingInfo();
  34165. boundingInfo = this.getBoundingInfo();
  34166. }
  34167. boundingInfo.update(world);
  34168. return this;
  34169. };
  34170. /**
  34171. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34172. * Boolean returned.
  34173. */
  34174. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34175. var boundingInfo = this.getBoundingInfo();
  34176. if (!boundingInfo) {
  34177. return false;
  34178. }
  34179. return boundingInfo.isInFrustum(frustumPlanes);
  34180. };
  34181. /**
  34182. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34183. * Boolean returned.
  34184. */
  34185. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34186. var boundingInfo = this.getBoundingInfo();
  34187. if (!boundingInfo) {
  34188. return false;
  34189. }
  34190. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34191. };
  34192. /**
  34193. * Renders the submesh.
  34194. * Returns it.
  34195. */
  34196. SubMesh.prototype.render = function (enableAlphaMode) {
  34197. this._renderingMesh.render(this, enableAlphaMode);
  34198. return this;
  34199. };
  34200. /**
  34201. * Returns a new Index Buffer.
  34202. * Type returned : WebGLBuffer.
  34203. */
  34204. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34205. if (!this._linesIndexBuffer) {
  34206. var linesIndices = [];
  34207. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34208. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34209. }
  34210. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34211. this.linesIndexCount = linesIndices.length;
  34212. }
  34213. return this._linesIndexBuffer;
  34214. };
  34215. /**
  34216. * True is the passed Ray intersects the submesh bounding box.
  34217. * Boolean returned.
  34218. */
  34219. SubMesh.prototype.canIntersects = function (ray) {
  34220. var boundingInfo = this.getBoundingInfo();
  34221. if (!boundingInfo) {
  34222. return false;
  34223. }
  34224. return ray.intersectsBox(boundingInfo.boundingBox);
  34225. };
  34226. /**
  34227. * Returns an object IntersectionInfo.
  34228. */
  34229. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34230. var intersectInfo = null;
  34231. var material = this.getMaterial();
  34232. if (!material) {
  34233. return null;
  34234. }
  34235. switch (material.fillMode) {
  34236. case BABYLON.Material.PointListDrawMode:
  34237. case BABYLON.Material.LineListDrawMode:
  34238. case BABYLON.Material.LineLoopDrawMode:
  34239. case BABYLON.Material.LineStripDrawMode:
  34240. case BABYLON.Material.TriangleFanDrawMode:
  34241. case BABYLON.Material.TriangleStripDrawMode:
  34242. return null;
  34243. }
  34244. // LineMesh first as it's also a Mesh...
  34245. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34246. var lineMesh = this._mesh;
  34247. // Line test
  34248. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34249. var p0 = positions[indices[index]];
  34250. var p1 = positions[indices[index + 1]];
  34251. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34252. if (length < 0) {
  34253. continue;
  34254. }
  34255. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34256. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34257. if (fastCheck) {
  34258. break;
  34259. }
  34260. }
  34261. }
  34262. }
  34263. else {
  34264. // Triangles test
  34265. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34266. var p0 = positions[indices[index]];
  34267. var p1 = positions[indices[index + 1]];
  34268. var p2 = positions[indices[index + 2]];
  34269. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34270. if (currentIntersectInfo) {
  34271. if (currentIntersectInfo.distance < 0) {
  34272. continue;
  34273. }
  34274. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34275. intersectInfo = currentIntersectInfo;
  34276. intersectInfo.faceId = index / 3;
  34277. if (fastCheck) {
  34278. break;
  34279. }
  34280. }
  34281. }
  34282. }
  34283. }
  34284. return intersectInfo;
  34285. };
  34286. SubMesh.prototype._rebuild = function () {
  34287. if (this._linesIndexBuffer) {
  34288. this._linesIndexBuffer = null;
  34289. }
  34290. };
  34291. // Clone
  34292. /**
  34293. * Creates a new Submesh from the passed Mesh.
  34294. */
  34295. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34296. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34297. if (!this.IsGlobal) {
  34298. var boundingInfo = this.getBoundingInfo();
  34299. if (!boundingInfo) {
  34300. return result;
  34301. }
  34302. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34303. }
  34304. return result;
  34305. };
  34306. // Dispose
  34307. /**
  34308. * Disposes the Submesh.
  34309. * Returns nothing.
  34310. */
  34311. SubMesh.prototype.dispose = function () {
  34312. if (this._linesIndexBuffer) {
  34313. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34314. this._linesIndexBuffer = null;
  34315. }
  34316. // Remove from mesh
  34317. var index = this._mesh.subMeshes.indexOf(this);
  34318. this._mesh.subMeshes.splice(index, 1);
  34319. };
  34320. // Statics
  34321. /**
  34322. * Creates a new Submesh from the passed parameters :
  34323. * - materialIndex (integer) : the index of the main mesh material.
  34324. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34325. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34326. * - mesh (Mesh) : the main mesh to create the submesh from.
  34327. * - renderingMesh (optional Mesh) : rendering mesh.
  34328. */
  34329. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34330. var minVertexIndex = Number.MAX_VALUE;
  34331. var maxVertexIndex = -Number.MAX_VALUE;
  34332. renderingMesh = (renderingMesh || mesh);
  34333. var indices = renderingMesh.getIndices();
  34334. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34335. var vertexIndex = indices[index];
  34336. if (vertexIndex < minVertexIndex)
  34337. minVertexIndex = vertexIndex;
  34338. if (vertexIndex > maxVertexIndex)
  34339. maxVertexIndex = vertexIndex;
  34340. }
  34341. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34342. };
  34343. return SubMesh;
  34344. }(BaseSubMesh));
  34345. BABYLON.SubMesh = SubMesh;
  34346. })(BABYLON || (BABYLON = {}));
  34347. //# sourceMappingURL=babylon.subMesh.js.map
  34348. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34349. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34350. s = arguments[i];
  34351. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34352. t[p] = s[p];
  34353. }
  34354. return t;
  34355. };
  34356. var BABYLON;
  34357. (function (BABYLON) {
  34358. /**
  34359. * Manages the defines for the Material
  34360. */
  34361. var MaterialDefines = /** @class */ (function () {
  34362. function MaterialDefines() {
  34363. this._isDirty = true;
  34364. /** @hidden */
  34365. this._areLightsDirty = true;
  34366. /** @hidden */
  34367. this._areAttributesDirty = true;
  34368. /** @hidden */
  34369. this._areTexturesDirty = true;
  34370. /** @hidden */
  34371. this._areFresnelDirty = true;
  34372. /** @hidden */
  34373. this._areMiscDirty = true;
  34374. /** @hidden */
  34375. this._areImageProcessingDirty = true;
  34376. /** @hidden */
  34377. this._normals = false;
  34378. /** @hidden */
  34379. this._uvs = false;
  34380. /** @hidden */
  34381. this._needNormals = false;
  34382. /** @hidden */
  34383. this._needUVs = false;
  34384. }
  34385. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34386. /**
  34387. * Specifies if the material needs to be re-calculated
  34388. */
  34389. get: function () {
  34390. return this._isDirty;
  34391. },
  34392. enumerable: true,
  34393. configurable: true
  34394. });
  34395. /**
  34396. * Marks the material to indicate that it has been re-calculated
  34397. */
  34398. MaterialDefines.prototype.markAsProcessed = function () {
  34399. this._isDirty = false;
  34400. this._areAttributesDirty = false;
  34401. this._areTexturesDirty = false;
  34402. this._areFresnelDirty = false;
  34403. this._areLightsDirty = false;
  34404. this._areMiscDirty = false;
  34405. this._areImageProcessingDirty = false;
  34406. };
  34407. /**
  34408. * Marks the material to indicate that it needs to be re-calculated
  34409. */
  34410. MaterialDefines.prototype.markAsUnprocessed = function () {
  34411. this._isDirty = true;
  34412. };
  34413. /**
  34414. * Marks the material to indicate all of its defines need to be re-calculated
  34415. */
  34416. MaterialDefines.prototype.markAllAsDirty = function () {
  34417. this._areTexturesDirty = true;
  34418. this._areAttributesDirty = true;
  34419. this._areLightsDirty = true;
  34420. this._areFresnelDirty = true;
  34421. this._areMiscDirty = true;
  34422. this._areImageProcessingDirty = true;
  34423. this._isDirty = true;
  34424. };
  34425. /**
  34426. * Marks the material to indicate that image processing needs to be re-calculated
  34427. */
  34428. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34429. this._areImageProcessingDirty = true;
  34430. this._isDirty = true;
  34431. };
  34432. /**
  34433. * Marks the material to indicate the lights need to be re-calculated
  34434. */
  34435. MaterialDefines.prototype.markAsLightDirty = function () {
  34436. this._areLightsDirty = true;
  34437. this._isDirty = true;
  34438. };
  34439. /**
  34440. * Marks the attribute state as changed
  34441. */
  34442. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34443. this._areAttributesDirty = true;
  34444. this._isDirty = true;
  34445. };
  34446. /**
  34447. * Marks the texture state as changed
  34448. */
  34449. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34450. this._areTexturesDirty = true;
  34451. this._isDirty = true;
  34452. };
  34453. /**
  34454. * Marks the fresnel state as changed
  34455. */
  34456. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34457. this._areFresnelDirty = true;
  34458. this._isDirty = true;
  34459. };
  34460. /**
  34461. * Marks the misc state as changed
  34462. */
  34463. MaterialDefines.prototype.markAsMiscDirty = function () {
  34464. this._areMiscDirty = true;
  34465. this._isDirty = true;
  34466. };
  34467. /**
  34468. * Rebuilds the material defines
  34469. */
  34470. MaterialDefines.prototype.rebuild = function () {
  34471. if (this._keys) {
  34472. delete this._keys;
  34473. }
  34474. this._keys = [];
  34475. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34476. var key = _a[_i];
  34477. if (key[0] === "_") {
  34478. continue;
  34479. }
  34480. this._keys.push(key);
  34481. }
  34482. };
  34483. /**
  34484. * Specifies if two material defines are equal
  34485. * @param other - A material define instance to compare to
  34486. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34487. */
  34488. MaterialDefines.prototype.isEqual = function (other) {
  34489. if (this._keys.length !== other._keys.length) {
  34490. return false;
  34491. }
  34492. for (var index = 0; index < this._keys.length; index++) {
  34493. var prop = this._keys[index];
  34494. if (this[prop] !== other[prop]) {
  34495. return false;
  34496. }
  34497. }
  34498. return true;
  34499. };
  34500. /**
  34501. * Clones this instance's defines to another instance
  34502. * @param other - material defines to clone values to
  34503. */
  34504. MaterialDefines.prototype.cloneTo = function (other) {
  34505. if (this._keys.length !== other._keys.length) {
  34506. other._keys = this._keys.slice(0);
  34507. }
  34508. for (var index = 0; index < this._keys.length; index++) {
  34509. var prop = this._keys[index];
  34510. other[prop] = this[prop];
  34511. }
  34512. };
  34513. /**
  34514. * Resets the material define values
  34515. */
  34516. MaterialDefines.prototype.reset = function () {
  34517. for (var index = 0; index < this._keys.length; index++) {
  34518. var prop = this._keys[index];
  34519. var type = typeof this[prop];
  34520. switch (type) {
  34521. case "number":
  34522. this[prop] = 0;
  34523. break;
  34524. case "string":
  34525. this[prop] = "";
  34526. break;
  34527. default:
  34528. this[prop] = false;
  34529. break;
  34530. }
  34531. }
  34532. };
  34533. /**
  34534. * Converts the material define values to a string
  34535. * @returns - String of material define information
  34536. */
  34537. MaterialDefines.prototype.toString = function () {
  34538. var result = "";
  34539. for (var index = 0; index < this._keys.length; index++) {
  34540. var prop = this._keys[index];
  34541. var value = this[prop];
  34542. var type = typeof value;
  34543. switch (type) {
  34544. case "number":
  34545. case "string":
  34546. result += "#define " + prop + " " + value + "\n";
  34547. break;
  34548. default:
  34549. if (value) {
  34550. result += "#define " + prop + "\n";
  34551. }
  34552. break;
  34553. }
  34554. }
  34555. return result;
  34556. };
  34557. return MaterialDefines;
  34558. }());
  34559. BABYLON.MaterialDefines = MaterialDefines;
  34560. /**
  34561. * Base class for the main features of a material in Babylon.js
  34562. */
  34563. var Material = /** @class */ (function () {
  34564. /**
  34565. * Creates a material instance
  34566. * @param name defines the name of the material
  34567. * @param scene defines the scene to reference
  34568. * @param doNotAdd specifies if the material should be added to the scene
  34569. */
  34570. function Material(name, scene, doNotAdd) {
  34571. /**
  34572. * Specifies if the ready state should be checked on each call
  34573. */
  34574. this.checkReadyOnEveryCall = false;
  34575. /**
  34576. * Specifies if the ready state should be checked once
  34577. */
  34578. this.checkReadyOnlyOnce = false;
  34579. /**
  34580. * The state of the material
  34581. */
  34582. this.state = "";
  34583. /**
  34584. * The alpha value of the material
  34585. */
  34586. this._alpha = 1.0;
  34587. /**
  34588. * Specifies if back face culling is enabled
  34589. */
  34590. this._backFaceCulling = true;
  34591. /**
  34592. * Specifies if the material should be serialized
  34593. */
  34594. this.doNotSerialize = false;
  34595. /**
  34596. * Specifies if the effect should be stored on sub meshes
  34597. */
  34598. this.storeEffectOnSubMeshes = false;
  34599. /**
  34600. * An event triggered when the material is disposed
  34601. */
  34602. this.onDisposeObservable = new BABYLON.Observable();
  34603. /**
  34604. * An event triggered when the material is bound
  34605. */
  34606. this.onBindObservable = new BABYLON.Observable();
  34607. /**
  34608. * An event triggered when the material is unbound
  34609. */
  34610. this.onUnBindObservable = new BABYLON.Observable();
  34611. /**
  34612. * Stores the value of the alpha mode
  34613. */
  34614. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34615. /**
  34616. * Stores the state of the need depth pre-pass value
  34617. */
  34618. this._needDepthPrePass = false;
  34619. /**
  34620. * Specifies if depth writing should be disabled
  34621. */
  34622. this.disableDepthWrite = false;
  34623. /**
  34624. * Specifies if depth writing should be forced
  34625. */
  34626. this.forceDepthWrite = false;
  34627. /**
  34628. * Specifies if there should be a separate pass for culling
  34629. */
  34630. this.separateCullingPass = false;
  34631. /**
  34632. * Stores the state specifing if fog should be enabled
  34633. */
  34634. this._fogEnabled = true;
  34635. /**
  34636. * Stores the size of points
  34637. */
  34638. this.pointSize = 1.0;
  34639. /**
  34640. * Stores the z offset value
  34641. */
  34642. this.zOffset = 0;
  34643. /**
  34644. * Specifies if the material was previously ready
  34645. */
  34646. this._wasPreviouslyReady = false;
  34647. /**
  34648. * Stores the fill mode state
  34649. */
  34650. this._fillMode = Material.TriangleFillMode;
  34651. this.name = name;
  34652. this.id = name || BABYLON.Tools.RandomId();
  34653. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34654. this.uniqueId = this._scene.getUniqueId();
  34655. if (this._scene.useRightHandedSystem) {
  34656. this.sideOrientation = Material.ClockWiseSideOrientation;
  34657. }
  34658. else {
  34659. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34660. }
  34661. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34662. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34663. if (!doNotAdd) {
  34664. this._scene.materials.push(this);
  34665. }
  34666. }
  34667. Object.defineProperty(Material, "TriangleFillMode", {
  34668. /**
  34669. * Returns the triangle fill mode
  34670. */
  34671. get: function () {
  34672. return Material._TriangleFillMode;
  34673. },
  34674. enumerable: true,
  34675. configurable: true
  34676. });
  34677. Object.defineProperty(Material, "WireFrameFillMode", {
  34678. /**
  34679. * Returns the wireframe mode
  34680. */
  34681. get: function () {
  34682. return Material._WireFrameFillMode;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(Material, "PointFillMode", {
  34688. /**
  34689. * Returns the point fill mode
  34690. */
  34691. get: function () {
  34692. return Material._PointFillMode;
  34693. },
  34694. enumerable: true,
  34695. configurable: true
  34696. });
  34697. Object.defineProperty(Material, "PointListDrawMode", {
  34698. /**
  34699. * Returns the point list draw mode
  34700. */
  34701. get: function () {
  34702. return Material._PointListDrawMode;
  34703. },
  34704. enumerable: true,
  34705. configurable: true
  34706. });
  34707. Object.defineProperty(Material, "LineListDrawMode", {
  34708. /**
  34709. * Returns the line list draw mode
  34710. */
  34711. get: function () {
  34712. return Material._LineListDrawMode;
  34713. },
  34714. enumerable: true,
  34715. configurable: true
  34716. });
  34717. Object.defineProperty(Material, "LineLoopDrawMode", {
  34718. /**
  34719. * Returns the line loop draw mode
  34720. */
  34721. get: function () {
  34722. return Material._LineLoopDrawMode;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. Object.defineProperty(Material, "LineStripDrawMode", {
  34728. /**
  34729. * Returns the line strip draw mode
  34730. */
  34731. get: function () {
  34732. return Material._LineStripDrawMode;
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34738. /**
  34739. * Returns the triangle strip draw mode
  34740. */
  34741. get: function () {
  34742. return Material._TriangleStripDrawMode;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34748. /**
  34749. * Returns the triangle fan draw mode
  34750. */
  34751. get: function () {
  34752. return Material._TriangleFanDrawMode;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34758. /**
  34759. * Returns the clock-wise side orientation
  34760. */
  34761. get: function () {
  34762. return Material._ClockWiseSideOrientation;
  34763. },
  34764. enumerable: true,
  34765. configurable: true
  34766. });
  34767. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34768. /**
  34769. * Returns the counter clock-wise side orientation
  34770. */
  34771. get: function () {
  34772. return Material._CounterClockWiseSideOrientation;
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(Material, "TextureDirtyFlag", {
  34778. /**
  34779. * Returns the dirty texture flag value
  34780. */
  34781. get: function () {
  34782. return Material._TextureDirtyFlag;
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material, "LightDirtyFlag", {
  34788. /**
  34789. * Returns the dirty light flag value
  34790. */
  34791. get: function () {
  34792. return Material._LightDirtyFlag;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34798. /**
  34799. * Returns the dirty fresnel flag value
  34800. */
  34801. get: function () {
  34802. return Material._FresnelDirtyFlag;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34808. /**
  34809. * Returns the dirty attributes flag value
  34810. */
  34811. get: function () {
  34812. return Material._AttributesDirtyFlag;
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(Material, "MiscDirtyFlag", {
  34818. /**
  34819. * Returns the dirty misc flag value
  34820. */
  34821. get: function () {
  34822. return Material._MiscDirtyFlag;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material.prototype, "alpha", {
  34828. /**
  34829. * Gets the alpha value of the material
  34830. */
  34831. get: function () {
  34832. return this._alpha;
  34833. },
  34834. /**
  34835. * Sets the alpha value of the material
  34836. */
  34837. set: function (value) {
  34838. if (this._alpha === value) {
  34839. return;
  34840. }
  34841. this._alpha = value;
  34842. this.markAsDirty(Material.MiscDirtyFlag);
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34848. /**
  34849. * Gets the back-face culling state
  34850. */
  34851. get: function () {
  34852. return this._backFaceCulling;
  34853. },
  34854. /**
  34855. * Sets the back-face culling state
  34856. */
  34857. set: function (value) {
  34858. if (this._backFaceCulling === value) {
  34859. return;
  34860. }
  34861. this._backFaceCulling = value;
  34862. this.markAsDirty(Material.TextureDirtyFlag);
  34863. },
  34864. enumerable: true,
  34865. configurable: true
  34866. });
  34867. Object.defineProperty(Material.prototype, "onDispose", {
  34868. /**
  34869. * Called during a dispose event
  34870. */
  34871. set: function (callback) {
  34872. if (this._onDisposeObserver) {
  34873. this.onDisposeObservable.remove(this._onDisposeObserver);
  34874. }
  34875. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34876. },
  34877. enumerable: true,
  34878. configurable: true
  34879. });
  34880. Object.defineProperty(Material.prototype, "onBind", {
  34881. /**
  34882. * Called during a bind event
  34883. */
  34884. set: function (callback) {
  34885. if (this._onBindObserver) {
  34886. this.onBindObservable.remove(this._onBindObserver);
  34887. }
  34888. this._onBindObserver = this.onBindObservable.add(callback);
  34889. },
  34890. enumerable: true,
  34891. configurable: true
  34892. });
  34893. Object.defineProperty(Material.prototype, "alphaMode", {
  34894. /**
  34895. * Gets the value of the alpha mode
  34896. */
  34897. get: function () {
  34898. return this._alphaMode;
  34899. },
  34900. /**
  34901. * Sets the value of the alpha mode.
  34902. *
  34903. * | Value | Type | Description |
  34904. * | --- | --- | --- |
  34905. * | 0 | ALPHA_DISABLE | |
  34906. * | 1 | ALPHA_ADD | |
  34907. * | 2 | ALPHA_COMBINE | |
  34908. * | 3 | ALPHA_SUBTRACT | |
  34909. * | 4 | ALPHA_MULTIPLY | |
  34910. * | 5 | ALPHA_MAXIMIZED | |
  34911. * | 6 | ALPHA_ONEONE | |
  34912. * | 7 | ALPHA_PREMULTIPLIED | |
  34913. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34914. * | 9 | ALPHA_INTERPOLATE | |
  34915. * | 10 | ALPHA_SCREENMODE | |
  34916. *
  34917. */
  34918. set: function (value) {
  34919. if (this._alphaMode === value) {
  34920. return;
  34921. }
  34922. this._alphaMode = value;
  34923. this.markAsDirty(Material.TextureDirtyFlag);
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34929. /**
  34930. * Gets the depth pre-pass value
  34931. */
  34932. get: function () {
  34933. return this._needDepthPrePass;
  34934. },
  34935. /**
  34936. * Sets the need depth pre-pass value
  34937. */
  34938. set: function (value) {
  34939. if (this._needDepthPrePass === value) {
  34940. return;
  34941. }
  34942. this._needDepthPrePass = value;
  34943. if (this._needDepthPrePass) {
  34944. this.checkReadyOnEveryCall = true;
  34945. }
  34946. },
  34947. enumerable: true,
  34948. configurable: true
  34949. });
  34950. Object.defineProperty(Material.prototype, "fogEnabled", {
  34951. /**
  34952. * Gets the value of the fog enabled state
  34953. */
  34954. get: function () {
  34955. return this._fogEnabled;
  34956. },
  34957. /**
  34958. * Sets the state for enabling fog
  34959. */
  34960. set: function (value) {
  34961. if (this._fogEnabled === value) {
  34962. return;
  34963. }
  34964. this._fogEnabled = value;
  34965. this.markAsDirty(Material.MiscDirtyFlag);
  34966. },
  34967. enumerable: true,
  34968. configurable: true
  34969. });
  34970. Object.defineProperty(Material.prototype, "wireframe", {
  34971. /**
  34972. * Gets a value specifying if wireframe mode is enabled
  34973. */
  34974. get: function () {
  34975. switch (this._fillMode) {
  34976. case Material.WireFrameFillMode:
  34977. case Material.LineListDrawMode:
  34978. case Material.LineLoopDrawMode:
  34979. case Material.LineStripDrawMode:
  34980. return true;
  34981. }
  34982. return this._scene.forceWireframe;
  34983. },
  34984. /**
  34985. * Sets the state of wireframe mode
  34986. */
  34987. set: function (value) {
  34988. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34989. },
  34990. enumerable: true,
  34991. configurable: true
  34992. });
  34993. Object.defineProperty(Material.prototype, "pointsCloud", {
  34994. /**
  34995. * Gets the value specifying if point clouds are enabled
  34996. */
  34997. get: function () {
  34998. switch (this._fillMode) {
  34999. case Material.PointFillMode:
  35000. case Material.PointListDrawMode:
  35001. return true;
  35002. }
  35003. return this._scene.forcePointsCloud;
  35004. },
  35005. /**
  35006. * Sets the state of point cloud mode
  35007. */
  35008. set: function (value) {
  35009. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35010. },
  35011. enumerable: true,
  35012. configurable: true
  35013. });
  35014. Object.defineProperty(Material.prototype, "fillMode", {
  35015. /**
  35016. * Gets the material fill mode
  35017. */
  35018. get: function () {
  35019. return this._fillMode;
  35020. },
  35021. /**
  35022. * Sets the material fill mode
  35023. */
  35024. set: function (value) {
  35025. if (this._fillMode === value) {
  35026. return;
  35027. }
  35028. this._fillMode = value;
  35029. this.markAsDirty(Material.MiscDirtyFlag);
  35030. },
  35031. enumerable: true,
  35032. configurable: true
  35033. });
  35034. /**
  35035. * Returns a string representation of the current material
  35036. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35037. * @returns a string with material information
  35038. */
  35039. Material.prototype.toString = function (fullDetails) {
  35040. var ret = "Name: " + this.name;
  35041. if (fullDetails) {
  35042. }
  35043. return ret;
  35044. };
  35045. /**
  35046. * Gets the class name of the material
  35047. * @returns a string with the class name of the material
  35048. */
  35049. Material.prototype.getClassName = function () {
  35050. return "Material";
  35051. };
  35052. Object.defineProperty(Material.prototype, "isFrozen", {
  35053. /**
  35054. * Specifies if updates for the material been locked
  35055. */
  35056. get: function () {
  35057. return this.checkReadyOnlyOnce;
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. /**
  35063. * Locks updates for the material
  35064. */
  35065. Material.prototype.freeze = function () {
  35066. this.checkReadyOnlyOnce = true;
  35067. };
  35068. /**
  35069. * Unlocks updates for the material
  35070. */
  35071. Material.prototype.unfreeze = function () {
  35072. this.checkReadyOnlyOnce = false;
  35073. };
  35074. /**
  35075. * Specifies if the material is ready to be used
  35076. * @param mesh defines the mesh to check
  35077. * @param useInstances specifies if instances should be used
  35078. * @returns a boolean indicating if the material is ready to be used
  35079. */
  35080. Material.prototype.isReady = function (mesh, useInstances) {
  35081. return true;
  35082. };
  35083. /**
  35084. * Specifies that the submesh is ready to be used
  35085. * @param mesh defines the mesh to check
  35086. * @param subMesh defines which submesh to check
  35087. * @param useInstances specifies that instances should be used
  35088. * @returns a boolean indicating that the submesh is ready or not
  35089. */
  35090. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35091. return false;
  35092. };
  35093. /**
  35094. * Returns the material effect
  35095. * @returns the effect associated with the material
  35096. */
  35097. Material.prototype.getEffect = function () {
  35098. return this._effect;
  35099. };
  35100. /**
  35101. * Returns the current scene
  35102. * @returns a Scene
  35103. */
  35104. Material.prototype.getScene = function () {
  35105. return this._scene;
  35106. };
  35107. /**
  35108. * Specifies if the material will require alpha blending
  35109. * @returns a boolean specifying if alpha blending is needed
  35110. */
  35111. Material.prototype.needAlphaBlending = function () {
  35112. return (this.alpha < 1.0);
  35113. };
  35114. /**
  35115. * Specifies if the mesh will require alpha blending
  35116. * @param mesh defines the mesh to check
  35117. * @returns a boolean specifying if alpha blending is needed for the mesh
  35118. */
  35119. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35120. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35121. };
  35122. /**
  35123. * Specifies if this material should be rendered in alpha test mode
  35124. * @returns a boolean specifying if an alpha test is needed.
  35125. */
  35126. Material.prototype.needAlphaTesting = function () {
  35127. return false;
  35128. };
  35129. /**
  35130. * Gets the texture used for the alpha test
  35131. * @returns the texture to use for alpha testing
  35132. */
  35133. Material.prototype.getAlphaTestTexture = function () {
  35134. return null;
  35135. };
  35136. /**
  35137. * Marks the material to indicate that it needs to be re-calculated
  35138. */
  35139. Material.prototype.markDirty = function () {
  35140. this._wasPreviouslyReady = false;
  35141. };
  35142. /** @hidden */
  35143. Material.prototype._preBind = function (effect, overrideOrientation) {
  35144. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35145. var engine = this._scene.getEngine();
  35146. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35147. var reverse = orientation === Material.ClockWiseSideOrientation;
  35148. engine.enableEffect(effect ? effect : this._effect);
  35149. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35150. return reverse;
  35151. };
  35152. /**
  35153. * Binds the material to the mesh
  35154. * @param world defines the world transformation matrix
  35155. * @param mesh defines the mesh to bind the material to
  35156. */
  35157. Material.prototype.bind = function (world, mesh) {
  35158. };
  35159. /**
  35160. * Binds the submesh to the material
  35161. * @param world defines the world transformation matrix
  35162. * @param mesh defines the mesh containing the submesh
  35163. * @param subMesh defines the submesh to bind the material to
  35164. */
  35165. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35166. };
  35167. /**
  35168. * Binds the world matrix to the material
  35169. * @param world defines the world transformation matrix
  35170. */
  35171. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35172. };
  35173. /**
  35174. * Binds the scene's uniform buffer to the effect.
  35175. * @param effect defines the effect to bind to the scene uniform buffer
  35176. * @param sceneUbo defines the uniform buffer storing scene data
  35177. */
  35178. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35179. sceneUbo.bindToEffect(effect, "Scene");
  35180. };
  35181. /**
  35182. * Binds the view matrix to the effect
  35183. * @param effect defines the effect to bind the view matrix to
  35184. */
  35185. Material.prototype.bindView = function (effect) {
  35186. if (!this._useUBO) {
  35187. effect.setMatrix("view", this.getScene().getViewMatrix());
  35188. }
  35189. else {
  35190. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35191. }
  35192. };
  35193. /**
  35194. * Binds the view projection matrix to the effect
  35195. * @param effect defines the effect to bind the view projection matrix to
  35196. */
  35197. Material.prototype.bindViewProjection = function (effect) {
  35198. if (!this._useUBO) {
  35199. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35200. }
  35201. else {
  35202. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35203. }
  35204. };
  35205. /**
  35206. * Specifies if material alpha testing should be turned on for the mesh
  35207. * @param mesh defines the mesh to check
  35208. */
  35209. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35210. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35211. };
  35212. /**
  35213. * Processes to execute after binding the material to a mesh
  35214. * @param mesh defines the rendered mesh
  35215. */
  35216. Material.prototype._afterBind = function (mesh) {
  35217. this._scene._cachedMaterial = this;
  35218. if (mesh) {
  35219. this._scene._cachedVisibility = mesh.visibility;
  35220. }
  35221. else {
  35222. this._scene._cachedVisibility = 1;
  35223. }
  35224. if (mesh) {
  35225. this.onBindObservable.notifyObservers(mesh);
  35226. }
  35227. if (this.disableDepthWrite) {
  35228. var engine = this._scene.getEngine();
  35229. this._cachedDepthWriteState = engine.getDepthWrite();
  35230. engine.setDepthWrite(false);
  35231. }
  35232. };
  35233. /**
  35234. * Unbinds the material from the mesh
  35235. */
  35236. Material.prototype.unbind = function () {
  35237. this.onUnBindObservable.notifyObservers(this);
  35238. if (this.disableDepthWrite) {
  35239. var engine = this._scene.getEngine();
  35240. engine.setDepthWrite(this._cachedDepthWriteState);
  35241. }
  35242. };
  35243. /**
  35244. * Gets the active textures from the material
  35245. * @returns an array of textures
  35246. */
  35247. Material.prototype.getActiveTextures = function () {
  35248. return [];
  35249. };
  35250. /**
  35251. * Specifies if the material uses a texture
  35252. * @param texture defines the texture to check against the material
  35253. * @returns a boolean specifying if the material uses the texture
  35254. */
  35255. Material.prototype.hasTexture = function (texture) {
  35256. return false;
  35257. };
  35258. /**
  35259. * Makes a duplicate of the material, and gives it a new name
  35260. * @param name defines the new name for the duplicated material
  35261. * @returns the cloned material
  35262. */
  35263. Material.prototype.clone = function (name) {
  35264. return null;
  35265. };
  35266. /**
  35267. * Gets the meshes bound to the material
  35268. * @returns an array of meshes bound to the material
  35269. */
  35270. Material.prototype.getBindedMeshes = function () {
  35271. var result = new Array();
  35272. for (var index = 0; index < this._scene.meshes.length; index++) {
  35273. var mesh = this._scene.meshes[index];
  35274. if (mesh.material === this) {
  35275. result.push(mesh);
  35276. }
  35277. }
  35278. return result;
  35279. };
  35280. /**
  35281. * Force shader compilation
  35282. * @param mesh defines the mesh associated with this material
  35283. * @param onCompiled defines a function to execute once the material is compiled
  35284. * @param options defines the options to configure the compilation
  35285. */
  35286. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35287. var _this = this;
  35288. var localOptions = __assign({ clipPlane: false }, options);
  35289. var subMesh = new BABYLON.BaseSubMesh();
  35290. var scene = this.getScene();
  35291. var checkReady = function () {
  35292. if (!_this._scene || !_this._scene.getEngine()) {
  35293. return;
  35294. }
  35295. if (subMesh._materialDefines) {
  35296. subMesh._materialDefines._renderId = -1;
  35297. }
  35298. var clipPlaneState = scene.clipPlane;
  35299. if (localOptions.clipPlane) {
  35300. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35301. }
  35302. if (_this.storeEffectOnSubMeshes) {
  35303. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35304. if (onCompiled) {
  35305. onCompiled(_this);
  35306. }
  35307. }
  35308. else {
  35309. setTimeout(checkReady, 16);
  35310. }
  35311. }
  35312. else {
  35313. if (_this.isReady(mesh)) {
  35314. if (onCompiled) {
  35315. onCompiled(_this);
  35316. }
  35317. }
  35318. else {
  35319. setTimeout(checkReady, 16);
  35320. }
  35321. }
  35322. if (localOptions.clipPlane) {
  35323. scene.clipPlane = clipPlaneState;
  35324. }
  35325. };
  35326. checkReady();
  35327. };
  35328. /**
  35329. * Force shader compilation
  35330. * @param mesh defines the mesh that will use this material
  35331. * @param options defines additional options for compiling the shaders
  35332. * @returns a promise that resolves when the compilation completes
  35333. */
  35334. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35335. var _this = this;
  35336. return new Promise(function (resolve) {
  35337. _this.forceCompilation(mesh, function () {
  35338. resolve();
  35339. }, options);
  35340. });
  35341. };
  35342. /**
  35343. * Marks a define in the material to indicate that it needs to be re-computed
  35344. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35345. */
  35346. Material.prototype.markAsDirty = function (flag) {
  35347. if (flag & Material.TextureDirtyFlag) {
  35348. this._markAllSubMeshesAsTexturesDirty();
  35349. }
  35350. if (flag & Material.LightDirtyFlag) {
  35351. this._markAllSubMeshesAsLightsDirty();
  35352. }
  35353. if (flag & Material.FresnelDirtyFlag) {
  35354. this._markAllSubMeshesAsFresnelDirty();
  35355. }
  35356. if (flag & Material.AttributesDirtyFlag) {
  35357. this._markAllSubMeshesAsAttributesDirty();
  35358. }
  35359. if (flag & Material.MiscDirtyFlag) {
  35360. this._markAllSubMeshesAsMiscDirty();
  35361. }
  35362. this.getScene().resetCachedMaterial();
  35363. };
  35364. /**
  35365. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35366. * @param func defines a function which checks material defines against the submeshes
  35367. */
  35368. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35369. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35370. var mesh = _a[_i];
  35371. if (!mesh.subMeshes) {
  35372. continue;
  35373. }
  35374. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35375. var subMesh = _c[_b];
  35376. if (subMesh.getMaterial() !== this) {
  35377. continue;
  35378. }
  35379. if (!subMesh._materialDefines) {
  35380. continue;
  35381. }
  35382. func(subMesh._materialDefines);
  35383. }
  35384. }
  35385. };
  35386. /**
  35387. * Indicates that image processing needs to be re-calculated for all submeshes
  35388. */
  35389. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35390. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35391. };
  35392. /**
  35393. * Indicates that textures need to be re-calculated for all submeshes
  35394. */
  35395. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35396. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35397. };
  35398. /**
  35399. * Indicates that fresnel needs to be re-calculated for all submeshes
  35400. */
  35401. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35402. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35403. };
  35404. /**
  35405. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35406. */
  35407. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35408. this._markAllSubMeshesAsDirty(function (defines) {
  35409. defines.markAsFresnelDirty();
  35410. defines.markAsMiscDirty();
  35411. });
  35412. };
  35413. /**
  35414. * Indicates that lights need to be re-calculated for all submeshes
  35415. */
  35416. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35417. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35418. };
  35419. /**
  35420. * Indicates that attributes need to be re-calculated for all submeshes
  35421. */
  35422. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35423. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35424. };
  35425. /**
  35426. * Indicates that misc needs to be re-calculated for all submeshes
  35427. */
  35428. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35429. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35430. };
  35431. /**
  35432. * Indicates that textures and misc need to be re-calculated for all submeshes
  35433. */
  35434. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35435. this._markAllSubMeshesAsDirty(function (defines) {
  35436. defines.markAsTexturesDirty();
  35437. defines.markAsMiscDirty();
  35438. });
  35439. };
  35440. /**
  35441. * Disposes the material
  35442. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35443. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35444. */
  35445. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35446. // Animations
  35447. this.getScene().stopAnimation(this);
  35448. this.getScene().freeProcessedMaterials();
  35449. // Remove from scene
  35450. var index = this._scene.materials.indexOf(this);
  35451. if (index >= 0) {
  35452. this._scene.materials.splice(index, 1);
  35453. }
  35454. // Remove from meshes
  35455. for (index = 0; index < this._scene.meshes.length; index++) {
  35456. var mesh = this._scene.meshes[index];
  35457. if (mesh.material === this) {
  35458. mesh.material = null;
  35459. if (mesh.geometry) {
  35460. var geometry = (mesh.geometry);
  35461. if (this.storeEffectOnSubMeshes) {
  35462. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35463. var subMesh = _a[_i];
  35464. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35465. if (forceDisposeEffect && subMesh._materialEffect) {
  35466. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35467. }
  35468. }
  35469. }
  35470. else {
  35471. geometry._releaseVertexArrayObject(this._effect);
  35472. }
  35473. }
  35474. }
  35475. }
  35476. this._uniformBuffer.dispose();
  35477. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35478. if (forceDisposeEffect && this._effect) {
  35479. if (!this.storeEffectOnSubMeshes) {
  35480. this._scene.getEngine()._releaseEffect(this._effect);
  35481. }
  35482. this._effect = null;
  35483. }
  35484. // Callback
  35485. this.onDisposeObservable.notifyObservers(this);
  35486. this.onDisposeObservable.clear();
  35487. this.onBindObservable.clear();
  35488. this.onUnBindObservable.clear();
  35489. };
  35490. /**
  35491. * Serializes this material
  35492. * @returns the serialized material object
  35493. */
  35494. Material.prototype.serialize = function () {
  35495. return BABYLON.SerializationHelper.Serialize(this);
  35496. };
  35497. /**
  35498. * Creates a MultiMaterial from parsed MultiMaterial data.
  35499. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35500. * @param scene defines the hosting scene
  35501. * @returns a new MultiMaterial
  35502. */
  35503. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35504. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35505. multiMaterial.id = parsedMultiMaterial.id;
  35506. if (BABYLON.Tags) {
  35507. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35508. }
  35509. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35510. var subMatId = parsedMultiMaterial.materials[matIndex];
  35511. if (subMatId) {
  35512. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35513. }
  35514. else {
  35515. multiMaterial.subMaterials.push(null);
  35516. }
  35517. }
  35518. return multiMaterial;
  35519. };
  35520. /**
  35521. * Creates a material from parsed material data
  35522. * @param parsedMaterial defines parsed material data
  35523. * @param scene defines the hosting scene
  35524. * @param rootUrl defines the root URL to use to load textures
  35525. * @returns a new material
  35526. */
  35527. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35528. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35529. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35530. }
  35531. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35532. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35533. if (!BABYLON.LegacyPBRMaterial) {
  35534. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35535. return;
  35536. }
  35537. }
  35538. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35539. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35540. };
  35541. // Triangle views
  35542. Material._TriangleFillMode = 0;
  35543. Material._WireFrameFillMode = 1;
  35544. Material._PointFillMode = 2;
  35545. // Draw modes
  35546. Material._PointListDrawMode = 3;
  35547. Material._LineListDrawMode = 4;
  35548. Material._LineLoopDrawMode = 5;
  35549. Material._LineStripDrawMode = 6;
  35550. Material._TriangleStripDrawMode = 7;
  35551. Material._TriangleFanDrawMode = 8;
  35552. /**
  35553. * Stores the clock-wise side orientation
  35554. */
  35555. Material._ClockWiseSideOrientation = 0;
  35556. /**
  35557. * Stores the counter clock-wise side orientation
  35558. */
  35559. Material._CounterClockWiseSideOrientation = 1;
  35560. /**
  35561. * The dirty texture flag value
  35562. */
  35563. Material._TextureDirtyFlag = 1;
  35564. /**
  35565. * The dirty light flag value
  35566. */
  35567. Material._LightDirtyFlag = 2;
  35568. /**
  35569. * The dirty fresnel flag value
  35570. */
  35571. Material._FresnelDirtyFlag = 4;
  35572. /**
  35573. * The dirty attribute flag value
  35574. */
  35575. Material._AttributesDirtyFlag = 8;
  35576. /**
  35577. * The dirty misc flag value
  35578. */
  35579. Material._MiscDirtyFlag = 16;
  35580. __decorate([
  35581. BABYLON.serialize()
  35582. ], Material.prototype, "id", void 0);
  35583. __decorate([
  35584. BABYLON.serialize()
  35585. ], Material.prototype, "uniqueId", void 0);
  35586. __decorate([
  35587. BABYLON.serialize()
  35588. ], Material.prototype, "name", void 0);
  35589. __decorate([
  35590. BABYLON.serialize()
  35591. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35592. __decorate([
  35593. BABYLON.serialize()
  35594. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35595. __decorate([
  35596. BABYLON.serialize()
  35597. ], Material.prototype, "state", void 0);
  35598. __decorate([
  35599. BABYLON.serialize("alpha")
  35600. ], Material.prototype, "_alpha", void 0);
  35601. __decorate([
  35602. BABYLON.serialize("backFaceCulling")
  35603. ], Material.prototype, "_backFaceCulling", void 0);
  35604. __decorate([
  35605. BABYLON.serialize()
  35606. ], Material.prototype, "sideOrientation", void 0);
  35607. __decorate([
  35608. BABYLON.serialize("alphaMode")
  35609. ], Material.prototype, "_alphaMode", void 0);
  35610. __decorate([
  35611. BABYLON.serialize()
  35612. ], Material.prototype, "_needDepthPrePass", void 0);
  35613. __decorate([
  35614. BABYLON.serialize()
  35615. ], Material.prototype, "disableDepthWrite", void 0);
  35616. __decorate([
  35617. BABYLON.serialize()
  35618. ], Material.prototype, "forceDepthWrite", void 0);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], Material.prototype, "separateCullingPass", void 0);
  35622. __decorate([
  35623. BABYLON.serialize("fogEnabled")
  35624. ], Material.prototype, "_fogEnabled", void 0);
  35625. __decorate([
  35626. BABYLON.serialize()
  35627. ], Material.prototype, "pointSize", void 0);
  35628. __decorate([
  35629. BABYLON.serialize()
  35630. ], Material.prototype, "zOffset", void 0);
  35631. __decorate([
  35632. BABYLON.serialize()
  35633. ], Material.prototype, "wireframe", null);
  35634. __decorate([
  35635. BABYLON.serialize()
  35636. ], Material.prototype, "pointsCloud", null);
  35637. __decorate([
  35638. BABYLON.serialize()
  35639. ], Material.prototype, "fillMode", null);
  35640. return Material;
  35641. }());
  35642. BABYLON.Material = Material;
  35643. })(BABYLON || (BABYLON = {}));
  35644. //# sourceMappingURL=babylon.material.js.map
  35645. var BABYLON;
  35646. (function (BABYLON) {
  35647. var UniformBuffer = /** @class */ (function () {
  35648. /**
  35649. * Uniform buffer objects.
  35650. *
  35651. * Handles blocks of uniform on the GPU.
  35652. *
  35653. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35654. *
  35655. * For more information, please refer to :
  35656. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35657. */
  35658. function UniformBuffer(engine, data, dynamic) {
  35659. this._engine = engine;
  35660. this._noUBO = !engine.supportsUniformBuffers;
  35661. this._dynamic = dynamic;
  35662. this._data = data || [];
  35663. this._uniformLocations = {};
  35664. this._uniformSizes = {};
  35665. this._uniformLocationPointer = 0;
  35666. this._needSync = false;
  35667. if (this._noUBO) {
  35668. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35669. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35670. this.updateFloat = this._updateFloatForEffect;
  35671. this.updateFloat2 = this._updateFloat2ForEffect;
  35672. this.updateFloat3 = this._updateFloat3ForEffect;
  35673. this.updateFloat4 = this._updateFloat4ForEffect;
  35674. this.updateMatrix = this._updateMatrixForEffect;
  35675. this.updateVector3 = this._updateVector3ForEffect;
  35676. this.updateVector4 = this._updateVector4ForEffect;
  35677. this.updateColor3 = this._updateColor3ForEffect;
  35678. this.updateColor4 = this._updateColor4ForEffect;
  35679. }
  35680. else {
  35681. this._engine._uniformBuffers.push(this);
  35682. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35683. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35684. this.updateFloat = this._updateFloatForUniform;
  35685. this.updateFloat2 = this._updateFloat2ForUniform;
  35686. this.updateFloat3 = this._updateFloat3ForUniform;
  35687. this.updateFloat4 = this._updateFloat4ForUniform;
  35688. this.updateMatrix = this._updateMatrixForUniform;
  35689. this.updateVector3 = this._updateVector3ForUniform;
  35690. this.updateVector4 = this._updateVector4ForUniform;
  35691. this.updateColor3 = this._updateColor3ForUniform;
  35692. this.updateColor4 = this._updateColor4ForUniform;
  35693. }
  35694. }
  35695. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35696. // Properties
  35697. /**
  35698. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35699. * or just falling back on setUniformXXX calls.
  35700. */
  35701. get: function () {
  35702. return !this._noUBO;
  35703. },
  35704. enumerable: true,
  35705. configurable: true
  35706. });
  35707. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35708. /**
  35709. * Indicates if the WebGL underlying uniform buffer is in sync
  35710. * with the javascript cache data.
  35711. */
  35712. get: function () {
  35713. return !this._needSync;
  35714. },
  35715. enumerable: true,
  35716. configurable: true
  35717. });
  35718. /**
  35719. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35720. * Also, a dynamic UniformBuffer will disable cache verification and always
  35721. * update the underlying WebGL uniform buffer to the GPU.
  35722. */
  35723. UniformBuffer.prototype.isDynamic = function () {
  35724. return this._dynamic !== undefined;
  35725. };
  35726. /**
  35727. * The data cache on JS side.
  35728. */
  35729. UniformBuffer.prototype.getData = function () {
  35730. return this._bufferData;
  35731. };
  35732. /**
  35733. * The underlying WebGL Uniform buffer.
  35734. */
  35735. UniformBuffer.prototype.getBuffer = function () {
  35736. return this._buffer;
  35737. };
  35738. /**
  35739. * std140 layout specifies how to align data within an UBO structure.
  35740. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35741. * for specs.
  35742. */
  35743. UniformBuffer.prototype._fillAlignment = function (size) {
  35744. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35745. // and 4x4 matrices
  35746. // TODO : change if other types are used
  35747. var alignment;
  35748. if (size <= 2) {
  35749. alignment = size;
  35750. }
  35751. else {
  35752. alignment = 4;
  35753. }
  35754. if ((this._uniformLocationPointer % alignment) !== 0) {
  35755. var oldPointer = this._uniformLocationPointer;
  35756. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35757. var diff = this._uniformLocationPointer - oldPointer;
  35758. for (var i = 0; i < diff; i++) {
  35759. this._data.push(0);
  35760. }
  35761. }
  35762. };
  35763. /**
  35764. * Adds an uniform in the buffer.
  35765. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35766. * for the layout to be correct !
  35767. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35768. * @param {number|number[]} size Data size, or data directly.
  35769. */
  35770. UniformBuffer.prototype.addUniform = function (name, size) {
  35771. if (this._noUBO) {
  35772. return;
  35773. }
  35774. if (this._uniformLocations[name] !== undefined) {
  35775. // Already existing uniform
  35776. return;
  35777. }
  35778. // This function must be called in the order of the shader layout !
  35779. // size can be the size of the uniform, or data directly
  35780. var data;
  35781. if (size instanceof Array) {
  35782. data = size;
  35783. size = data.length;
  35784. }
  35785. else {
  35786. size = size;
  35787. data = [];
  35788. // Fill with zeros
  35789. for (var i = 0; i < size; i++) {
  35790. data.push(0);
  35791. }
  35792. }
  35793. this._fillAlignment(size);
  35794. this._uniformSizes[name] = size;
  35795. this._uniformLocations[name] = this._uniformLocationPointer;
  35796. this._uniformLocationPointer += size;
  35797. for (var i = 0; i < size; i++) {
  35798. this._data.push(data[i]);
  35799. }
  35800. this._needSync = true;
  35801. };
  35802. /**
  35803. * Wrapper for addUniform.
  35804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35805. * @param {Matrix} mat A 4x4 matrix.
  35806. */
  35807. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35808. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35809. };
  35810. /**
  35811. * Wrapper for addUniform.
  35812. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35813. * @param {number} x
  35814. * @param {number} y
  35815. */
  35816. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35817. var temp = [x, y];
  35818. this.addUniform(name, temp);
  35819. };
  35820. /**
  35821. * Wrapper for addUniform.
  35822. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35823. * @param {number} x
  35824. * @param {number} y
  35825. * @param {number} z
  35826. */
  35827. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35828. var temp = [x, y, z];
  35829. this.addUniform(name, temp);
  35830. };
  35831. /**
  35832. * Wrapper for addUniform.
  35833. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35834. * @param {Color3} color
  35835. */
  35836. UniformBuffer.prototype.addColor3 = function (name, color) {
  35837. var temp = new Array();
  35838. color.toArray(temp);
  35839. this.addUniform(name, temp);
  35840. };
  35841. /**
  35842. * Wrapper for addUniform.
  35843. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35844. * @param {Color3} color
  35845. * @param {number} alpha
  35846. */
  35847. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35848. var temp = new Array();
  35849. color.toArray(temp);
  35850. temp.push(alpha);
  35851. this.addUniform(name, temp);
  35852. };
  35853. /**
  35854. * Wrapper for addUniform.
  35855. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35856. * @param {Vector3} vector
  35857. */
  35858. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35859. var temp = new Array();
  35860. vector.toArray(temp);
  35861. this.addUniform(name, temp);
  35862. };
  35863. /**
  35864. * Wrapper for addUniform.
  35865. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35866. */
  35867. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35868. this.addUniform(name, 12);
  35869. };
  35870. /**
  35871. * Wrapper for addUniform.
  35872. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35873. */
  35874. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35875. this.addUniform(name, 8);
  35876. };
  35877. /**
  35878. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35879. */
  35880. UniformBuffer.prototype.create = function () {
  35881. if (this._noUBO) {
  35882. return;
  35883. }
  35884. if (this._buffer) {
  35885. return; // nothing to do
  35886. }
  35887. // See spec, alignment must be filled as a vec4
  35888. this._fillAlignment(4);
  35889. this._bufferData = new Float32Array(this._data);
  35890. this._rebuild();
  35891. this._needSync = true;
  35892. };
  35893. UniformBuffer.prototype._rebuild = function () {
  35894. if (this._noUBO) {
  35895. return;
  35896. }
  35897. if (this._dynamic) {
  35898. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35899. }
  35900. else {
  35901. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35902. }
  35903. };
  35904. /**
  35905. * Updates the WebGL Uniform Buffer on the GPU.
  35906. * If the `dynamic` flag is set to true, no cache comparison is done.
  35907. * Otherwise, the buffer will be updated only if the cache differs.
  35908. */
  35909. UniformBuffer.prototype.update = function () {
  35910. if (!this._buffer) {
  35911. this.create();
  35912. return;
  35913. }
  35914. if (!this._dynamic && !this._needSync) {
  35915. return;
  35916. }
  35917. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35918. this._needSync = false;
  35919. };
  35920. /**
  35921. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35922. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35923. * @param {number[]|Float32Array} data Flattened data
  35924. * @param {number} size Size of the data.
  35925. */
  35926. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35927. var location = this._uniformLocations[uniformName];
  35928. if (location === undefined) {
  35929. if (this._buffer) {
  35930. // Cannot add an uniform if the buffer is already created
  35931. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35932. return;
  35933. }
  35934. this.addUniform(uniformName, size);
  35935. location = this._uniformLocations[uniformName];
  35936. }
  35937. if (!this._buffer) {
  35938. this.create();
  35939. }
  35940. if (!this._dynamic) {
  35941. // Cache for static uniform buffers
  35942. var changed = false;
  35943. for (var i = 0; i < size; i++) {
  35944. if (this._bufferData[location + i] !== data[i]) {
  35945. changed = true;
  35946. this._bufferData[location + i] = data[i];
  35947. }
  35948. }
  35949. this._needSync = this._needSync || changed;
  35950. }
  35951. else {
  35952. // No cache for dynamic
  35953. for (var i = 0; i < size; i++) {
  35954. this._bufferData[location + i] = data[i];
  35955. }
  35956. }
  35957. };
  35958. // Update methods
  35959. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35960. // To match std140, matrix must be realigned
  35961. for (var i = 0; i < 3; i++) {
  35962. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35963. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35964. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35965. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35966. }
  35967. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35968. };
  35969. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35970. this._currentEffect.setMatrix3x3(name, matrix);
  35971. };
  35972. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35973. this._currentEffect.setMatrix2x2(name, matrix);
  35974. };
  35975. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35976. // To match std140, matrix must be realigned
  35977. for (var i = 0; i < 2; i++) {
  35978. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35979. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35980. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35981. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35982. }
  35983. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35984. };
  35985. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35986. this._currentEffect.setFloat(name, x);
  35987. };
  35988. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35989. UniformBuffer._tempBuffer[0] = x;
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35991. };
  35992. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35993. if (suffix === void 0) { suffix = ""; }
  35994. this._currentEffect.setFloat2(name + suffix, x, y);
  35995. };
  35996. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35997. if (suffix === void 0) { suffix = ""; }
  35998. UniformBuffer._tempBuffer[0] = x;
  35999. UniformBuffer._tempBuffer[1] = y;
  36000. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36001. };
  36002. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36003. if (suffix === void 0) { suffix = ""; }
  36004. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36005. };
  36006. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36007. if (suffix === void 0) { suffix = ""; }
  36008. UniformBuffer._tempBuffer[0] = x;
  36009. UniformBuffer._tempBuffer[1] = y;
  36010. UniformBuffer._tempBuffer[2] = z;
  36011. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36012. };
  36013. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36014. if (suffix === void 0) { suffix = ""; }
  36015. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36016. };
  36017. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36018. if (suffix === void 0) { suffix = ""; }
  36019. UniformBuffer._tempBuffer[0] = x;
  36020. UniformBuffer._tempBuffer[1] = y;
  36021. UniformBuffer._tempBuffer[2] = z;
  36022. UniformBuffer._tempBuffer[3] = w;
  36023. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36024. };
  36025. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36026. this._currentEffect.setMatrix(name, mat);
  36027. };
  36028. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36029. this.updateUniform(name, mat.toArray(), 16);
  36030. };
  36031. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36032. this._currentEffect.setVector3(name, vector);
  36033. };
  36034. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36035. vector.toArray(UniformBuffer._tempBuffer);
  36036. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36037. };
  36038. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36039. this._currentEffect.setVector4(name, vector);
  36040. };
  36041. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36042. vector.toArray(UniformBuffer._tempBuffer);
  36043. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36044. };
  36045. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36046. if (suffix === void 0) { suffix = ""; }
  36047. this._currentEffect.setColor3(name + suffix, color);
  36048. };
  36049. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36050. if (suffix === void 0) { suffix = ""; }
  36051. color.toArray(UniformBuffer._tempBuffer);
  36052. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36053. };
  36054. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36055. if (suffix === void 0) { suffix = ""; }
  36056. this._currentEffect.setColor4(name + suffix, color, alpha);
  36057. };
  36058. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36059. if (suffix === void 0) { suffix = ""; }
  36060. color.toArray(UniformBuffer._tempBuffer);
  36061. UniformBuffer._tempBuffer[3] = alpha;
  36062. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36063. };
  36064. /**
  36065. * Sets a sampler uniform on the effect.
  36066. * @param {string} name Name of the sampler.
  36067. * @param {Texture} texture
  36068. */
  36069. UniformBuffer.prototype.setTexture = function (name, texture) {
  36070. this._currentEffect.setTexture(name, texture);
  36071. };
  36072. /**
  36073. * Directly updates the value of the uniform in the cache AND on the GPU.
  36074. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36075. * @param {number[]|Float32Array} data Flattened data
  36076. */
  36077. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36078. this.updateUniform(uniformName, data, data.length);
  36079. this.update();
  36080. };
  36081. /**
  36082. * Binds this uniform buffer to an effect.
  36083. * @param {Effect} effect
  36084. * @param {string} name Name of the uniform block in the shader.
  36085. */
  36086. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36087. this._currentEffect = effect;
  36088. if (this._noUBO || !this._buffer) {
  36089. return;
  36090. }
  36091. effect.bindUniformBuffer(this._buffer, name);
  36092. };
  36093. /**
  36094. * Disposes the uniform buffer.
  36095. */
  36096. UniformBuffer.prototype.dispose = function () {
  36097. if (this._noUBO) {
  36098. return;
  36099. }
  36100. var index = this._engine._uniformBuffers.indexOf(this);
  36101. if (index !== -1) {
  36102. this._engine._uniformBuffers.splice(index, 1);
  36103. }
  36104. if (!this._buffer) {
  36105. return;
  36106. }
  36107. if (this._engine._releaseBuffer(this._buffer)) {
  36108. this._buffer = null;
  36109. }
  36110. };
  36111. // Pool for avoiding memory leaks
  36112. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36113. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36114. return UniformBuffer;
  36115. }());
  36116. BABYLON.UniformBuffer = UniformBuffer;
  36117. })(BABYLON || (BABYLON = {}));
  36118. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36119. var BABYLON;
  36120. (function (BABYLON) {
  36121. /**
  36122. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36123. */
  36124. var VertexData = /** @class */ (function () {
  36125. function VertexData() {
  36126. }
  36127. /**
  36128. * Uses the passed data array to set the set the values for the specified kind of data
  36129. * @param data a linear array of floating numbers
  36130. * @param kind the type of data that is being set, eg positions, colors etc
  36131. */
  36132. VertexData.prototype.set = function (data, kind) {
  36133. switch (kind) {
  36134. case BABYLON.VertexBuffer.PositionKind:
  36135. this.positions = data;
  36136. break;
  36137. case BABYLON.VertexBuffer.NormalKind:
  36138. this.normals = data;
  36139. break;
  36140. case BABYLON.VertexBuffer.TangentKind:
  36141. this.tangents = data;
  36142. break;
  36143. case BABYLON.VertexBuffer.UVKind:
  36144. this.uvs = data;
  36145. break;
  36146. case BABYLON.VertexBuffer.UV2Kind:
  36147. this.uvs2 = data;
  36148. break;
  36149. case BABYLON.VertexBuffer.UV3Kind:
  36150. this.uvs3 = data;
  36151. break;
  36152. case BABYLON.VertexBuffer.UV4Kind:
  36153. this.uvs4 = data;
  36154. break;
  36155. case BABYLON.VertexBuffer.UV5Kind:
  36156. this.uvs5 = data;
  36157. break;
  36158. case BABYLON.VertexBuffer.UV6Kind:
  36159. this.uvs6 = data;
  36160. break;
  36161. case BABYLON.VertexBuffer.ColorKind:
  36162. this.colors = data;
  36163. break;
  36164. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36165. this.matricesIndices = data;
  36166. break;
  36167. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36168. this.matricesWeights = data;
  36169. break;
  36170. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36171. this.matricesIndicesExtra = data;
  36172. break;
  36173. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36174. this.matricesWeightsExtra = data;
  36175. break;
  36176. }
  36177. };
  36178. /**
  36179. * Associates the vertexData to the passed Mesh.
  36180. * Sets it as updatable or not (default `false`)
  36181. * @param mesh the mesh the vertexData is applied to
  36182. * @param updatable when used and having the value true allows new data to update the vertexData
  36183. * @returns the VertexData
  36184. */
  36185. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36186. this._applyTo(mesh, updatable);
  36187. return this;
  36188. };
  36189. /**
  36190. * Associates the vertexData to the passed Geometry.
  36191. * Sets it as updatable or not (default `false`)
  36192. * @param geometry the geometry the vertexData is applied to
  36193. * @param updatable when used and having the value true allows new data to update the vertexData
  36194. * @returns VertexData
  36195. */
  36196. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36197. this._applyTo(geometry, updatable);
  36198. return this;
  36199. };
  36200. /**
  36201. * Updates the associated mesh
  36202. * @param mesh the mesh to be updated
  36203. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36204. * @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
  36205. * @returns VertexData
  36206. */
  36207. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36208. this._update(mesh);
  36209. return this;
  36210. };
  36211. /**
  36212. * Updates the associated geometry
  36213. * @param geometry the geometry to be updated
  36214. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36215. * @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
  36216. * @returns VertexData.
  36217. */
  36218. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36219. this._update(geometry);
  36220. return this;
  36221. };
  36222. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36223. if (updatable === void 0) { updatable = false; }
  36224. if (this.positions) {
  36225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36226. }
  36227. if (this.normals) {
  36228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36229. }
  36230. if (this.tangents) {
  36231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36232. }
  36233. if (this.uvs) {
  36234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36235. }
  36236. if (this.uvs2) {
  36237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36238. }
  36239. if (this.uvs3) {
  36240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36241. }
  36242. if (this.uvs4) {
  36243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36244. }
  36245. if (this.uvs5) {
  36246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36247. }
  36248. if (this.uvs6) {
  36249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36250. }
  36251. if (this.colors) {
  36252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36253. }
  36254. if (this.matricesIndices) {
  36255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36256. }
  36257. if (this.matricesWeights) {
  36258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36259. }
  36260. if (this.matricesIndicesExtra) {
  36261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36262. }
  36263. if (this.matricesWeightsExtra) {
  36264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36265. }
  36266. if (this.indices) {
  36267. meshOrGeometry.setIndices(this.indices, null, updatable);
  36268. }
  36269. else {
  36270. meshOrGeometry.setIndices([], null);
  36271. }
  36272. return this;
  36273. };
  36274. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36275. if (this.positions) {
  36276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36277. }
  36278. if (this.normals) {
  36279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36280. }
  36281. if (this.tangents) {
  36282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36283. }
  36284. if (this.uvs) {
  36285. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36286. }
  36287. if (this.uvs2) {
  36288. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36289. }
  36290. if (this.uvs3) {
  36291. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36292. }
  36293. if (this.uvs4) {
  36294. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36295. }
  36296. if (this.uvs5) {
  36297. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36298. }
  36299. if (this.uvs6) {
  36300. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36301. }
  36302. if (this.colors) {
  36303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36304. }
  36305. if (this.matricesIndices) {
  36306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36307. }
  36308. if (this.matricesWeights) {
  36309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36310. }
  36311. if (this.matricesIndicesExtra) {
  36312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36313. }
  36314. if (this.matricesWeightsExtra) {
  36315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36316. }
  36317. if (this.indices) {
  36318. meshOrGeometry.setIndices(this.indices, null);
  36319. }
  36320. return this;
  36321. };
  36322. /**
  36323. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36324. * @param matrix the transforming matrix
  36325. * @returns the VertexData
  36326. */
  36327. VertexData.prototype.transform = function (matrix) {
  36328. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36329. var transformed = BABYLON.Vector3.Zero();
  36330. var index;
  36331. if (this.positions) {
  36332. var position = BABYLON.Vector3.Zero();
  36333. for (index = 0; index < this.positions.length; index += 3) {
  36334. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36335. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36336. this.positions[index] = transformed.x;
  36337. this.positions[index + 1] = transformed.y;
  36338. this.positions[index + 2] = transformed.z;
  36339. }
  36340. }
  36341. if (this.normals) {
  36342. var normal = BABYLON.Vector3.Zero();
  36343. for (index = 0; index < this.normals.length; index += 3) {
  36344. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36345. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36346. this.normals[index] = transformed.x;
  36347. this.normals[index + 1] = transformed.y;
  36348. this.normals[index + 2] = transformed.z;
  36349. }
  36350. }
  36351. if (this.tangents) {
  36352. var tangent = BABYLON.Vector4.Zero();
  36353. var tangentTransformed = BABYLON.Vector4.Zero();
  36354. for (index = 0; index < this.tangents.length; index += 4) {
  36355. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36356. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36357. this.tangents[index] = tangentTransformed.x;
  36358. this.tangents[index + 1] = tangentTransformed.y;
  36359. this.tangents[index + 2] = tangentTransformed.z;
  36360. this.tangents[index + 3] = tangentTransformed.w;
  36361. }
  36362. }
  36363. if (flip && this.indices) {
  36364. for (index = 0; index < this.indices.length; index += 3) {
  36365. var tmp = this.indices[index + 1];
  36366. this.indices[index + 1] = this.indices[index + 2];
  36367. this.indices[index + 2] = tmp;
  36368. }
  36369. }
  36370. return this;
  36371. };
  36372. /**
  36373. * Merges the passed VertexData into the current one
  36374. * @param other the VertexData to be merged into the current one
  36375. * @returns the modified VertexData
  36376. */
  36377. VertexData.prototype.merge = function (other) {
  36378. this._validate();
  36379. other._validate();
  36380. if (!this.normals !== !other.normals ||
  36381. !this.tangents !== !other.tangents ||
  36382. !this.uvs !== !other.uvs ||
  36383. !this.uvs2 !== !other.uvs2 ||
  36384. !this.uvs3 !== !other.uvs3 ||
  36385. !this.uvs4 !== !other.uvs4 ||
  36386. !this.uvs5 !== !other.uvs5 ||
  36387. !this.uvs6 !== !other.uvs6 ||
  36388. !this.colors !== !other.colors ||
  36389. !this.matricesIndices !== !other.matricesIndices ||
  36390. !this.matricesWeights !== !other.matricesWeights ||
  36391. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36392. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36393. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36394. }
  36395. if (other.indices) {
  36396. if (!this.indices) {
  36397. this.indices = [];
  36398. }
  36399. var offset = this.positions ? this.positions.length / 3 : 0;
  36400. for (var index = 0; index < other.indices.length; index++) {
  36401. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36402. this.indices.push(other.indices[index] + offset);
  36403. }
  36404. }
  36405. this.positions = this._mergeElement(this.positions, other.positions);
  36406. this.normals = this._mergeElement(this.normals, other.normals);
  36407. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36408. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36409. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36410. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36411. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36412. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36413. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36414. this.colors = this._mergeElement(this.colors, other.colors);
  36415. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36416. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36417. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36418. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36419. return this;
  36420. };
  36421. VertexData.prototype._mergeElement = function (source, other) {
  36422. if (!source) {
  36423. return other;
  36424. }
  36425. if (!other) {
  36426. return source;
  36427. }
  36428. var len = other.length + source.length;
  36429. var isSrcTypedArray = source instanceof Float32Array;
  36430. var isOthTypedArray = other instanceof Float32Array;
  36431. // use non-loop method when the source is Float32Array
  36432. if (isSrcTypedArray) {
  36433. var ret32 = new Float32Array(len);
  36434. ret32.set(source);
  36435. ret32.set(other, source.length);
  36436. return ret32;
  36437. // source is number[], when other is also use concat
  36438. }
  36439. else if (!isOthTypedArray) {
  36440. return source.concat(other);
  36441. // source is a number[], but other is a Float32Array, loop required
  36442. }
  36443. else {
  36444. var ret = source.slice(0); // copy source to a separate array
  36445. for (var i = 0, len = other.length; i < len; i++) {
  36446. ret.push(other[i]);
  36447. }
  36448. return ret;
  36449. }
  36450. };
  36451. VertexData.prototype._validate = function () {
  36452. if (!this.positions) {
  36453. throw new Error("Positions are required");
  36454. }
  36455. var getElementCount = function (kind, values) {
  36456. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36457. if ((values.length % stride) !== 0) {
  36458. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36459. }
  36460. return values.length / stride;
  36461. };
  36462. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36463. var validateElementCount = function (kind, values) {
  36464. var elementCount = getElementCount(kind, values);
  36465. if (elementCount !== positionsElementCount) {
  36466. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36467. }
  36468. };
  36469. if (this.normals)
  36470. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36471. if (this.tangents)
  36472. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36473. if (this.uvs)
  36474. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36475. if (this.uvs2)
  36476. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36477. if (this.uvs3)
  36478. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36479. if (this.uvs4)
  36480. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36481. if (this.uvs5)
  36482. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36483. if (this.uvs6)
  36484. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36485. if (this.colors)
  36486. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36487. if (this.matricesIndices)
  36488. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36489. if (this.matricesWeights)
  36490. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36491. if (this.matricesIndicesExtra)
  36492. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36493. if (this.matricesWeightsExtra)
  36494. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36495. };
  36496. /**
  36497. * Serializes the VertexData
  36498. * @returns a serialized object
  36499. */
  36500. VertexData.prototype.serialize = function () {
  36501. var serializationObject = this.serialize();
  36502. if (this.positions) {
  36503. serializationObject.positions = this.positions;
  36504. }
  36505. if (this.normals) {
  36506. serializationObject.normals = this.normals;
  36507. }
  36508. if (this.tangents) {
  36509. serializationObject.tangents = this.tangents;
  36510. }
  36511. if (this.uvs) {
  36512. serializationObject.uvs = this.uvs;
  36513. }
  36514. if (this.uvs2) {
  36515. serializationObject.uvs2 = this.uvs2;
  36516. }
  36517. if (this.uvs3) {
  36518. serializationObject.uvs3 = this.uvs3;
  36519. }
  36520. if (this.uvs4) {
  36521. serializationObject.uvs4 = this.uvs4;
  36522. }
  36523. if (this.uvs5) {
  36524. serializationObject.uvs5 = this.uvs5;
  36525. }
  36526. if (this.uvs6) {
  36527. serializationObject.uvs6 = this.uvs6;
  36528. }
  36529. if (this.colors) {
  36530. serializationObject.colors = this.colors;
  36531. }
  36532. if (this.matricesIndices) {
  36533. serializationObject.matricesIndices = this.matricesIndices;
  36534. serializationObject.matricesIndices._isExpanded = true;
  36535. }
  36536. if (this.matricesWeights) {
  36537. serializationObject.matricesWeights = this.matricesWeights;
  36538. }
  36539. if (this.matricesIndicesExtra) {
  36540. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36541. serializationObject.matricesIndicesExtra._isExpanded = true;
  36542. }
  36543. if (this.matricesWeightsExtra) {
  36544. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36545. }
  36546. serializationObject.indices = this.indices;
  36547. return serializationObject;
  36548. };
  36549. // Statics
  36550. /**
  36551. * Extracts the vertexData from a mesh
  36552. * @param mesh the mesh from which to extract the VertexData
  36553. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36554. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36555. * @returns the object VertexData associated to the passed mesh
  36556. */
  36557. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36558. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36559. };
  36560. /**
  36561. * Extracts the vertexData from the geometry
  36562. * @param geometry the geometry from which to extract the VertexData
  36563. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36564. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36565. * @returns the object VertexData associated to the passed mesh
  36566. */
  36567. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36568. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36569. };
  36570. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36571. var result = new VertexData();
  36572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36573. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36574. }
  36575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36576. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36577. }
  36578. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36579. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36580. }
  36581. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36582. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36583. }
  36584. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36585. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36586. }
  36587. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36588. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36589. }
  36590. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36591. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36592. }
  36593. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36594. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36595. }
  36596. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36597. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36598. }
  36599. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36600. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36601. }
  36602. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36603. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36604. }
  36605. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36606. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36607. }
  36608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36609. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36610. }
  36611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36612. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36613. }
  36614. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36615. return result;
  36616. };
  36617. /**
  36618. * Creates the VertexData for a Ribbon
  36619. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36620. * * pathArray array of paths, each of which an array of successive Vector3
  36621. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36622. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36623. * * 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
  36624. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36625. * * 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)
  36626. * * 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)
  36627. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36628. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36629. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36630. * @returns the VertexData of the ribbon
  36631. */
  36632. VertexData.CreateRibbon = function (options) {
  36633. var pathArray = options.pathArray;
  36634. var closeArray = options.closeArray || false;
  36635. var closePath = options.closePath || false;
  36636. var invertUV = options.invertUV || false;
  36637. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36638. var offset = options.offset || defaultOffset;
  36639. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36641. var customUV = options.uvs;
  36642. var customColors = options.colors;
  36643. var positions = [];
  36644. var indices = [];
  36645. var normals = [];
  36646. var uvs = [];
  36647. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36648. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36649. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36650. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36651. var minlg; // minimal length among all paths from pathArray
  36652. var lg = []; // array of path lengths : nb of vertex per path
  36653. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36654. var p; // path iterator
  36655. var i; // point iterator
  36656. var j; // point iterator
  36657. // if single path in pathArray
  36658. if (pathArray.length < 2) {
  36659. var ar1 = [];
  36660. var ar2 = [];
  36661. for (i = 0; i < pathArray[0].length - offset; i++) {
  36662. ar1.push(pathArray[0][i]);
  36663. ar2.push(pathArray[0][i + offset]);
  36664. }
  36665. pathArray = [ar1, ar2];
  36666. }
  36667. // positions and horizontal distances (u)
  36668. var idc = 0;
  36669. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36670. var path;
  36671. var l;
  36672. minlg = pathArray[0].length;
  36673. var vectlg;
  36674. var dist;
  36675. for (p = 0; p < pathArray.length; p++) {
  36676. uTotalDistance[p] = 0;
  36677. us[p] = [0];
  36678. path = pathArray[p];
  36679. l = path.length;
  36680. minlg = (minlg < l) ? minlg : l;
  36681. j = 0;
  36682. while (j < l) {
  36683. positions.push(path[j].x, path[j].y, path[j].z);
  36684. if (j > 0) {
  36685. vectlg = path[j].subtract(path[j - 1]).length();
  36686. dist = vectlg + uTotalDistance[p];
  36687. us[p].push(dist);
  36688. uTotalDistance[p] = dist;
  36689. }
  36690. j++;
  36691. }
  36692. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36693. j--;
  36694. positions.push(path[0].x, path[0].y, path[0].z);
  36695. vectlg = path[j].subtract(path[0]).length();
  36696. dist = vectlg + uTotalDistance[p];
  36697. us[p].push(dist);
  36698. uTotalDistance[p] = dist;
  36699. }
  36700. lg[p] = l + closePathCorr;
  36701. idx[p] = idc;
  36702. idc += (l + closePathCorr);
  36703. }
  36704. // vertical distances (v)
  36705. var path1;
  36706. var path2;
  36707. var vertex1 = null;
  36708. var vertex2 = null;
  36709. for (i = 0; i < minlg + closePathCorr; i++) {
  36710. vTotalDistance[i] = 0;
  36711. vs[i] = [0];
  36712. for (p = 0; p < pathArray.length - 1; p++) {
  36713. path1 = pathArray[p];
  36714. path2 = pathArray[p + 1];
  36715. if (i === minlg) { // closePath
  36716. vertex1 = path1[0];
  36717. vertex2 = path2[0];
  36718. }
  36719. else {
  36720. vertex1 = path1[i];
  36721. vertex2 = path2[i];
  36722. }
  36723. vectlg = vertex2.subtract(vertex1).length();
  36724. dist = vectlg + vTotalDistance[i];
  36725. vs[i].push(dist);
  36726. vTotalDistance[i] = dist;
  36727. }
  36728. if (closeArray && vertex2 && vertex1) {
  36729. path1 = pathArray[p];
  36730. path2 = pathArray[0];
  36731. if (i === minlg) { // closePath
  36732. vertex2 = path2[0];
  36733. }
  36734. vectlg = vertex2.subtract(vertex1).length();
  36735. dist = vectlg + vTotalDistance[i];
  36736. vTotalDistance[i] = dist;
  36737. }
  36738. }
  36739. // uvs
  36740. var u;
  36741. var v;
  36742. if (customUV) {
  36743. for (p = 0; p < customUV.length; p++) {
  36744. uvs.push(customUV[p].x, customUV[p].y);
  36745. }
  36746. }
  36747. else {
  36748. for (p = 0; p < pathArray.length; p++) {
  36749. for (i = 0; i < minlg + closePathCorr; i++) {
  36750. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36751. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36752. if (invertUV) {
  36753. uvs.push(v, u);
  36754. }
  36755. else {
  36756. uvs.push(u, v);
  36757. }
  36758. }
  36759. }
  36760. }
  36761. // indices
  36762. p = 0; // path index
  36763. var pi = 0; // positions array index
  36764. var l1 = lg[p] - 1; // path1 length
  36765. var l2 = lg[p + 1] - 1; // path2 length
  36766. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36767. var shft = idx[1] - idx[0]; // shift
  36768. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36769. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36770. // 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
  36771. indices.push(pi, pi + shft, pi + 1);
  36772. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36773. pi += 1;
  36774. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36775. p++;
  36776. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36777. shft = idx[0] - idx[p];
  36778. l1 = lg[p] - 1;
  36779. l2 = lg[0] - 1;
  36780. }
  36781. else {
  36782. shft = idx[p + 1] - idx[p];
  36783. l1 = lg[p] - 1;
  36784. l2 = lg[p + 1] - 1;
  36785. }
  36786. pi = idx[p];
  36787. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36788. }
  36789. }
  36790. // normals
  36791. VertexData.ComputeNormals(positions, indices, normals);
  36792. if (closePath) { // update both the first and last vertex normals to their average value
  36793. var indexFirst = 0;
  36794. var indexLast = 0;
  36795. for (p = 0; p < pathArray.length; p++) {
  36796. indexFirst = idx[p] * 3;
  36797. if (p + 1 < pathArray.length) {
  36798. indexLast = (idx[p + 1] - 1) * 3;
  36799. }
  36800. else {
  36801. indexLast = normals.length - 3;
  36802. }
  36803. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36804. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36805. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36806. normals[indexLast] = normals[indexFirst];
  36807. normals[indexLast + 1] = normals[indexFirst + 1];
  36808. normals[indexLast + 2] = normals[indexFirst + 2];
  36809. }
  36810. }
  36811. // sides
  36812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36813. // Colors
  36814. var colors = null;
  36815. if (customColors) {
  36816. colors = new Float32Array(customColors.length * 4);
  36817. for (var c = 0; c < customColors.length; c++) {
  36818. colors[c * 4] = customColors[c].r;
  36819. colors[c * 4 + 1] = customColors[c].g;
  36820. colors[c * 4 + 2] = customColors[c].b;
  36821. colors[c * 4 + 3] = customColors[c].a;
  36822. }
  36823. }
  36824. // Result
  36825. var vertexData = new VertexData();
  36826. var positions32 = new Float32Array(positions);
  36827. var normals32 = new Float32Array(normals);
  36828. var uvs32 = new Float32Array(uvs);
  36829. vertexData.indices = indices;
  36830. vertexData.positions = positions32;
  36831. vertexData.normals = normals32;
  36832. vertexData.uvs = uvs32;
  36833. if (colors) {
  36834. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36835. }
  36836. if (closePath) {
  36837. vertexData._idx = idx;
  36838. }
  36839. return vertexData;
  36840. };
  36841. /**
  36842. * Creates the VertexData for a box
  36843. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36844. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36845. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36846. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36847. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36848. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36849. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36850. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36851. * * 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)
  36852. * * 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)
  36853. * @returns the VertexData of the box
  36854. */
  36855. VertexData.CreateBox = function (options) {
  36856. var normalsSource = [
  36857. new BABYLON.Vector3(0, 0, 1),
  36858. new BABYLON.Vector3(0, 0, -1),
  36859. new BABYLON.Vector3(1, 0, 0),
  36860. new BABYLON.Vector3(-1, 0, 0),
  36861. new BABYLON.Vector3(0, 1, 0),
  36862. new BABYLON.Vector3(0, -1, 0)
  36863. ];
  36864. var indices = [];
  36865. var positions = [];
  36866. var normals = [];
  36867. var uvs = [];
  36868. var width = options.width || options.size || 1;
  36869. var height = options.height || options.size || 1;
  36870. var depth = options.depth || options.size || 1;
  36871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36872. var faceUV = options.faceUV || new Array(6);
  36873. var faceColors = options.faceColors;
  36874. var colors = [];
  36875. // default face colors and UV if undefined
  36876. for (var f = 0; f < 6; f++) {
  36877. if (faceUV[f] === undefined) {
  36878. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36879. }
  36880. if (faceColors && faceColors[f] === undefined) {
  36881. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36882. }
  36883. }
  36884. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36885. // Create each face in turn.
  36886. for (var index = 0; index < normalsSource.length; index++) {
  36887. var normal = normalsSource[index];
  36888. // Get two vectors perpendicular to the face normal and to each other.
  36889. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36890. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36891. // Six indices (two triangles) per face.
  36892. var verticesLength = positions.length / 3;
  36893. indices.push(verticesLength);
  36894. indices.push(verticesLength + 1);
  36895. indices.push(verticesLength + 2);
  36896. indices.push(verticesLength);
  36897. indices.push(verticesLength + 2);
  36898. indices.push(verticesLength + 3);
  36899. // Four vertices per face.
  36900. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36901. positions.push(vertex.x, vertex.y, vertex.z);
  36902. normals.push(normal.x, normal.y, normal.z);
  36903. uvs.push(faceUV[index].z, faceUV[index].w);
  36904. if (faceColors) {
  36905. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36906. }
  36907. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36908. positions.push(vertex.x, vertex.y, vertex.z);
  36909. normals.push(normal.x, normal.y, normal.z);
  36910. uvs.push(faceUV[index].x, faceUV[index].w);
  36911. if (faceColors) {
  36912. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36913. }
  36914. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36915. positions.push(vertex.x, vertex.y, vertex.z);
  36916. normals.push(normal.x, normal.y, normal.z);
  36917. uvs.push(faceUV[index].x, faceUV[index].y);
  36918. if (faceColors) {
  36919. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36920. }
  36921. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36922. positions.push(vertex.x, vertex.y, vertex.z);
  36923. normals.push(normal.x, normal.y, normal.z);
  36924. uvs.push(faceUV[index].z, faceUV[index].y);
  36925. if (faceColors) {
  36926. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36927. }
  36928. }
  36929. // sides
  36930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36931. // Result
  36932. var vertexData = new VertexData();
  36933. vertexData.indices = indices;
  36934. vertexData.positions = positions;
  36935. vertexData.normals = normals;
  36936. vertexData.uvs = uvs;
  36937. if (faceColors) {
  36938. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36939. vertexData.colors = totalColors;
  36940. }
  36941. return vertexData;
  36942. };
  36943. /**
  36944. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36945. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36946. * * segments sets the number of horizontal strips optional, default 32
  36947. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36948. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36949. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36950. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36951. * * 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
  36952. * * 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
  36953. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36954. * * 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)
  36955. * * 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)
  36956. * @returns the VertexData of the ellipsoid
  36957. */
  36958. VertexData.CreateSphere = function (options) {
  36959. var segments = options.segments || 32;
  36960. var diameterX = options.diameterX || options.diameter || 1;
  36961. var diameterY = options.diameterY || options.diameter || 1;
  36962. var diameterZ = options.diameterZ || options.diameter || 1;
  36963. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36964. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36965. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36966. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36967. var totalZRotationSteps = 2 + segments;
  36968. var totalYRotationSteps = 2 * totalZRotationSteps;
  36969. var indices = [];
  36970. var positions = [];
  36971. var normals = [];
  36972. var uvs = [];
  36973. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36974. var normalizedZ = zRotationStep / totalZRotationSteps;
  36975. var angleZ = normalizedZ * Math.PI * slice;
  36976. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36977. var normalizedY = yRotationStep / totalYRotationSteps;
  36978. var angleY = normalizedY * Math.PI * 2 * arc;
  36979. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36980. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36981. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36982. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36983. var vertex = complete.multiply(radius);
  36984. var normal = complete.divide(radius).normalize();
  36985. positions.push(vertex.x, vertex.y, vertex.z);
  36986. normals.push(normal.x, normal.y, normal.z);
  36987. uvs.push(normalizedY, normalizedZ);
  36988. }
  36989. if (zRotationStep > 0) {
  36990. var verticesCount = positions.length / 3;
  36991. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36992. indices.push((firstIndex));
  36993. indices.push((firstIndex + 1));
  36994. indices.push(firstIndex + totalYRotationSteps + 1);
  36995. indices.push((firstIndex + totalYRotationSteps + 1));
  36996. indices.push((firstIndex + 1));
  36997. indices.push((firstIndex + totalYRotationSteps + 2));
  36998. }
  36999. }
  37000. }
  37001. // Sides
  37002. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37003. // Result
  37004. var vertexData = new VertexData();
  37005. vertexData.indices = indices;
  37006. vertexData.positions = positions;
  37007. vertexData.normals = normals;
  37008. vertexData.uvs = uvs;
  37009. return vertexData;
  37010. };
  37011. /**
  37012. * Creates the VertexData for a cylinder, cone or prism
  37013. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37014. * * height sets the height (y direction) of the cylinder, optional, default 2
  37015. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37016. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37017. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37018. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37019. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37020. * * 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
  37021. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37022. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37023. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37024. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37025. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37026. * * 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)
  37027. * * 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)
  37028. * @returns the VertexData of the cylinder, cone or prism
  37029. */
  37030. VertexData.CreateCylinder = function (options) {
  37031. var height = options.height || 2;
  37032. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37033. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37034. var tessellation = options.tessellation || 24;
  37035. var subdivisions = options.subdivisions || 1;
  37036. var hasRings = options.hasRings ? true : false;
  37037. var enclose = options.enclose ? true : false;
  37038. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37039. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37040. var faceUV = options.faceUV || new Array(3);
  37041. var faceColors = options.faceColors;
  37042. // default face colors and UV if undefined
  37043. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37044. var ringNb = (hasRings) ? subdivisions : 1;
  37045. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37046. var f;
  37047. for (f = 0; f < surfaceNb; f++) {
  37048. if (faceColors && faceColors[f] === undefined) {
  37049. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37050. }
  37051. }
  37052. for (f = 0; f < surfaceNb; f++) {
  37053. if (faceUV && faceUV[f] === undefined) {
  37054. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37055. }
  37056. }
  37057. var indices = new Array();
  37058. var positions = new Array();
  37059. var normals = new Array();
  37060. var uvs = new Array();
  37061. var colors = new Array();
  37062. var angle_step = Math.PI * 2 * arc / tessellation;
  37063. var angle;
  37064. var h;
  37065. var radius;
  37066. var tan = (diameterBottom - diameterTop) / 2 / height;
  37067. var ringVertex = BABYLON.Vector3.Zero();
  37068. var ringNormal = BABYLON.Vector3.Zero();
  37069. var ringFirstVertex = BABYLON.Vector3.Zero();
  37070. var ringFirstNormal = BABYLON.Vector3.Zero();
  37071. var quadNormal = BABYLON.Vector3.Zero();
  37072. var Y = BABYLON.Axis.Y;
  37073. // positions, normals, uvs
  37074. var i;
  37075. var j;
  37076. var r;
  37077. var ringIdx = 1;
  37078. var s = 1; // surface index
  37079. var cs = 0;
  37080. var v = 0;
  37081. for (i = 0; i <= subdivisions; i++) {
  37082. h = i / subdivisions;
  37083. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37084. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37085. for (r = 0; r < ringIdx; r++) {
  37086. if (hasRings) {
  37087. s += r;
  37088. }
  37089. if (enclose) {
  37090. s += 2 * r;
  37091. }
  37092. for (j = 0; j <= tessellation; j++) {
  37093. angle = j * angle_step;
  37094. // position
  37095. ringVertex.x = Math.cos(-angle) * radius;
  37096. ringVertex.y = -height / 2 + h * height;
  37097. ringVertex.z = Math.sin(-angle) * radius;
  37098. // normal
  37099. if (diameterTop === 0 && i === subdivisions) {
  37100. // if no top cap, reuse former normals
  37101. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37102. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37103. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37104. }
  37105. else {
  37106. ringNormal.x = ringVertex.x;
  37107. ringNormal.z = ringVertex.z;
  37108. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37109. ringNormal.normalize();
  37110. }
  37111. // keep first ring vertex values for enclose
  37112. if (j === 0) {
  37113. ringFirstVertex.copyFrom(ringVertex);
  37114. ringFirstNormal.copyFrom(ringNormal);
  37115. }
  37116. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37117. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37118. if (hasRings) {
  37119. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37120. }
  37121. else {
  37122. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37123. }
  37124. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37125. if (faceColors) {
  37126. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37127. }
  37128. }
  37129. // if enclose, add four vertices and their dedicated normals
  37130. if (arc !== 1 && enclose) {
  37131. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37132. positions.push(0, ringVertex.y, 0);
  37133. positions.push(0, ringVertex.y, 0);
  37134. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37135. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37136. quadNormal.normalize();
  37137. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37138. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37139. quadNormal.normalize();
  37140. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37141. if (hasRings) {
  37142. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37143. }
  37144. else {
  37145. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37146. }
  37147. uvs.push(faceUV[s + 1].x, v);
  37148. uvs.push(faceUV[s + 1].z, v);
  37149. if (hasRings) {
  37150. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37151. }
  37152. else {
  37153. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37154. }
  37155. uvs.push(faceUV[s + 2].x, v);
  37156. uvs.push(faceUV[s + 2].z, v);
  37157. if (faceColors) {
  37158. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37159. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37160. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37161. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37162. }
  37163. }
  37164. if (cs !== s) {
  37165. cs = s;
  37166. }
  37167. }
  37168. }
  37169. // indices
  37170. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37171. var s;
  37172. i = 0;
  37173. for (s = 0; s < subdivisions; s++) {
  37174. var i0 = 0;
  37175. var i1 = 0;
  37176. var i2 = 0;
  37177. var i3 = 0;
  37178. for (j = 0; j < tessellation; j++) {
  37179. i0 = i * (e + 1) + j;
  37180. i1 = (i + 1) * (e + 1) + j;
  37181. i2 = i * (e + 1) + (j + 1);
  37182. i3 = (i + 1) * (e + 1) + (j + 1);
  37183. indices.push(i0, i1, i2);
  37184. indices.push(i3, i2, i1);
  37185. }
  37186. if (arc !== 1 && enclose) { // if enclose, add two quads
  37187. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37188. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37189. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37190. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37191. }
  37192. i = (hasRings) ? (i + 2) : (i + 1);
  37193. }
  37194. // Caps
  37195. var createCylinderCap = function (isTop) {
  37196. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37197. if (radius === 0) {
  37198. return;
  37199. }
  37200. // Cap positions, normals & uvs
  37201. var angle;
  37202. var circleVector;
  37203. var i;
  37204. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37205. var c = null;
  37206. if (faceColors) {
  37207. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37208. }
  37209. // cap center
  37210. var vbase = positions.length / 3;
  37211. var offset = isTop ? height / 2 : -height / 2;
  37212. var center = new BABYLON.Vector3(0, offset, 0);
  37213. positions.push(center.x, center.y, center.z);
  37214. normals.push(0, isTop ? 1 : -1, 0);
  37215. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37216. if (c) {
  37217. colors.push(c.r, c.g, c.b, c.a);
  37218. }
  37219. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37220. for (i = 0; i <= tessellation; i++) {
  37221. angle = Math.PI * 2 * i * arc / tessellation;
  37222. var cos = Math.cos(-angle);
  37223. var sin = Math.sin(-angle);
  37224. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37225. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37226. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37227. normals.push(0, isTop ? 1 : -1, 0);
  37228. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37229. if (c) {
  37230. colors.push(c.r, c.g, c.b, c.a);
  37231. }
  37232. }
  37233. // Cap indices
  37234. for (i = 0; i < tessellation; i++) {
  37235. if (!isTop) {
  37236. indices.push(vbase);
  37237. indices.push(vbase + (i + 1));
  37238. indices.push(vbase + (i + 2));
  37239. }
  37240. else {
  37241. indices.push(vbase);
  37242. indices.push(vbase + (i + 2));
  37243. indices.push(vbase + (i + 1));
  37244. }
  37245. }
  37246. };
  37247. // add caps to geometry
  37248. createCylinderCap(false);
  37249. createCylinderCap(true);
  37250. // Sides
  37251. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37252. var vertexData = new VertexData();
  37253. vertexData.indices = indices;
  37254. vertexData.positions = positions;
  37255. vertexData.normals = normals;
  37256. vertexData.uvs = uvs;
  37257. if (faceColors) {
  37258. vertexData.colors = colors;
  37259. }
  37260. return vertexData;
  37261. };
  37262. /**
  37263. * Creates the VertexData for a torus
  37264. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37265. * * diameter the diameter of the torus, optional default 1
  37266. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37267. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37268. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37269. * * 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)
  37270. * * 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)
  37271. * @returns the VertexData of the torus
  37272. */
  37273. VertexData.CreateTorus = function (options) {
  37274. var indices = [];
  37275. var positions = [];
  37276. var normals = [];
  37277. var uvs = [];
  37278. var diameter = options.diameter || 1;
  37279. var thickness = options.thickness || 0.5;
  37280. var tessellation = options.tessellation || 16;
  37281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37282. var stride = tessellation + 1;
  37283. for (var i = 0; i <= tessellation; i++) {
  37284. var u = i / tessellation;
  37285. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37286. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37287. for (var j = 0; j <= tessellation; j++) {
  37288. var v = 1 - j / tessellation;
  37289. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37290. var dx = Math.cos(innerAngle);
  37291. var dy = Math.sin(innerAngle);
  37292. // Create a vertex.
  37293. var normal = new BABYLON.Vector3(dx, dy, 0);
  37294. var position = normal.scale(thickness / 2);
  37295. var textureCoordinate = new BABYLON.Vector2(u, v);
  37296. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37297. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37298. positions.push(position.x, position.y, position.z);
  37299. normals.push(normal.x, normal.y, normal.z);
  37300. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37301. // And create indices for two triangles.
  37302. var nextI = (i + 1) % stride;
  37303. var nextJ = (j + 1) % stride;
  37304. indices.push(i * stride + j);
  37305. indices.push(i * stride + nextJ);
  37306. indices.push(nextI * stride + j);
  37307. indices.push(i * stride + nextJ);
  37308. indices.push(nextI * stride + nextJ);
  37309. indices.push(nextI * stride + j);
  37310. }
  37311. }
  37312. // Sides
  37313. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37314. // Result
  37315. var vertexData = new VertexData();
  37316. vertexData.indices = indices;
  37317. vertexData.positions = positions;
  37318. vertexData.normals = normals;
  37319. vertexData.uvs = uvs;
  37320. return vertexData;
  37321. };
  37322. /**
  37323. * Creates the VertexData of the LineSystem
  37324. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37325. * - lines an array of lines, each line being an array of successive Vector3
  37326. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37327. * @returns the VertexData of the LineSystem
  37328. */
  37329. VertexData.CreateLineSystem = function (options) {
  37330. var indices = [];
  37331. var positions = [];
  37332. var lines = options.lines;
  37333. var colors = options.colors;
  37334. var vertexColors = [];
  37335. var idx = 0;
  37336. for (var l = 0; l < lines.length; l++) {
  37337. var points = lines[l];
  37338. for (var index = 0; index < points.length; index++) {
  37339. positions.push(points[index].x, points[index].y, points[index].z);
  37340. if (colors) {
  37341. var color = colors[l];
  37342. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37343. }
  37344. if (index > 0) {
  37345. indices.push(idx - 1);
  37346. indices.push(idx);
  37347. }
  37348. idx++;
  37349. }
  37350. }
  37351. var vertexData = new VertexData();
  37352. vertexData.indices = indices;
  37353. vertexData.positions = positions;
  37354. if (colors) {
  37355. vertexData.colors = vertexColors;
  37356. }
  37357. return vertexData;
  37358. };
  37359. /**
  37360. * Create the VertexData for a DashedLines
  37361. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37362. * - points an array successive Vector3
  37363. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37364. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37365. * - dashNb the intended total number of dashes, optional, default 200
  37366. * @returns the VertexData for the DashedLines
  37367. */
  37368. VertexData.CreateDashedLines = function (options) {
  37369. var dashSize = options.dashSize || 3;
  37370. var gapSize = options.gapSize || 1;
  37371. var dashNb = options.dashNb || 200;
  37372. var points = options.points;
  37373. var positions = new Array();
  37374. var indices = new Array();
  37375. var curvect = BABYLON.Vector3.Zero();
  37376. var lg = 0;
  37377. var nb = 0;
  37378. var shft = 0;
  37379. var dashshft = 0;
  37380. var curshft = 0;
  37381. var idx = 0;
  37382. var i = 0;
  37383. for (i = 0; i < points.length - 1; i++) {
  37384. points[i + 1].subtractToRef(points[i], curvect);
  37385. lg += curvect.length();
  37386. }
  37387. shft = lg / dashNb;
  37388. dashshft = dashSize * shft / (dashSize + gapSize);
  37389. for (i = 0; i < points.length - 1; i++) {
  37390. points[i + 1].subtractToRef(points[i], curvect);
  37391. nb = Math.floor(curvect.length() / shft);
  37392. curvect.normalize();
  37393. for (var j = 0; j < nb; j++) {
  37394. curshft = shft * j;
  37395. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37396. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37397. indices.push(idx, idx + 1);
  37398. idx += 2;
  37399. }
  37400. }
  37401. // Result
  37402. var vertexData = new VertexData();
  37403. vertexData.positions = positions;
  37404. vertexData.indices = indices;
  37405. return vertexData;
  37406. };
  37407. /**
  37408. * Creates the VertexData for a Ground
  37409. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37410. * - width the width (x direction) of the ground, optional, default 1
  37411. * - height the height (z direction) of the ground, optional, default 1
  37412. * - subdivisions the number of subdivisions per side, optional, default 1
  37413. * @returns the VertexData of the Ground
  37414. */
  37415. VertexData.CreateGround = function (options) {
  37416. var indices = [];
  37417. var positions = [];
  37418. var normals = [];
  37419. var uvs = [];
  37420. var row, col;
  37421. var width = options.width || 1;
  37422. var height = options.height || 1;
  37423. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37424. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37425. for (row = 0; row <= subdivisionsY; row++) {
  37426. for (col = 0; col <= subdivisionsX; col++) {
  37427. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37428. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37429. positions.push(position.x, position.y, position.z);
  37430. normals.push(normal.x, normal.y, normal.z);
  37431. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37432. }
  37433. }
  37434. for (row = 0; row < subdivisionsY; row++) {
  37435. for (col = 0; col < subdivisionsX; col++) {
  37436. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37437. indices.push(col + 1 + row * (subdivisionsX + 1));
  37438. indices.push(col + row * (subdivisionsX + 1));
  37439. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37440. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37441. indices.push(col + row * (subdivisionsX + 1));
  37442. }
  37443. }
  37444. // Result
  37445. var vertexData = new VertexData();
  37446. vertexData.indices = indices;
  37447. vertexData.positions = positions;
  37448. vertexData.normals = normals;
  37449. vertexData.uvs = uvs;
  37450. return vertexData;
  37451. };
  37452. /**
  37453. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37454. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37455. * * xmin the ground minimum X coordinate, optional, default -1
  37456. * * zmin the ground minimum Z coordinate, optional, default -1
  37457. * * xmax the ground maximum X coordinate, optional, default 1
  37458. * * zmax the ground maximum Z coordinate, optional, default 1
  37459. * * 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}
  37460. * * 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}
  37461. * @returns the VertexData of the TiledGround
  37462. */
  37463. VertexData.CreateTiledGround = function (options) {
  37464. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37465. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37466. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37467. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37468. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37469. var precision = options.precision || { w: 1, h: 1 };
  37470. var indices = new Array();
  37471. var positions = new Array();
  37472. var normals = new Array();
  37473. var uvs = new Array();
  37474. var row, col, tileRow, tileCol;
  37475. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37476. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37477. precision.w = (precision.w < 1) ? 1 : precision.w;
  37478. precision.h = (precision.h < 1) ? 1 : precision.h;
  37479. var tileSize = {
  37480. 'w': (xmax - xmin) / subdivisions.w,
  37481. 'h': (zmax - zmin) / subdivisions.h
  37482. };
  37483. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37484. // Indices
  37485. var base = positions.length / 3;
  37486. var rowLength = precision.w + 1;
  37487. for (row = 0; row < precision.h; row++) {
  37488. for (col = 0; col < precision.w; col++) {
  37489. var square = [
  37490. base + col + row * rowLength,
  37491. base + (col + 1) + row * rowLength,
  37492. base + (col + 1) + (row + 1) * rowLength,
  37493. base + col + (row + 1) * rowLength
  37494. ];
  37495. indices.push(square[1]);
  37496. indices.push(square[2]);
  37497. indices.push(square[3]);
  37498. indices.push(square[0]);
  37499. indices.push(square[1]);
  37500. indices.push(square[3]);
  37501. }
  37502. }
  37503. // Position, normals and uvs
  37504. var position = BABYLON.Vector3.Zero();
  37505. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37506. for (row = 0; row <= precision.h; row++) {
  37507. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37508. for (col = 0; col <= precision.w; col++) {
  37509. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37510. position.y = 0;
  37511. positions.push(position.x, position.y, position.z);
  37512. normals.push(normal.x, normal.y, normal.z);
  37513. uvs.push(col / precision.w, row / precision.h);
  37514. }
  37515. }
  37516. }
  37517. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37518. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37519. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37520. }
  37521. }
  37522. // Result
  37523. var vertexData = new VertexData();
  37524. vertexData.indices = indices;
  37525. vertexData.positions = positions;
  37526. vertexData.normals = normals;
  37527. vertexData.uvs = uvs;
  37528. return vertexData;
  37529. };
  37530. /**
  37531. * Creates the VertexData of the Ground designed from a heightmap
  37532. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37533. * * width the width (x direction) of the ground
  37534. * * height the height (z direction) of the ground
  37535. * * subdivisions the number of subdivisions per side
  37536. * * minHeight the minimum altitude on the ground, optional, default 0
  37537. * * maxHeight the maximum altitude on the ground, optional default 1
  37538. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37539. * * buffer the array holding the image color data
  37540. * * bufferWidth the width of image
  37541. * * bufferHeight the height of image
  37542. * @returns the VertexData of the Ground designed from a heightmap
  37543. */
  37544. VertexData.CreateGroundFromHeightMap = function (options) {
  37545. var indices = [];
  37546. var positions = [];
  37547. var normals = [];
  37548. var uvs = [];
  37549. var row, col;
  37550. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37551. // Vertices
  37552. for (row = 0; row <= options.subdivisions; row++) {
  37553. for (col = 0; col <= options.subdivisions; col++) {
  37554. 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));
  37555. // Compute height
  37556. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37557. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37558. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37559. var r = options.buffer[pos] / 255.0;
  37560. var g = options.buffer[pos + 1] / 255.0;
  37561. var b = options.buffer[pos + 2] / 255.0;
  37562. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37563. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37564. // Add vertex
  37565. positions.push(position.x, position.y, position.z);
  37566. normals.push(0, 0, 0);
  37567. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37568. }
  37569. }
  37570. // Indices
  37571. for (row = 0; row < options.subdivisions; row++) {
  37572. for (col = 0; col < options.subdivisions; col++) {
  37573. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37574. indices.push(col + 1 + row * (options.subdivisions + 1));
  37575. indices.push(col + row * (options.subdivisions + 1));
  37576. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37577. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37578. indices.push(col + row * (options.subdivisions + 1));
  37579. }
  37580. }
  37581. // Normals
  37582. VertexData.ComputeNormals(positions, indices, normals);
  37583. // Result
  37584. var vertexData = new VertexData();
  37585. vertexData.indices = indices;
  37586. vertexData.positions = positions;
  37587. vertexData.normals = normals;
  37588. vertexData.uvs = uvs;
  37589. return vertexData;
  37590. };
  37591. /**
  37592. * Creates the VertexData for a Plane
  37593. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37594. * * size sets the width and height of the plane to the value of size, optional default 1
  37595. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37596. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37597. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37598. * * 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)
  37599. * * 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)
  37600. * @returns the VertexData of the box
  37601. */
  37602. VertexData.CreatePlane = function (options) {
  37603. var indices = [];
  37604. var positions = [];
  37605. var normals = [];
  37606. var uvs = [];
  37607. var width = options.width || options.size || 1;
  37608. var height = options.height || options.size || 1;
  37609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37610. // Vertices
  37611. var halfWidth = width / 2.0;
  37612. var halfHeight = height / 2.0;
  37613. positions.push(-halfWidth, -halfHeight, 0);
  37614. normals.push(0, 0, -1.0);
  37615. uvs.push(0.0, 0.0);
  37616. positions.push(halfWidth, -halfHeight, 0);
  37617. normals.push(0, 0, -1.0);
  37618. uvs.push(1.0, 0.0);
  37619. positions.push(halfWidth, halfHeight, 0);
  37620. normals.push(0, 0, -1.0);
  37621. uvs.push(1.0, 1.0);
  37622. positions.push(-halfWidth, halfHeight, 0);
  37623. normals.push(0, 0, -1.0);
  37624. uvs.push(0.0, 1.0);
  37625. // Indices
  37626. indices.push(0);
  37627. indices.push(1);
  37628. indices.push(2);
  37629. indices.push(0);
  37630. indices.push(2);
  37631. indices.push(3);
  37632. // Sides
  37633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37634. // Result
  37635. var vertexData = new VertexData();
  37636. vertexData.indices = indices;
  37637. vertexData.positions = positions;
  37638. vertexData.normals = normals;
  37639. vertexData.uvs = uvs;
  37640. return vertexData;
  37641. };
  37642. /**
  37643. * Creates the VertexData of the Disc or regular Polygon
  37644. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37645. * * radius the radius of the disc, optional default 0.5
  37646. * * tessellation the number of polygon sides, optional, default 64
  37647. * * 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
  37648. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37649. * * 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)
  37650. * * 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)
  37651. * @returns the VertexData of the box
  37652. */
  37653. VertexData.CreateDisc = function (options) {
  37654. var positions = new Array();
  37655. var indices = new Array();
  37656. var normals = new Array();
  37657. var uvs = new Array();
  37658. var radius = options.radius || 0.5;
  37659. var tessellation = options.tessellation || 64;
  37660. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37662. // positions and uvs
  37663. positions.push(0, 0, 0); // disc center first
  37664. uvs.push(0.5, 0.5);
  37665. var theta = Math.PI * 2 * arc;
  37666. var step = theta / tessellation;
  37667. for (var a = 0; a < theta; a += step) {
  37668. var x = Math.cos(a);
  37669. var y = Math.sin(a);
  37670. var u = (x + 1) / 2;
  37671. var v = (1 - y) / 2;
  37672. positions.push(radius * x, radius * y, 0);
  37673. uvs.push(u, v);
  37674. }
  37675. if (arc === 1) {
  37676. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37677. uvs.push(uvs[2], uvs[3]);
  37678. }
  37679. //indices
  37680. var vertexNb = positions.length / 3;
  37681. for (var i = 1; i < vertexNb - 1; i++) {
  37682. indices.push(i + 1, 0, i);
  37683. }
  37684. // result
  37685. VertexData.ComputeNormals(positions, indices, normals);
  37686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37687. var vertexData = new VertexData();
  37688. vertexData.indices = indices;
  37689. vertexData.positions = positions;
  37690. vertexData.normals = normals;
  37691. vertexData.uvs = uvs;
  37692. return vertexData;
  37693. };
  37694. /**
  37695. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37696. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37697. * @param polygon a mesh built from polygonTriangulation.build()
  37698. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37699. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37700. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37701. * @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)
  37702. * @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)
  37703. * @returns the VertexData of the Polygon
  37704. */
  37705. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37706. var faceUV = fUV || new Array(3);
  37707. var faceColors = fColors;
  37708. var colors = [];
  37709. // default face colors and UV if undefined
  37710. for (var f = 0; f < 3; f++) {
  37711. if (faceUV[f] === undefined) {
  37712. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37713. }
  37714. if (faceColors && faceColors[f] === undefined) {
  37715. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37716. }
  37717. }
  37718. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37719. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37720. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37721. var indices = polygon.getIndices();
  37722. // set face colours and textures
  37723. var idx = 0;
  37724. var face = 0;
  37725. for (var index = 0; index < normals.length; index += 3) {
  37726. //Edge Face no. 1
  37727. if (Math.abs(normals[index + 1]) < 0.001) {
  37728. face = 1;
  37729. }
  37730. //Top Face no. 0
  37731. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37732. face = 0;
  37733. }
  37734. //Bottom Face no. 2
  37735. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37736. face = 2;
  37737. }
  37738. idx = index / 3;
  37739. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37740. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37741. if (faceColors) {
  37742. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37743. }
  37744. }
  37745. // sides
  37746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37747. // Result
  37748. var vertexData = new VertexData();
  37749. vertexData.indices = indices;
  37750. vertexData.positions = positions;
  37751. vertexData.normals = normals;
  37752. vertexData.uvs = uvs;
  37753. if (faceColors) {
  37754. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37755. vertexData.colors = totalColors;
  37756. }
  37757. return vertexData;
  37758. };
  37759. /**
  37760. * Creates the VertexData of the IcoSphere
  37761. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37762. * * radius the radius of the IcoSphere, optional default 1
  37763. * * radiusX allows stretching in the x direction, optional, default radius
  37764. * * radiusY allows stretching in the y direction, optional, default radius
  37765. * * radiusZ allows stretching in the z direction, optional, default radius
  37766. * * flat when true creates a flat shaded mesh, optional, default true
  37767. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37768. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37769. * * 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)
  37770. * * 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)
  37771. * @returns the VertexData of the IcoSphere
  37772. */
  37773. VertexData.CreateIcoSphere = function (options) {
  37774. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37775. var radius = options.radius || 1;
  37776. var flat = (options.flat === undefined) ? true : options.flat;
  37777. var subdivisions = options.subdivisions || 4;
  37778. var radiusX = options.radiusX || radius;
  37779. var radiusY = options.radiusY || radius;
  37780. var radiusZ = options.radiusZ || radius;
  37781. var t = (1 + Math.sqrt(5)) / 2;
  37782. // 12 vertex x,y,z
  37783. var ico_vertices = [
  37784. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37785. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37786. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37787. ];
  37788. // index of 3 vertex makes a face of icopshere
  37789. var ico_indices = [
  37790. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37791. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37792. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37793. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37794. ];
  37795. // vertex for uv have aliased position, not for UV
  37796. var vertices_unalias_id = [
  37797. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37798. // vertex alias
  37799. 0,
  37800. 2,
  37801. 3,
  37802. 3,
  37803. 3,
  37804. 4,
  37805. 7,
  37806. 8,
  37807. 9,
  37808. 9,
  37809. 10,
  37810. 11 // 23: B + 12
  37811. ];
  37812. // uv as integer step (not pixels !)
  37813. var ico_vertexuv = [
  37814. 5, 1, 3, 1, 6, 4, 0, 0,
  37815. 5, 3, 4, 2, 2, 2, 4, 0,
  37816. 2, 0, 1, 1, 6, 0, 6, 2,
  37817. // vertex alias (for same vertex on different faces)
  37818. 0, 4,
  37819. 3, 3,
  37820. 4, 4,
  37821. 3, 1,
  37822. 4, 2,
  37823. 4, 4,
  37824. 0, 2,
  37825. 1, 1,
  37826. 2, 2,
  37827. 3, 3,
  37828. 1, 3,
  37829. 2, 4 // 23: B + 12
  37830. ];
  37831. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37832. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37833. // First island of uv mapping
  37834. // v = 4h 3+ 2
  37835. // v = 3h 9+ 4
  37836. // v = 2h 9+ 5 B
  37837. // v = 1h 9 1 0
  37838. // v = 0h 3 8 7 A
  37839. // u = 0 1 2 3 4 5 6 *a
  37840. // Second island of uv mapping
  37841. // v = 4h 0+ B+ 4+
  37842. // v = 3h A+ 2+
  37843. // v = 2h 7+ 6 3+
  37844. // v = 1h 8+ 3+
  37845. // v = 0h
  37846. // u = 0 1 2 3 4 5 6 *a
  37847. // Face layout on texture UV mapping
  37848. // ============
  37849. // \ 4 /\ 16 / ======
  37850. // \ / \ / /\ 11 /
  37851. // \/ 7 \/ / \ /
  37852. // ======= / 10 \/
  37853. // /\ 17 /\ =======
  37854. // / \ / \ \ 15 /\
  37855. // / 8 \/ 12 \ \ / \
  37856. // ============ \/ 6 \
  37857. // \ 18 /\ ============
  37858. // \ / \ \ 5 /\ 0 /
  37859. // \/ 13 \ \ / \ /
  37860. // ======= \/ 1 \/
  37861. // =============
  37862. // /\ 19 /\ 2 /\
  37863. // / \ / \ / \
  37864. // / 14 \/ 9 \/ 3 \
  37865. // ===================
  37866. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37867. var ustep = 138 / 1024;
  37868. var vstep = 239 / 1024;
  37869. var uoffset = 60 / 1024;
  37870. var voffset = 26 / 1024;
  37871. // Second island should have margin, not to touch the first island
  37872. // avoid any borderline artefact in pixel rounding
  37873. var island_u_offset = -40 / 1024;
  37874. var island_v_offset = +20 / 1024;
  37875. // face is either island 0 or 1 :
  37876. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37877. var island = [
  37878. 0, 0, 0, 0, 1,
  37879. 0, 0, 1, 1, 0,
  37880. 0, 0, 1, 1, 0,
  37881. 0, 1, 1, 1, 0 // 15 - 19
  37882. ];
  37883. var indices = new Array();
  37884. var positions = new Array();
  37885. var normals = new Array();
  37886. var uvs = new Array();
  37887. var current_indice = 0;
  37888. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37889. var face_vertex_pos = new Array(3);
  37890. var face_vertex_uv = new Array(3);
  37891. var v012;
  37892. for (v012 = 0; v012 < 3; v012++) {
  37893. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37894. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37895. }
  37896. // create all with normals
  37897. for (var face = 0; face < 20; face++) {
  37898. // 3 vertex per face
  37899. for (v012 = 0; v012 < 3; v012++) {
  37900. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37901. var v_id = ico_indices[3 * face + v012];
  37902. // vertex have 3D position (x,y,z)
  37903. 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]);
  37904. // Normalize to get normal, then scale to radius
  37905. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37906. // uv Coordinates from vertex ID
  37907. 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);
  37908. }
  37909. // Subdivide the face (interpolate pos, norm, uv)
  37910. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37911. // - norm is linear interpolation of vertex corner normal
  37912. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37913. // - uv is linear interpolation
  37914. //
  37915. // Topology is as below for sub-divide by 2
  37916. // vertex shown as v0,v1,v2
  37917. // interp index is i1 to progress in range [v0,v1[
  37918. // interp index is i2 to progress in range [v0,v2[
  37919. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37920. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37921. //
  37922. //
  37923. // i2 v2
  37924. // ^ ^
  37925. // / / \
  37926. // / / \
  37927. // / / \
  37928. // / / (0,1) \
  37929. // / #---------\
  37930. // / / \ (0,0)'/ \
  37931. // / / \ / \
  37932. // / / \ / \
  37933. // / / (0,0) \ / (1,0) \
  37934. // / #---------#---------\
  37935. // v0 v1
  37936. //
  37937. // --------------------> i1
  37938. //
  37939. // interp of (i1,i2):
  37940. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37941. // along i1 : lerp(x0,x1, i1/(S-i2))
  37942. //
  37943. // centroid of triangle is needed to get help normal computation
  37944. // (c1,c2) are used for centroid location
  37945. var interp_vertex = function (i1, i2, c1, c2) {
  37946. // vertex is interpolated from
  37947. // - face_vertex_pos[0..2]
  37948. // - face_vertex_uv[0..2]
  37949. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37950. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37951. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37952. pos_interp.normalize();
  37953. var vertex_normal;
  37954. if (flat) {
  37955. // in flat mode, recalculate normal as face centroid normal
  37956. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37957. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37958. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37959. }
  37960. else {
  37961. // in smooth mode, recalculate normal from each single vertex position
  37962. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37963. }
  37964. // Vertex normal need correction due to X,Y,Z radius scaling
  37965. vertex_normal.x /= radiusX;
  37966. vertex_normal.y /= radiusY;
  37967. vertex_normal.z /= radiusZ;
  37968. vertex_normal.normalize();
  37969. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37970. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37971. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37972. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37973. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37974. uvs.push(uv_interp.x, uv_interp.y);
  37975. // push each vertex has member of a face
  37976. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37977. indices.push(current_indice);
  37978. current_indice++;
  37979. };
  37980. for (var i2 = 0; i2 < subdivisions; i2++) {
  37981. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37982. // face : (i1,i2) for /\ :
  37983. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37984. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37985. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37986. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37987. if (i1 + i2 + 1 < subdivisions) {
  37988. // face : (i1,i2)' for \/ :
  37989. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37990. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37991. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37992. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37993. }
  37994. }
  37995. }
  37996. }
  37997. // Sides
  37998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37999. // Result
  38000. var vertexData = new VertexData();
  38001. vertexData.indices = indices;
  38002. vertexData.positions = positions;
  38003. vertexData.normals = normals;
  38004. vertexData.uvs = uvs;
  38005. return vertexData;
  38006. };
  38007. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38008. /**
  38009. * Creates the VertexData for a Polyhedron
  38010. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38011. * * type provided types are:
  38012. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38013. * * 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)
  38014. * * size the size of the IcoSphere, optional default 1
  38015. * * sizeX allows stretching in the x direction, optional, default size
  38016. * * sizeY allows stretching in the y direction, optional, default size
  38017. * * sizeZ allows stretching in the z direction, optional, default size
  38018. * * 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
  38019. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38020. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38021. * * flat when true creates a flat shaded mesh, optional, default true
  38022. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38023. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38024. * * 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)
  38025. * * 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)
  38026. * @returns the VertexData of the Polyhedron
  38027. */
  38028. VertexData.CreatePolyhedron = function (options) {
  38029. // provided polyhedron types :
  38030. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38031. // 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)
  38032. var polyhedra = [];
  38033. 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]] };
  38034. 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]] };
  38035. polyhedra[2] = {
  38036. 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]],
  38037. 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]]
  38038. };
  38039. polyhedra[3] = {
  38040. 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]],
  38041. 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]]
  38042. };
  38043. polyhedra[4] = {
  38044. 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]],
  38045. 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]]
  38046. };
  38047. 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]] };
  38048. 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]] };
  38049. 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]] };
  38050. 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]] };
  38051. 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]] };
  38052. 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]] };
  38053. 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]] };
  38054. 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]] };
  38055. 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]] };
  38056. polyhedra[14] = {
  38057. 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]],
  38058. 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]]
  38059. };
  38060. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38061. var size = options.size;
  38062. var sizeX = options.sizeX || size || 1;
  38063. var sizeY = options.sizeY || size || 1;
  38064. var sizeZ = options.sizeZ || size || 1;
  38065. var data = options.custom || polyhedra[type];
  38066. var nbfaces = data.face.length;
  38067. var faceUV = options.faceUV || new Array(nbfaces);
  38068. var faceColors = options.faceColors;
  38069. var flat = (options.flat === undefined) ? true : options.flat;
  38070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38071. var positions = new Array();
  38072. var indices = new Array();
  38073. var normals = new Array();
  38074. var uvs = new Array();
  38075. var colors = new Array();
  38076. var index = 0;
  38077. var faceIdx = 0; // face cursor in the array "indexes"
  38078. var indexes = new Array();
  38079. var i = 0;
  38080. var f = 0;
  38081. var u, v, ang, x, y, tmp;
  38082. // default face colors and UV if undefined
  38083. if (flat) {
  38084. for (f = 0; f < nbfaces; f++) {
  38085. if (faceColors && faceColors[f] === undefined) {
  38086. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38087. }
  38088. if (faceUV && faceUV[f] === undefined) {
  38089. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38090. }
  38091. }
  38092. }
  38093. if (!flat) {
  38094. for (i = 0; i < data.vertex.length; i++) {
  38095. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38096. uvs.push(0, 0);
  38097. }
  38098. for (f = 0; f < nbfaces; f++) {
  38099. for (i = 0; i < data.face[f].length - 2; i++) {
  38100. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38101. }
  38102. }
  38103. }
  38104. else {
  38105. for (f = 0; f < nbfaces; f++) {
  38106. var fl = data.face[f].length; // number of vertices of the current face
  38107. ang = 2 * Math.PI / fl;
  38108. x = 0.5 * Math.tan(ang / 2);
  38109. y = 0.5;
  38110. // positions, uvs, colors
  38111. for (i = 0; i < fl; i++) {
  38112. // positions
  38113. 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);
  38114. indexes.push(index);
  38115. index++;
  38116. // uvs
  38117. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38118. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38119. uvs.push(u, v);
  38120. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38121. y = x * Math.sin(ang) + y * Math.cos(ang);
  38122. x = tmp;
  38123. // colors
  38124. if (faceColors) {
  38125. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38126. }
  38127. }
  38128. // indices from indexes
  38129. for (i = 0; i < fl - 2; i++) {
  38130. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38131. }
  38132. faceIdx += fl;
  38133. }
  38134. }
  38135. VertexData.ComputeNormals(positions, indices, normals);
  38136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38137. var vertexData = new VertexData();
  38138. vertexData.positions = positions;
  38139. vertexData.indices = indices;
  38140. vertexData.normals = normals;
  38141. vertexData.uvs = uvs;
  38142. if (faceColors && flat) {
  38143. vertexData.colors = colors;
  38144. }
  38145. return vertexData;
  38146. };
  38147. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38148. /**
  38149. * Creates the VertexData for a TorusKnot
  38150. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38151. * * radius the radius of the torus knot, optional, default 2
  38152. * * tube the thickness of the tube, optional, default 0.5
  38153. * * radialSegments the number of sides on each tube segments, optional, default 32
  38154. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38155. * * p the number of windings around the z axis, optional, default 2
  38156. * * q the number of windings around the x axis, optional, default 3
  38157. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38158. * * 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)
  38159. * * 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)
  38160. * @returns the VertexData of the Torus Knot
  38161. */
  38162. VertexData.CreateTorusKnot = function (options) {
  38163. var indices = new Array();
  38164. var positions = new Array();
  38165. var normals = new Array();
  38166. var uvs = new Array();
  38167. var radius = options.radius || 2;
  38168. var tube = options.tube || 0.5;
  38169. var radialSegments = options.radialSegments || 32;
  38170. var tubularSegments = options.tubularSegments || 32;
  38171. var p = options.p || 2;
  38172. var q = options.q || 3;
  38173. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38174. // Helper
  38175. var getPos = function (angle) {
  38176. var cu = Math.cos(angle);
  38177. var su = Math.sin(angle);
  38178. var quOverP = q / p * angle;
  38179. var cs = Math.cos(quOverP);
  38180. var tx = radius * (2 + cs) * 0.5 * cu;
  38181. var ty = radius * (2 + cs) * su * 0.5;
  38182. var tz = radius * Math.sin(quOverP) * 0.5;
  38183. return new BABYLON.Vector3(tx, ty, tz);
  38184. };
  38185. // Vertices
  38186. var i;
  38187. var j;
  38188. for (i = 0; i <= radialSegments; i++) {
  38189. var modI = i % radialSegments;
  38190. var u = modI / radialSegments * 2 * p * Math.PI;
  38191. var p1 = getPos(u);
  38192. var p2 = getPos(u + 0.01);
  38193. var tang = p2.subtract(p1);
  38194. var n = p2.add(p1);
  38195. var bitan = BABYLON.Vector3.Cross(tang, n);
  38196. n = BABYLON.Vector3.Cross(bitan, tang);
  38197. bitan.normalize();
  38198. n.normalize();
  38199. for (j = 0; j < tubularSegments; j++) {
  38200. var modJ = j % tubularSegments;
  38201. var v = modJ / tubularSegments * 2 * Math.PI;
  38202. var cx = -tube * Math.cos(v);
  38203. var cy = tube * Math.sin(v);
  38204. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38205. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38206. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38207. uvs.push(i / radialSegments);
  38208. uvs.push(j / tubularSegments);
  38209. }
  38210. }
  38211. for (i = 0; i < radialSegments; i++) {
  38212. for (j = 0; j < tubularSegments; j++) {
  38213. var jNext = (j + 1) % tubularSegments;
  38214. var a = i * tubularSegments + j;
  38215. var b = (i + 1) * tubularSegments + j;
  38216. var c = (i + 1) * tubularSegments + jNext;
  38217. var d = i * tubularSegments + jNext;
  38218. indices.push(d);
  38219. indices.push(b);
  38220. indices.push(a);
  38221. indices.push(d);
  38222. indices.push(c);
  38223. indices.push(b);
  38224. }
  38225. }
  38226. // Normals
  38227. VertexData.ComputeNormals(positions, indices, normals);
  38228. // Sides
  38229. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38230. // Result
  38231. var vertexData = new VertexData();
  38232. vertexData.indices = indices;
  38233. vertexData.positions = positions;
  38234. vertexData.normals = normals;
  38235. vertexData.uvs = uvs;
  38236. return vertexData;
  38237. };
  38238. // Tools
  38239. /**
  38240. * Compute normals for given positions and indices
  38241. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38242. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38243. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38244. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38245. * * facetNormals : optional array of facet normals (vector3)
  38246. * * facetPositions : optional array of facet positions (vector3)
  38247. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38248. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38249. * * bInfo : optional bounding info, required for facetPartitioning computation
  38250. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38251. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38252. * * useRightHandedSystem: optional boolean to for right handed system computation
  38253. * * depthSort : optional boolean to enable the facet depth sort computation
  38254. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38255. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38256. */
  38257. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38258. // temporary scalar variables
  38259. var index = 0; // facet index
  38260. var p1p2x = 0.0; // p1p2 vector x coordinate
  38261. var p1p2y = 0.0; // p1p2 vector y coordinate
  38262. var p1p2z = 0.0; // p1p2 vector z coordinate
  38263. var p3p2x = 0.0; // p3p2 vector x coordinate
  38264. var p3p2y = 0.0; // p3p2 vector y coordinate
  38265. var p3p2z = 0.0; // p3p2 vector z coordinate
  38266. var faceNormalx = 0.0; // facet normal x coordinate
  38267. var faceNormaly = 0.0; // facet normal y coordinate
  38268. var faceNormalz = 0.0; // facet normal z coordinate
  38269. var length = 0.0; // facet normal length before normalization
  38270. var v1x = 0; // vector1 x index in the positions array
  38271. var v1y = 0; // vector1 y index in the positions array
  38272. var v1z = 0; // vector1 z index in the positions array
  38273. var v2x = 0; // vector2 x index in the positions array
  38274. var v2y = 0; // vector2 y index in the positions array
  38275. var v2z = 0; // vector2 z index in the positions array
  38276. var v3x = 0; // vector3 x index in the positions array
  38277. var v3y = 0; // vector3 y index in the positions array
  38278. var v3z = 0; // vector3 z index in the positions array
  38279. var computeFacetNormals = false;
  38280. var computeFacetPositions = false;
  38281. var computeFacetPartitioning = false;
  38282. var computeDepthSort = false;
  38283. var faceNormalSign = 1;
  38284. var ratio = 0;
  38285. var distanceTo = null;
  38286. if (options) {
  38287. computeFacetNormals = (options.facetNormals) ? true : false;
  38288. computeFacetPositions = (options.facetPositions) ? true : false;
  38289. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38290. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38291. ratio = options.ratio || 0;
  38292. computeDepthSort = (options.depthSort) ? true : false;
  38293. distanceTo = (options.distanceTo);
  38294. if (computeDepthSort) {
  38295. if (distanceTo === undefined) {
  38296. distanceTo = BABYLON.Vector3.Zero();
  38297. }
  38298. var depthSortedFacets = options.depthSortedFacets;
  38299. }
  38300. }
  38301. // facetPartitioning reinit if needed
  38302. var xSubRatio = 0;
  38303. var ySubRatio = 0;
  38304. var zSubRatio = 0;
  38305. var subSq = 0;
  38306. if (computeFacetPartitioning && options && options.bbSize) {
  38307. var ox = 0; // X partitioning index for facet position
  38308. var oy = 0; // Y partinioning index for facet position
  38309. var oz = 0; // Z partinioning index for facet position
  38310. var b1x = 0; // X partitioning index for facet v1 vertex
  38311. var b1y = 0; // Y partitioning index for facet v1 vertex
  38312. var b1z = 0; // z partitioning index for facet v1 vertex
  38313. var b2x = 0; // X partitioning index for facet v2 vertex
  38314. var b2y = 0; // Y partitioning index for facet v2 vertex
  38315. var b2z = 0; // Z partitioning index for facet v2 vertex
  38316. var b3x = 0; // X partitioning index for facet v3 vertex
  38317. var b3y = 0; // Y partitioning index for facet v3 vertex
  38318. var b3z = 0; // Z partitioning index for facet v3 vertex
  38319. var block_idx_o = 0; // facet barycenter block index
  38320. var block_idx_v1 = 0; // v1 vertex block index
  38321. var block_idx_v2 = 0; // v2 vertex block index
  38322. var block_idx_v3 = 0; // v3 vertex block index
  38323. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38324. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38325. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38326. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38327. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38328. subSq = options.subDiv.max * options.subDiv.max;
  38329. options.facetPartitioning.length = 0;
  38330. }
  38331. // reset the normals
  38332. for (index = 0; index < positions.length; index++) {
  38333. normals[index] = 0.0;
  38334. }
  38335. // Loop : 1 indice triplet = 1 facet
  38336. var nbFaces = (indices.length / 3) | 0;
  38337. for (index = 0; index < nbFaces; index++) {
  38338. // get the indexes of the coordinates of each vertex of the facet
  38339. v1x = indices[index * 3] * 3;
  38340. v1y = v1x + 1;
  38341. v1z = v1x + 2;
  38342. v2x = indices[index * 3 + 1] * 3;
  38343. v2y = v2x + 1;
  38344. v2z = v2x + 2;
  38345. v3x = indices[index * 3 + 2] * 3;
  38346. v3y = v3x + 1;
  38347. v3z = v3x + 2;
  38348. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38349. p1p2y = positions[v1y] - positions[v2y];
  38350. p1p2z = positions[v1z] - positions[v2z];
  38351. p3p2x = positions[v3x] - positions[v2x];
  38352. p3p2y = positions[v3y] - positions[v2y];
  38353. p3p2z = positions[v3z] - positions[v2z];
  38354. // compute the face normal with the cross product
  38355. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38356. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38357. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38358. // normalize this normal and store it in the array facetData
  38359. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38360. length = (length === 0) ? 1.0 : length;
  38361. faceNormalx /= length;
  38362. faceNormaly /= length;
  38363. faceNormalz /= length;
  38364. if (computeFacetNormals && options) {
  38365. options.facetNormals[index].x = faceNormalx;
  38366. options.facetNormals[index].y = faceNormaly;
  38367. options.facetNormals[index].z = faceNormalz;
  38368. }
  38369. if (computeFacetPositions && options) {
  38370. // compute and the facet barycenter coordinates in the array facetPositions
  38371. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38372. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38373. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38374. }
  38375. if (computeFacetPartitioning && options) {
  38376. // store the facet indexes in arrays in the main facetPartitioning array :
  38377. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38378. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38379. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38380. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38381. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38382. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38383. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38384. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38385. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38386. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38387. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38388. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38389. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38390. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38391. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38392. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38393. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38394. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38395. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38396. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38397. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38398. // push each facet index in each block containing the vertex
  38399. options.facetPartitioning[block_idx_v1].push(index);
  38400. if (block_idx_v2 != block_idx_v1) {
  38401. options.facetPartitioning[block_idx_v2].push(index);
  38402. }
  38403. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38404. options.facetPartitioning[block_idx_v3].push(index);
  38405. }
  38406. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38407. options.facetPartitioning[block_idx_o].push(index);
  38408. }
  38409. }
  38410. if (computeDepthSort && options && options.facetPositions) {
  38411. var dsf = depthSortedFacets[index];
  38412. dsf.ind = index * 3;
  38413. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38414. }
  38415. // compute the normals anyway
  38416. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38417. normals[v1y] += faceNormaly;
  38418. normals[v1z] += faceNormalz;
  38419. normals[v2x] += faceNormalx;
  38420. normals[v2y] += faceNormaly;
  38421. normals[v2z] += faceNormalz;
  38422. normals[v3x] += faceNormalx;
  38423. normals[v3y] += faceNormaly;
  38424. normals[v3z] += faceNormalz;
  38425. }
  38426. // last normalization of each normal
  38427. for (index = 0; index < normals.length / 3; index++) {
  38428. faceNormalx = normals[index * 3];
  38429. faceNormaly = normals[index * 3 + 1];
  38430. faceNormalz = normals[index * 3 + 2];
  38431. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38432. length = (length === 0) ? 1.0 : length;
  38433. faceNormalx /= length;
  38434. faceNormaly /= length;
  38435. faceNormalz /= length;
  38436. normals[index * 3] = faceNormalx;
  38437. normals[index * 3 + 1] = faceNormaly;
  38438. normals[index * 3 + 2] = faceNormalz;
  38439. }
  38440. };
  38441. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38442. var li = indices.length;
  38443. var ln = normals.length;
  38444. var i;
  38445. var n;
  38446. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38447. switch (sideOrientation) {
  38448. case BABYLON.Mesh.FRONTSIDE:
  38449. // nothing changed
  38450. break;
  38451. case BABYLON.Mesh.BACKSIDE:
  38452. var tmp;
  38453. // indices
  38454. for (i = 0; i < li; i += 3) {
  38455. tmp = indices[i];
  38456. indices[i] = indices[i + 2];
  38457. indices[i + 2] = tmp;
  38458. }
  38459. // normals
  38460. for (n = 0; n < ln; n++) {
  38461. normals[n] = -normals[n];
  38462. }
  38463. break;
  38464. case BABYLON.Mesh.DOUBLESIDE:
  38465. // positions
  38466. var lp = positions.length;
  38467. var l = lp / 3;
  38468. for (var p = 0; p < lp; p++) {
  38469. positions[lp + p] = positions[p];
  38470. }
  38471. // indices
  38472. for (i = 0; i < li; i += 3) {
  38473. indices[i + li] = indices[i + 2] + l;
  38474. indices[i + 1 + li] = indices[i + 1] + l;
  38475. indices[i + 2 + li] = indices[i] + l;
  38476. }
  38477. // normals
  38478. for (n = 0; n < ln; n++) {
  38479. normals[ln + n] = -normals[n];
  38480. }
  38481. // uvs
  38482. var lu = uvs.length;
  38483. var u = 0;
  38484. for (u = 0; u < lu; u++) {
  38485. uvs[u + lu] = uvs[u];
  38486. }
  38487. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38488. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38489. u = 0;
  38490. for (i = 0; i < lu / 2; i++) {
  38491. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38492. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38493. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38494. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38495. u += 2;
  38496. }
  38497. break;
  38498. }
  38499. };
  38500. /**
  38501. * Applies VertexData created from the imported parameters to the geometry
  38502. * @param parsedVertexData the parsed data from an imported file
  38503. * @param geometry the geometry to apply the VertexData to
  38504. */
  38505. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38506. var vertexData = new VertexData();
  38507. // positions
  38508. var positions = parsedVertexData.positions;
  38509. if (positions) {
  38510. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38511. }
  38512. // normals
  38513. var normals = parsedVertexData.normals;
  38514. if (normals) {
  38515. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38516. }
  38517. // tangents
  38518. var tangents = parsedVertexData.tangents;
  38519. if (tangents) {
  38520. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38521. }
  38522. // uvs
  38523. var uvs = parsedVertexData.uvs;
  38524. if (uvs) {
  38525. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38526. }
  38527. // uv2s
  38528. var uv2s = parsedVertexData.uv2s;
  38529. if (uv2s) {
  38530. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38531. }
  38532. // uv3s
  38533. var uv3s = parsedVertexData.uv3s;
  38534. if (uv3s) {
  38535. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38536. }
  38537. // uv4s
  38538. var uv4s = parsedVertexData.uv4s;
  38539. if (uv4s) {
  38540. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38541. }
  38542. // uv5s
  38543. var uv5s = parsedVertexData.uv5s;
  38544. if (uv5s) {
  38545. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38546. }
  38547. // uv6s
  38548. var uv6s = parsedVertexData.uv6s;
  38549. if (uv6s) {
  38550. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38551. }
  38552. // colors
  38553. var colors = parsedVertexData.colors;
  38554. if (colors) {
  38555. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38556. }
  38557. // matricesIndices
  38558. var matricesIndices = parsedVertexData.matricesIndices;
  38559. if (matricesIndices) {
  38560. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38561. }
  38562. // matricesWeights
  38563. var matricesWeights = parsedVertexData.matricesWeights;
  38564. if (matricesWeights) {
  38565. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38566. }
  38567. // indices
  38568. var indices = parsedVertexData.indices;
  38569. if (indices) {
  38570. vertexData.indices = indices;
  38571. }
  38572. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38573. };
  38574. return VertexData;
  38575. }());
  38576. BABYLON.VertexData = VertexData;
  38577. })(BABYLON || (BABYLON = {}));
  38578. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38579. var BABYLON;
  38580. (function (BABYLON) {
  38581. /**
  38582. * Class used to store geometry data (vertex buffers + index buffer)
  38583. */
  38584. var Geometry = /** @class */ (function () {
  38585. /**
  38586. * Creates a new geometry
  38587. * @param id defines the unique ID
  38588. * @param scene defines the hosting scene
  38589. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38590. * @param updatable defines if geometry must be updatable (false by default)
  38591. * @param mesh defines the mesh that will be associated with the geometry
  38592. */
  38593. function Geometry(id, scene, vertexData, updatable, mesh) {
  38594. if (updatable === void 0) { updatable = false; }
  38595. if (mesh === void 0) { mesh = null; }
  38596. /**
  38597. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38598. */
  38599. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38600. this._totalVertices = 0;
  38601. this._isDisposed = false;
  38602. this._indexBufferIsUpdatable = false;
  38603. this.id = id;
  38604. this._engine = scene.getEngine();
  38605. this._meshes = [];
  38606. this._scene = scene;
  38607. //Init vertex buffer cache
  38608. this._vertexBuffers = {};
  38609. this._indices = [];
  38610. this._updatable = updatable;
  38611. // vertexData
  38612. if (vertexData) {
  38613. this.setAllVerticesData(vertexData, updatable);
  38614. }
  38615. else {
  38616. this._totalVertices = 0;
  38617. this._indices = [];
  38618. }
  38619. if (this._engine.getCaps().vertexArrayObject) {
  38620. this._vertexArrayObjects = {};
  38621. }
  38622. // applyToMesh
  38623. if (mesh) {
  38624. if (mesh.getClassName() === "LinesMesh") {
  38625. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38626. this._updateExtend();
  38627. }
  38628. this.applyToMesh(mesh);
  38629. mesh.computeWorldMatrix(true);
  38630. }
  38631. }
  38632. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38633. /**
  38634. * 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
  38635. */
  38636. get: function () {
  38637. return this._boundingBias;
  38638. },
  38639. /**
  38640. * 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
  38641. */
  38642. set: function (value) {
  38643. if (this._boundingBias && this._boundingBias.equals(value)) {
  38644. return;
  38645. }
  38646. this._boundingBias = value.clone();
  38647. this._updateBoundingInfo(true, null);
  38648. },
  38649. enumerable: true,
  38650. configurable: true
  38651. });
  38652. /**
  38653. * Static function used to attach a new empty geometry to a mesh
  38654. * @param mesh defines the mesh to attach the geometry to
  38655. * @returns the new {BABYLON.Geometry}
  38656. */
  38657. Geometry.CreateGeometryForMesh = function (mesh) {
  38658. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38659. geometry.applyToMesh(mesh);
  38660. return geometry;
  38661. };
  38662. Object.defineProperty(Geometry.prototype, "extend", {
  38663. /**
  38664. * Gets the current extend of the geometry
  38665. */
  38666. get: function () {
  38667. return this._extend;
  38668. },
  38669. enumerable: true,
  38670. configurable: true
  38671. });
  38672. /**
  38673. * Gets the hosting scene
  38674. * @returns the hosting {BABYLON.Scene}
  38675. */
  38676. Geometry.prototype.getScene = function () {
  38677. return this._scene;
  38678. };
  38679. /**
  38680. * Gets the hosting engine
  38681. * @returns the hosting {BABYLON.Engine}
  38682. */
  38683. Geometry.prototype.getEngine = function () {
  38684. return this._engine;
  38685. };
  38686. /**
  38687. * Defines if the geometry is ready to use
  38688. * @returns true if the geometry is ready to be used
  38689. */
  38690. Geometry.prototype.isReady = function () {
  38691. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38692. };
  38693. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38694. /**
  38695. * Gets a value indicating that the geometry should not be serialized
  38696. */
  38697. get: function () {
  38698. for (var index = 0; index < this._meshes.length; index++) {
  38699. if (!this._meshes[index].doNotSerialize) {
  38700. return false;
  38701. }
  38702. }
  38703. return true;
  38704. },
  38705. enumerable: true,
  38706. configurable: true
  38707. });
  38708. /** @hidden */
  38709. Geometry.prototype._rebuild = function () {
  38710. if (this._vertexArrayObjects) {
  38711. this._vertexArrayObjects = {};
  38712. }
  38713. // Index buffer
  38714. if (this._meshes.length !== 0 && this._indices) {
  38715. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38716. }
  38717. // Vertex buffers
  38718. for (var key in this._vertexBuffers) {
  38719. var vertexBuffer = this._vertexBuffers[key];
  38720. vertexBuffer._rebuild();
  38721. }
  38722. };
  38723. /**
  38724. * Affects all geometry data in one call
  38725. * @param vertexData defines the geometry data
  38726. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38727. */
  38728. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38729. vertexData.applyToGeometry(this, updatable);
  38730. this.notifyUpdate();
  38731. };
  38732. /**
  38733. * Set specific vertex data
  38734. * @param kind defines the data kind (Position, normal, etc...)
  38735. * @param data defines the vertex data to use
  38736. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38737. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38738. */
  38739. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38740. if (updatable === void 0) { updatable = false; }
  38741. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38742. this.setVerticesBuffer(buffer);
  38743. };
  38744. /**
  38745. * Removes a specific vertex data
  38746. * @param kind defines the data kind (Position, normal, etc...)
  38747. */
  38748. Geometry.prototype.removeVerticesData = function (kind) {
  38749. if (this._vertexBuffers[kind]) {
  38750. this._vertexBuffers[kind].dispose();
  38751. delete this._vertexBuffers[kind];
  38752. }
  38753. };
  38754. /**
  38755. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38756. * @param buffer defines the vertex buffer to use
  38757. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38758. */
  38759. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38760. if (totalVertices === void 0) { totalVertices = null; }
  38761. var kind = buffer.getKind();
  38762. if (this._vertexBuffers[kind]) {
  38763. this._vertexBuffers[kind].dispose();
  38764. }
  38765. this._vertexBuffers[kind] = buffer;
  38766. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38767. var data = buffer.getData();
  38768. if (totalVertices != null) {
  38769. this._totalVertices = totalVertices;
  38770. }
  38771. else {
  38772. if (data != null) {
  38773. this._totalVertices = data.length / (buffer.byteStride / 4);
  38774. }
  38775. }
  38776. this._updateExtend(data);
  38777. this._resetPointsArrayCache();
  38778. var meshes = this._meshes;
  38779. var numOfMeshes = meshes.length;
  38780. for (var index = 0; index < numOfMeshes; index++) {
  38781. var mesh = meshes[index];
  38782. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38783. mesh._createGlobalSubMesh(false);
  38784. mesh.computeWorldMatrix(true);
  38785. }
  38786. }
  38787. this.notifyUpdate(kind);
  38788. if (this._vertexArrayObjects) {
  38789. this._disposeVertexArrayObjects();
  38790. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38791. }
  38792. };
  38793. /**
  38794. * Update a specific vertex buffer
  38795. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38796. * It will do nothing if the buffer is not updatable
  38797. * @param kind defines the data kind (Position, normal, etc...)
  38798. * @param data defines the data to use
  38799. * @param offset defines the offset in the target buffer where to store the data
  38800. * @param useBytes set to true if the offset is in bytes
  38801. */
  38802. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38803. if (useBytes === void 0) { useBytes = false; }
  38804. var vertexBuffer = this.getVertexBuffer(kind);
  38805. if (!vertexBuffer) {
  38806. return;
  38807. }
  38808. vertexBuffer.updateDirectly(data, offset, useBytes);
  38809. this.notifyUpdate(kind);
  38810. };
  38811. /**
  38812. * Update a specific vertex buffer
  38813. * This function will create a new buffer if the current one is not updatable
  38814. * @param kind defines the data kind (Position, normal, etc...)
  38815. * @param data defines the data to use
  38816. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38817. */
  38818. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38819. if (updateExtends === void 0) { updateExtends = false; }
  38820. var vertexBuffer = this.getVertexBuffer(kind);
  38821. if (!vertexBuffer) {
  38822. return;
  38823. }
  38824. vertexBuffer.update(data);
  38825. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38826. this._updateBoundingInfo(updateExtends, data);
  38827. }
  38828. this.notifyUpdate(kind);
  38829. };
  38830. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38831. if (updateExtends) {
  38832. this._updateExtend(data);
  38833. }
  38834. var meshes = this._meshes;
  38835. var numOfMeshes = meshes.length;
  38836. this._resetPointsArrayCache();
  38837. for (var index = 0; index < numOfMeshes; index++) {
  38838. var mesh = meshes[index];
  38839. if (updateExtends) {
  38840. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38841. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38842. var subMesh = mesh.subMeshes[subIndex];
  38843. subMesh.refreshBoundingInfo();
  38844. }
  38845. }
  38846. }
  38847. };
  38848. /** @hidden */
  38849. Geometry.prototype._bind = function (effect, indexToBind) {
  38850. if (!effect) {
  38851. return;
  38852. }
  38853. if (indexToBind === undefined) {
  38854. indexToBind = this._indexBuffer;
  38855. }
  38856. var vbs = this.getVertexBuffers();
  38857. if (!vbs) {
  38858. return;
  38859. }
  38860. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38861. this._engine.bindBuffers(vbs, indexToBind, effect);
  38862. return;
  38863. }
  38864. // Using VAO
  38865. if (!this._vertexArrayObjects[effect.key]) {
  38866. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38867. }
  38868. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38869. };
  38870. /**
  38871. * Gets total number of vertices
  38872. * @returns the total number of vertices
  38873. */
  38874. Geometry.prototype.getTotalVertices = function () {
  38875. if (!this.isReady()) {
  38876. return 0;
  38877. }
  38878. return this._totalVertices;
  38879. };
  38880. /**
  38881. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38882. * @param kind defines the data kind (Position, normal, etc...)
  38883. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38884. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38885. * @returns a float array containing vertex data
  38886. */
  38887. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38888. var vertexBuffer = this.getVertexBuffer(kind);
  38889. if (!vertexBuffer) {
  38890. return null;
  38891. }
  38892. var data = vertexBuffer.getData();
  38893. if (!data) {
  38894. return null;
  38895. }
  38896. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38897. var count = this._totalVertices * vertexBuffer.getSize();
  38898. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38899. var copy_1 = new Array(count);
  38900. vertexBuffer.forEach(count, function (value, index) {
  38901. copy_1[index] = value;
  38902. });
  38903. return copy_1;
  38904. }
  38905. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38906. if (data instanceof Array) {
  38907. var offset = vertexBuffer.byteOffset / 4;
  38908. return BABYLON.Tools.Slice(data, offset, offset + count);
  38909. }
  38910. else if (data instanceof ArrayBuffer) {
  38911. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38912. }
  38913. else {
  38914. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38915. }
  38916. }
  38917. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38918. return BABYLON.Tools.Slice(data);
  38919. }
  38920. return data;
  38921. };
  38922. /**
  38923. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38924. * @param kind defines the data kind (Position, normal, etc...)
  38925. * @returns true if the vertex buffer with the specified kind is updatable
  38926. */
  38927. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38928. var vb = this._vertexBuffers[kind];
  38929. if (!vb) {
  38930. return false;
  38931. }
  38932. return vb.isUpdatable();
  38933. };
  38934. /**
  38935. * Gets a specific vertex buffer
  38936. * @param kind defines the data kind (Position, normal, etc...)
  38937. * @returns a {BABYLON.VertexBuffer}
  38938. */
  38939. Geometry.prototype.getVertexBuffer = function (kind) {
  38940. if (!this.isReady()) {
  38941. return null;
  38942. }
  38943. return this._vertexBuffers[kind];
  38944. };
  38945. /**
  38946. * Returns all vertex buffers
  38947. * @return an object holding all vertex buffers indexed by kind
  38948. */
  38949. Geometry.prototype.getVertexBuffers = function () {
  38950. if (!this.isReady()) {
  38951. return null;
  38952. }
  38953. return this._vertexBuffers;
  38954. };
  38955. /**
  38956. * Gets a boolean indicating if specific vertex buffer is present
  38957. * @param kind defines the data kind (Position, normal, etc...)
  38958. * @returns true if data is present
  38959. */
  38960. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38961. if (!this._vertexBuffers) {
  38962. if (this._delayInfo) {
  38963. return this._delayInfo.indexOf(kind) !== -1;
  38964. }
  38965. return false;
  38966. }
  38967. return this._vertexBuffers[kind] !== undefined;
  38968. };
  38969. /**
  38970. * Gets a list of all attached data kinds (Position, normal, etc...)
  38971. * @returns a list of string containing all kinds
  38972. */
  38973. Geometry.prototype.getVerticesDataKinds = function () {
  38974. var result = [];
  38975. var kind;
  38976. if (!this._vertexBuffers && this._delayInfo) {
  38977. for (kind in this._delayInfo) {
  38978. result.push(kind);
  38979. }
  38980. }
  38981. else {
  38982. for (kind in this._vertexBuffers) {
  38983. result.push(kind);
  38984. }
  38985. }
  38986. return result;
  38987. };
  38988. /**
  38989. * Update index buffer
  38990. * @param indices defines the indices to store in the index buffer
  38991. * @param offset defines the offset in the target buffer where to store the data
  38992. */
  38993. Geometry.prototype.updateIndices = function (indices, offset) {
  38994. if (!this._indexBuffer) {
  38995. return;
  38996. }
  38997. if (!this._indexBufferIsUpdatable) {
  38998. this.setIndices(indices, null, true);
  38999. }
  39000. else {
  39001. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39002. }
  39003. };
  39004. /**
  39005. * Creates a new index buffer
  39006. * @param indices defines the indices to store in the index buffer
  39007. * @param totalVertices defines the total number of vertices (could be null)
  39008. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39009. */
  39010. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39011. if (totalVertices === void 0) { totalVertices = null; }
  39012. if (updatable === void 0) { updatable = false; }
  39013. if (this._indexBuffer) {
  39014. this._engine._releaseBuffer(this._indexBuffer);
  39015. }
  39016. this._disposeVertexArrayObjects();
  39017. this._indices = indices;
  39018. this._indexBufferIsUpdatable = updatable;
  39019. if (this._meshes.length !== 0 && this._indices) {
  39020. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39021. }
  39022. if (totalVertices != undefined) { // including null and undefined
  39023. this._totalVertices = totalVertices;
  39024. }
  39025. var meshes = this._meshes;
  39026. var numOfMeshes = meshes.length;
  39027. for (var index = 0; index < numOfMeshes; index++) {
  39028. meshes[index]._createGlobalSubMesh(true);
  39029. }
  39030. this.notifyUpdate();
  39031. };
  39032. /**
  39033. * Return the total number of indices
  39034. * @returns the total number of indices
  39035. */
  39036. Geometry.prototype.getTotalIndices = function () {
  39037. if (!this.isReady()) {
  39038. return 0;
  39039. }
  39040. return this._indices.length;
  39041. };
  39042. /**
  39043. * Gets the index buffer array
  39044. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39045. * @returns the index buffer array
  39046. */
  39047. Geometry.prototype.getIndices = function (copyWhenShared) {
  39048. if (!this.isReady()) {
  39049. return null;
  39050. }
  39051. var orig = this._indices;
  39052. if (!copyWhenShared || this._meshes.length === 1) {
  39053. return orig;
  39054. }
  39055. else {
  39056. var len = orig.length;
  39057. var copy = [];
  39058. for (var i = 0; i < len; i++) {
  39059. copy.push(orig[i]);
  39060. }
  39061. return copy;
  39062. }
  39063. };
  39064. /**
  39065. * Gets the index buffer
  39066. * @return the index buffer
  39067. */
  39068. Geometry.prototype.getIndexBuffer = function () {
  39069. if (!this.isReady()) {
  39070. return null;
  39071. }
  39072. return this._indexBuffer;
  39073. };
  39074. /** @hidden */
  39075. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39076. if (effect === void 0) { effect = null; }
  39077. if (!effect || !this._vertexArrayObjects) {
  39078. return;
  39079. }
  39080. if (this._vertexArrayObjects[effect.key]) {
  39081. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39082. delete this._vertexArrayObjects[effect.key];
  39083. }
  39084. };
  39085. /**
  39086. * Release the associated resources for a specific mesh
  39087. * @param mesh defines the source mesh
  39088. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39089. */
  39090. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39091. var meshes = this._meshes;
  39092. var index = meshes.indexOf(mesh);
  39093. if (index === -1) {
  39094. return;
  39095. }
  39096. meshes.splice(index, 1);
  39097. mesh._geometry = null;
  39098. if (meshes.length === 0 && shouldDispose) {
  39099. this.dispose();
  39100. }
  39101. };
  39102. /**
  39103. * Apply current geometry to a given mesh
  39104. * @param mesh defines the mesh to apply geometry to
  39105. */
  39106. Geometry.prototype.applyToMesh = function (mesh) {
  39107. if (mesh._geometry === this) {
  39108. return;
  39109. }
  39110. var previousGeometry = mesh._geometry;
  39111. if (previousGeometry) {
  39112. previousGeometry.releaseForMesh(mesh);
  39113. }
  39114. var meshes = this._meshes;
  39115. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39116. mesh._geometry = this;
  39117. this._scene.pushGeometry(this);
  39118. meshes.push(mesh);
  39119. if (this.isReady()) {
  39120. this._applyToMesh(mesh);
  39121. }
  39122. else {
  39123. mesh._boundingInfo = this._boundingInfo;
  39124. }
  39125. };
  39126. Geometry.prototype._updateExtend = function (data) {
  39127. if (data === void 0) { data = null; }
  39128. if (!data) {
  39129. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39130. }
  39131. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39132. };
  39133. Geometry.prototype._applyToMesh = function (mesh) {
  39134. var numOfMeshes = this._meshes.length;
  39135. // vertexBuffers
  39136. for (var kind in this._vertexBuffers) {
  39137. if (numOfMeshes === 1) {
  39138. this._vertexBuffers[kind].create();
  39139. }
  39140. var buffer = this._vertexBuffers[kind].getBuffer();
  39141. if (buffer)
  39142. buffer.references = numOfMeshes;
  39143. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39144. if (!this._extend) {
  39145. this._updateExtend();
  39146. }
  39147. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39148. mesh._createGlobalSubMesh(false);
  39149. //bounding info was just created again, world matrix should be applied again.
  39150. mesh._updateBoundingInfo();
  39151. }
  39152. }
  39153. // indexBuffer
  39154. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39155. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39156. }
  39157. if (this._indexBuffer) {
  39158. this._indexBuffer.references = numOfMeshes;
  39159. }
  39160. };
  39161. Geometry.prototype.notifyUpdate = function (kind) {
  39162. if (this.onGeometryUpdated) {
  39163. this.onGeometryUpdated(this, kind);
  39164. }
  39165. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39166. var mesh = _a[_i];
  39167. mesh._markSubMeshesAsAttributesDirty();
  39168. }
  39169. };
  39170. /**
  39171. * Load the geometry if it was flagged as delay loaded
  39172. * @param scene defines the hosting scene
  39173. * @param onLoaded defines a callback called when the geometry is loaded
  39174. */
  39175. Geometry.prototype.load = function (scene, onLoaded) {
  39176. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39177. return;
  39178. }
  39179. if (this.isReady()) {
  39180. if (onLoaded) {
  39181. onLoaded();
  39182. }
  39183. return;
  39184. }
  39185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39186. this._queueLoad(scene, onLoaded);
  39187. };
  39188. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39189. var _this = this;
  39190. if (!this.delayLoadingFile) {
  39191. return;
  39192. }
  39193. scene._addPendingData(this);
  39194. scene._loadFile(this.delayLoadingFile, function (data) {
  39195. if (!_this._delayLoadingFunction) {
  39196. return;
  39197. }
  39198. _this._delayLoadingFunction(JSON.parse(data), _this);
  39199. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39200. _this._delayInfo = [];
  39201. scene._removePendingData(_this);
  39202. var meshes = _this._meshes;
  39203. var numOfMeshes = meshes.length;
  39204. for (var index = 0; index < numOfMeshes; index++) {
  39205. _this._applyToMesh(meshes[index]);
  39206. }
  39207. if (onLoaded) {
  39208. onLoaded();
  39209. }
  39210. }, undefined, true);
  39211. };
  39212. /**
  39213. * Invert the geometry to move from a right handed system to a left handed one.
  39214. */
  39215. Geometry.prototype.toLeftHanded = function () {
  39216. // Flip faces
  39217. var tIndices = this.getIndices(false);
  39218. if (tIndices != null && tIndices.length > 0) {
  39219. for (var i = 0; i < tIndices.length; i += 3) {
  39220. var tTemp = tIndices[i + 0];
  39221. tIndices[i + 0] = tIndices[i + 2];
  39222. tIndices[i + 2] = tTemp;
  39223. }
  39224. this.setIndices(tIndices);
  39225. }
  39226. // Negate position.z
  39227. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39228. if (tPositions != null && tPositions.length > 0) {
  39229. for (var i = 0; i < tPositions.length; i += 3) {
  39230. tPositions[i + 2] = -tPositions[i + 2];
  39231. }
  39232. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39233. }
  39234. // Negate normal.z
  39235. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39236. if (tNormals != null && tNormals.length > 0) {
  39237. for (var i = 0; i < tNormals.length; i += 3) {
  39238. tNormals[i + 2] = -tNormals[i + 2];
  39239. }
  39240. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39241. }
  39242. };
  39243. // Cache
  39244. /** @hidden */
  39245. Geometry.prototype._resetPointsArrayCache = function () {
  39246. this._positions = null;
  39247. };
  39248. /** @hidden */
  39249. Geometry.prototype._generatePointsArray = function () {
  39250. if (this._positions)
  39251. return true;
  39252. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39253. if (!data || data.length === 0) {
  39254. return false;
  39255. }
  39256. this._positions = [];
  39257. for (var index = 0; index < data.length; index += 3) {
  39258. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39259. }
  39260. return true;
  39261. };
  39262. /**
  39263. * Gets a value indicating if the geometry is disposed
  39264. * @returns true if the geometry was disposed
  39265. */
  39266. Geometry.prototype.isDisposed = function () {
  39267. return this._isDisposed;
  39268. };
  39269. Geometry.prototype._disposeVertexArrayObjects = function () {
  39270. if (this._vertexArrayObjects) {
  39271. for (var kind in this._vertexArrayObjects) {
  39272. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39273. }
  39274. this._vertexArrayObjects = {};
  39275. }
  39276. };
  39277. /**
  39278. * Free all associated resources
  39279. */
  39280. Geometry.prototype.dispose = function () {
  39281. var meshes = this._meshes;
  39282. var numOfMeshes = meshes.length;
  39283. var index;
  39284. for (index = 0; index < numOfMeshes; index++) {
  39285. this.releaseForMesh(meshes[index]);
  39286. }
  39287. this._meshes = [];
  39288. this._disposeVertexArrayObjects();
  39289. for (var kind in this._vertexBuffers) {
  39290. this._vertexBuffers[kind].dispose();
  39291. }
  39292. this._vertexBuffers = {};
  39293. this._totalVertices = 0;
  39294. if (this._indexBuffer) {
  39295. this._engine._releaseBuffer(this._indexBuffer);
  39296. }
  39297. this._indexBuffer = null;
  39298. this._indices = [];
  39299. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39300. this.delayLoadingFile = null;
  39301. this._delayLoadingFunction = null;
  39302. this._delayInfo = [];
  39303. this._boundingInfo = null;
  39304. this._scene.removeGeometry(this);
  39305. this._isDisposed = true;
  39306. };
  39307. /**
  39308. * Clone the current geometry into a new geometry
  39309. * @param id defines the unique ID of the new geometry
  39310. * @returns a new geometry object
  39311. */
  39312. Geometry.prototype.copy = function (id) {
  39313. var vertexData = new BABYLON.VertexData();
  39314. vertexData.indices = [];
  39315. var indices = this.getIndices();
  39316. if (indices) {
  39317. for (var index = 0; index < indices.length; index++) {
  39318. vertexData.indices.push(indices[index]);
  39319. }
  39320. }
  39321. var updatable = false;
  39322. var stopChecking = false;
  39323. var kind;
  39324. for (kind in this._vertexBuffers) {
  39325. // using slice() to make a copy of the array and not just reference it
  39326. var data = this.getVerticesData(kind);
  39327. if (data instanceof Float32Array) {
  39328. vertexData.set(new Float32Array(data), kind);
  39329. }
  39330. else {
  39331. vertexData.set(data.slice(0), kind);
  39332. }
  39333. if (!stopChecking) {
  39334. var vb = this.getVertexBuffer(kind);
  39335. if (vb) {
  39336. updatable = vb.isUpdatable();
  39337. stopChecking = !updatable;
  39338. }
  39339. }
  39340. }
  39341. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39342. geometry.delayLoadState = this.delayLoadState;
  39343. geometry.delayLoadingFile = this.delayLoadingFile;
  39344. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39345. for (kind in this._delayInfo) {
  39346. geometry._delayInfo = geometry._delayInfo || [];
  39347. geometry._delayInfo.push(kind);
  39348. }
  39349. // Bounding info
  39350. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39351. return geometry;
  39352. };
  39353. /**
  39354. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39355. * @return a JSON representation of the current geometry data (without the vertices data)
  39356. */
  39357. Geometry.prototype.serialize = function () {
  39358. var serializationObject = {};
  39359. serializationObject.id = this.id;
  39360. serializationObject.updatable = this._updatable;
  39361. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39362. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39363. }
  39364. return serializationObject;
  39365. };
  39366. Geometry.prototype.toNumberArray = function (origin) {
  39367. if (Array.isArray(origin)) {
  39368. return origin;
  39369. }
  39370. else {
  39371. return Array.prototype.slice.call(origin);
  39372. }
  39373. };
  39374. /**
  39375. * Serialize all vertices data into a JSON oject
  39376. * @returns a JSON representation of the current geometry data
  39377. */
  39378. Geometry.prototype.serializeVerticeData = function () {
  39379. var serializationObject = this.serialize();
  39380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39381. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39382. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39383. serializationObject.positions._updatable = true;
  39384. }
  39385. }
  39386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39387. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39388. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39389. serializationObject.normals._updatable = true;
  39390. }
  39391. }
  39392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39393. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39395. serializationObject.tangets._updatable = true;
  39396. }
  39397. }
  39398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39399. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39401. serializationObject.uvs._updatable = true;
  39402. }
  39403. }
  39404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39405. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39406. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39407. serializationObject.uv2s._updatable = true;
  39408. }
  39409. }
  39410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39411. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39413. serializationObject.uv3s._updatable = true;
  39414. }
  39415. }
  39416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39417. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39419. serializationObject.uv4s._updatable = true;
  39420. }
  39421. }
  39422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39423. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39424. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39425. serializationObject.uv5s._updatable = true;
  39426. }
  39427. }
  39428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39429. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39430. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39431. serializationObject.uv6s._updatable = true;
  39432. }
  39433. }
  39434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39435. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39436. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39437. serializationObject.colors._updatable = true;
  39438. }
  39439. }
  39440. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39441. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39442. serializationObject.matricesIndices._isExpanded = true;
  39443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39444. serializationObject.matricesIndices._updatable = true;
  39445. }
  39446. }
  39447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39448. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39449. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39450. serializationObject.matricesWeights._updatable = true;
  39451. }
  39452. }
  39453. serializationObject.indices = this.toNumberArray(this.getIndices());
  39454. return serializationObject;
  39455. };
  39456. // Statics
  39457. /**
  39458. * Extracts a clone of a mesh geometry
  39459. * @param mesh defines the source mesh
  39460. * @param id defines the unique ID of the new geometry object
  39461. * @returns the new geometry object
  39462. */
  39463. Geometry.ExtractFromMesh = function (mesh, id) {
  39464. var geometry = mesh._geometry;
  39465. if (!geometry) {
  39466. return null;
  39467. }
  39468. return geometry.copy(id);
  39469. };
  39470. /**
  39471. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39472. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39473. * Be aware Math.random() could cause collisions, but:
  39474. * "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"
  39475. * @returns a string containing a new GUID
  39476. */
  39477. Geometry.RandomId = function () {
  39478. return BABYLON.Tools.RandomId();
  39479. };
  39480. /** @hidden */
  39481. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39482. var scene = mesh.getScene();
  39483. // Geometry
  39484. var geometryId = parsedGeometry.geometryId;
  39485. if (geometryId) {
  39486. var geometry = scene.getGeometryByID(geometryId);
  39487. if (geometry) {
  39488. geometry.applyToMesh(mesh);
  39489. }
  39490. }
  39491. else if (parsedGeometry instanceof ArrayBuffer) {
  39492. var binaryInfo = mesh._binaryInfo;
  39493. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39494. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39496. }
  39497. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39498. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39500. }
  39501. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39502. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39504. }
  39505. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39506. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39508. }
  39509. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39510. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39512. }
  39513. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39514. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39515. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39516. }
  39517. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39518. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39520. }
  39521. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39522. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39524. }
  39525. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39526. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39527. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39528. }
  39529. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39530. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39531. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39532. }
  39533. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39534. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39535. var floatIndices = [];
  39536. for (var i = 0; i < matricesIndicesData.length; i++) {
  39537. var index = matricesIndicesData[i];
  39538. floatIndices.push(index & 0x000000FF);
  39539. floatIndices.push((index & 0x0000FF00) >> 8);
  39540. floatIndices.push((index & 0x00FF0000) >> 16);
  39541. floatIndices.push(index >> 24);
  39542. }
  39543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39544. }
  39545. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39546. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39548. }
  39549. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39550. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39551. mesh.setIndices(indicesData, null);
  39552. }
  39553. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39554. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39555. mesh.subMeshes = [];
  39556. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39557. var materialIndex = subMeshesData[(i * 5) + 0];
  39558. var verticesStart = subMeshesData[(i * 5) + 1];
  39559. var verticesCount = subMeshesData[(i * 5) + 2];
  39560. var indexStart = subMeshesData[(i * 5) + 3];
  39561. var indexCount = subMeshesData[(i * 5) + 4];
  39562. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39563. }
  39564. }
  39565. }
  39566. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39568. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39569. if (parsedGeometry.tangents) {
  39570. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39571. }
  39572. if (parsedGeometry.uvs) {
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39574. }
  39575. if (parsedGeometry.uvs2) {
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39577. }
  39578. if (parsedGeometry.uvs3) {
  39579. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39580. }
  39581. if (parsedGeometry.uvs4) {
  39582. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39583. }
  39584. if (parsedGeometry.uvs5) {
  39585. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39586. }
  39587. if (parsedGeometry.uvs6) {
  39588. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39589. }
  39590. if (parsedGeometry.colors) {
  39591. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39592. }
  39593. if (parsedGeometry.matricesIndices) {
  39594. if (!parsedGeometry.matricesIndices._isExpanded) {
  39595. var floatIndices = [];
  39596. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39597. var matricesIndex = parsedGeometry.matricesIndices[i];
  39598. floatIndices.push(matricesIndex & 0x000000FF);
  39599. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39600. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39601. floatIndices.push(matricesIndex >> 24);
  39602. }
  39603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39604. }
  39605. else {
  39606. delete parsedGeometry.matricesIndices._isExpanded;
  39607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39608. }
  39609. }
  39610. if (parsedGeometry.matricesIndicesExtra) {
  39611. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39612. var floatIndices = [];
  39613. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39614. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39615. floatIndices.push(matricesIndex & 0x000000FF);
  39616. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39617. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39618. floatIndices.push(matricesIndex >> 24);
  39619. }
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39621. }
  39622. else {
  39623. delete parsedGeometry.matricesIndices._isExpanded;
  39624. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39625. }
  39626. }
  39627. if (parsedGeometry.matricesWeights) {
  39628. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39630. }
  39631. if (parsedGeometry.matricesWeightsExtra) {
  39632. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39633. }
  39634. mesh.setIndices(parsedGeometry.indices, null);
  39635. }
  39636. // SubMeshes
  39637. if (parsedGeometry.subMeshes) {
  39638. mesh.subMeshes = [];
  39639. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39640. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39641. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39642. }
  39643. }
  39644. // Flat shading
  39645. if (mesh._shouldGenerateFlatShading) {
  39646. mesh.convertToFlatShadedMesh();
  39647. delete mesh._shouldGenerateFlatShading;
  39648. }
  39649. // Update
  39650. mesh.computeWorldMatrix(true);
  39651. // Octree
  39652. var sceneOctree = scene.selectionOctree;
  39653. if (sceneOctree !== undefined && sceneOctree !== null) {
  39654. sceneOctree.addMesh(mesh);
  39655. }
  39656. };
  39657. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39658. var epsilon = 1e-3;
  39659. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39660. return;
  39661. }
  39662. var noInfluenceBoneIndex = 0.0;
  39663. if (parsedGeometry.skeletonId > -1) {
  39664. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39665. if (!skeleton) {
  39666. return;
  39667. }
  39668. noInfluenceBoneIndex = skeleton.bones.length;
  39669. }
  39670. else {
  39671. return;
  39672. }
  39673. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39674. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39675. var matricesWeights = parsedGeometry.matricesWeights;
  39676. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39677. var influencers = parsedGeometry.numBoneInfluencer;
  39678. var size = matricesWeights.length;
  39679. for (var i = 0; i < size; i += 4) {
  39680. var weight = 0.0;
  39681. var firstZeroWeight = -1;
  39682. for (var j = 0; j < 4; j++) {
  39683. var w = matricesWeights[i + j];
  39684. weight += w;
  39685. if (w < epsilon && firstZeroWeight < 0) {
  39686. firstZeroWeight = j;
  39687. }
  39688. }
  39689. if (matricesWeightsExtra) {
  39690. for (var j = 0; j < 4; j++) {
  39691. var w = matricesWeightsExtra[i + j];
  39692. weight += w;
  39693. if (w < epsilon && firstZeroWeight < 0) {
  39694. firstZeroWeight = j + 4;
  39695. }
  39696. }
  39697. }
  39698. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39699. firstZeroWeight = influencers - 1;
  39700. }
  39701. if (weight > epsilon) {
  39702. var mweight = 1.0 / weight;
  39703. for (var j = 0; j < 4; j++) {
  39704. matricesWeights[i + j] *= mweight;
  39705. }
  39706. if (matricesWeightsExtra) {
  39707. for (var j = 0; j < 4; j++) {
  39708. matricesWeightsExtra[i + j] *= mweight;
  39709. }
  39710. }
  39711. }
  39712. else {
  39713. if (firstZeroWeight >= 4) {
  39714. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39715. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39716. }
  39717. else {
  39718. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39719. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39720. }
  39721. }
  39722. }
  39723. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39724. if (parsedGeometry.matricesWeightsExtra) {
  39725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39726. }
  39727. };
  39728. /**
  39729. * Create a new geometry from persisted data (Using .babylon file format)
  39730. * @param parsedVertexData defines the persisted data
  39731. * @param scene defines the hosting scene
  39732. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39733. * @returns the new geometry object
  39734. */
  39735. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39736. if (scene.getGeometryByID(parsedVertexData.id)) {
  39737. return null; // null since geometry could be something else than a box...
  39738. }
  39739. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39740. if (BABYLON.Tags) {
  39741. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39742. }
  39743. if (parsedVertexData.delayLoadingFile) {
  39744. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39745. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39746. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39747. geometry._delayInfo = [];
  39748. if (parsedVertexData.hasUVs) {
  39749. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39750. }
  39751. if (parsedVertexData.hasUVs2) {
  39752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39753. }
  39754. if (parsedVertexData.hasUVs3) {
  39755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39756. }
  39757. if (parsedVertexData.hasUVs4) {
  39758. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39759. }
  39760. if (parsedVertexData.hasUVs5) {
  39761. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39762. }
  39763. if (parsedVertexData.hasUVs6) {
  39764. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39765. }
  39766. if (parsedVertexData.hasColors) {
  39767. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39768. }
  39769. if (parsedVertexData.hasMatricesIndices) {
  39770. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39771. }
  39772. if (parsedVertexData.hasMatricesWeights) {
  39773. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39774. }
  39775. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39776. }
  39777. else {
  39778. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39779. }
  39780. scene.pushGeometry(geometry, true);
  39781. return geometry;
  39782. };
  39783. return Geometry;
  39784. }());
  39785. BABYLON.Geometry = Geometry;
  39786. // Primitives
  39787. /// Abstract class
  39788. /**
  39789. * Abstract class used to provide common services for all typed geometries
  39790. * @hidden
  39791. */
  39792. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39793. __extends(_PrimitiveGeometry, _super);
  39794. /**
  39795. * Creates a new typed geometry
  39796. * @param id defines the unique ID of the geometry
  39797. * @param scene defines the hosting scene
  39798. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39799. * @param mesh defines the hosting mesh (can be null)
  39800. */
  39801. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39802. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39803. if (mesh === void 0) { mesh = null; }
  39804. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39805. _this._canBeRegenerated = _canBeRegenerated;
  39806. _this._beingRegenerated = true;
  39807. _this.regenerate();
  39808. _this._beingRegenerated = false;
  39809. return _this;
  39810. }
  39811. /**
  39812. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39813. * @returns true if the geometry can be regenerated
  39814. */
  39815. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39816. return this._canBeRegenerated;
  39817. };
  39818. /**
  39819. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39820. */
  39821. _PrimitiveGeometry.prototype.regenerate = function () {
  39822. if (!this._canBeRegenerated) {
  39823. return;
  39824. }
  39825. this._beingRegenerated = true;
  39826. this.setAllVerticesData(this._regenerateVertexData(), false);
  39827. this._beingRegenerated = false;
  39828. };
  39829. /**
  39830. * Clone the geometry
  39831. * @param id defines the unique ID of the new geometry
  39832. * @returns the new geometry
  39833. */
  39834. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39835. return _super.prototype.copy.call(this, id);
  39836. };
  39837. // overrides
  39838. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39839. if (!this._beingRegenerated) {
  39840. return;
  39841. }
  39842. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39843. };
  39844. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39845. if (!this._beingRegenerated) {
  39846. return;
  39847. }
  39848. _super.prototype.setVerticesData.call(this, kind, data, false);
  39849. };
  39850. // to override
  39851. /** @hidden */
  39852. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39853. throw new Error("Abstract method");
  39854. };
  39855. _PrimitiveGeometry.prototype.copy = function (id) {
  39856. throw new Error("Must be overriden in sub-classes.");
  39857. };
  39858. _PrimitiveGeometry.prototype.serialize = function () {
  39859. var serializationObject = _super.prototype.serialize.call(this);
  39860. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39861. return serializationObject;
  39862. };
  39863. return _PrimitiveGeometry;
  39864. }(Geometry));
  39865. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39866. /**
  39867. * Creates a ribbon geometry
  39868. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39869. */
  39870. var RibbonGeometry = /** @class */ (function (_super) {
  39871. __extends(RibbonGeometry, _super);
  39872. /**
  39873. * Creates a ribbon geometry
  39874. * @param id defines the unique ID of the geometry
  39875. * @param scene defines the hosting scene
  39876. * @param pathArray defines the array of paths to use
  39877. * @param closeArray defines if the last path and the first path must be joined
  39878. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39879. * @param offset defines the offset between points
  39880. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39881. * @param mesh defines the hosting mesh (can be null)
  39882. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39883. */
  39884. function RibbonGeometry(id, scene,
  39885. /**
  39886. * Defines the array of paths to use
  39887. */
  39888. pathArray,
  39889. /**
  39890. * Defines if the last and first points of each path in your pathArray must be joined
  39891. */
  39892. closeArray,
  39893. /**
  39894. * Defines if the last and first points of each path in your pathArray must be joined
  39895. */
  39896. closePath,
  39897. /**
  39898. * Defines the offset between points
  39899. */
  39900. offset, canBeRegenerated, mesh,
  39901. /**
  39902. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39903. */
  39904. side) {
  39905. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39906. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39907. _this.pathArray = pathArray;
  39908. _this.closeArray = closeArray;
  39909. _this.closePath = closePath;
  39910. _this.offset = offset;
  39911. _this.side = side;
  39912. return _this;
  39913. }
  39914. /** @hidden */
  39915. RibbonGeometry.prototype._regenerateVertexData = function () {
  39916. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39917. };
  39918. RibbonGeometry.prototype.copy = function (id) {
  39919. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39920. };
  39921. return RibbonGeometry;
  39922. }(_PrimitiveGeometry));
  39923. BABYLON.RibbonGeometry = RibbonGeometry;
  39924. /**
  39925. * Creates a box geometry
  39926. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39927. */
  39928. var BoxGeometry = /** @class */ (function (_super) {
  39929. __extends(BoxGeometry, _super);
  39930. /**
  39931. * Creates a box geometry
  39932. * @param id defines the unique ID of the geometry
  39933. * @param scene defines the hosting scene
  39934. * @param size defines the zise of the box (width, height and depth are the same)
  39935. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39936. * @param mesh defines the hosting mesh (can be null)
  39937. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39938. */
  39939. function BoxGeometry(id, scene,
  39940. /**
  39941. * Defines the zise of the box (width, height and depth are the same)
  39942. */
  39943. size, canBeRegenerated, mesh,
  39944. /**
  39945. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39946. */
  39947. side) {
  39948. if (mesh === void 0) { mesh = null; }
  39949. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39950. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39951. _this.size = size;
  39952. _this.side = side;
  39953. return _this;
  39954. }
  39955. BoxGeometry.prototype._regenerateVertexData = function () {
  39956. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39957. };
  39958. BoxGeometry.prototype.copy = function (id) {
  39959. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39960. };
  39961. BoxGeometry.prototype.serialize = function () {
  39962. var serializationObject = _super.prototype.serialize.call(this);
  39963. serializationObject.size = this.size;
  39964. return serializationObject;
  39965. };
  39966. BoxGeometry.Parse = function (parsedBox, scene) {
  39967. if (scene.getGeometryByID(parsedBox.id)) {
  39968. return null; // null since geometry could be something else than a box...
  39969. }
  39970. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39971. if (BABYLON.Tags) {
  39972. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39973. }
  39974. scene.pushGeometry(box, true);
  39975. return box;
  39976. };
  39977. return BoxGeometry;
  39978. }(_PrimitiveGeometry));
  39979. BABYLON.BoxGeometry = BoxGeometry;
  39980. /**
  39981. * Creates a sphere geometry
  39982. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39983. */
  39984. var SphereGeometry = /** @class */ (function (_super) {
  39985. __extends(SphereGeometry, _super);
  39986. /**
  39987. * Create a new sphere geometry
  39988. * @param id defines the unique ID of the geometry
  39989. * @param scene defines the hosting scene
  39990. * @param segments defines the number of segments to use to create the sphere
  39991. * @param diameter defines the diameter of the sphere
  39992. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39993. * @param mesh defines the hosting mesh (can be null)
  39994. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39995. */
  39996. function SphereGeometry(id, scene,
  39997. /**
  39998. * Defines the number of segments to use to create the sphere
  39999. */
  40000. segments,
  40001. /**
  40002. * Defines the diameter of the sphere
  40003. */
  40004. diameter, canBeRegenerated, mesh,
  40005. /**
  40006. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40007. */
  40008. side) {
  40009. if (mesh === void 0) { mesh = null; }
  40010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40011. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40012. _this.segments = segments;
  40013. _this.diameter = diameter;
  40014. _this.side = side;
  40015. return _this;
  40016. }
  40017. SphereGeometry.prototype._regenerateVertexData = function () {
  40018. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40019. };
  40020. SphereGeometry.prototype.copy = function (id) {
  40021. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40022. };
  40023. SphereGeometry.prototype.serialize = function () {
  40024. var serializationObject = _super.prototype.serialize.call(this);
  40025. serializationObject.segments = this.segments;
  40026. serializationObject.diameter = this.diameter;
  40027. return serializationObject;
  40028. };
  40029. SphereGeometry.Parse = function (parsedSphere, scene) {
  40030. if (scene.getGeometryByID(parsedSphere.id)) {
  40031. return null; // null since geometry could be something else than a sphere...
  40032. }
  40033. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40034. if (BABYLON.Tags) {
  40035. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40036. }
  40037. scene.pushGeometry(sphere, true);
  40038. return sphere;
  40039. };
  40040. return SphereGeometry;
  40041. }(_PrimitiveGeometry));
  40042. BABYLON.SphereGeometry = SphereGeometry;
  40043. /**
  40044. * Creates a disc geometry
  40045. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40046. */
  40047. var DiscGeometry = /** @class */ (function (_super) {
  40048. __extends(DiscGeometry, _super);
  40049. /**
  40050. * Creates a new disc geometry
  40051. * @param id defines the unique ID of the geometry
  40052. * @param scene defines the hosting scene
  40053. * @param radius defines the radius of the disc
  40054. * @param tessellation defines the tesselation factor to apply to the disc
  40055. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40056. * @param mesh defines the hosting mesh (can be null)
  40057. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40058. */
  40059. function DiscGeometry(id, scene,
  40060. /**
  40061. * Defines the radius of the disc
  40062. */
  40063. radius,
  40064. /**
  40065. * Defines the tesselation factor to apply to the disc
  40066. */
  40067. tessellation, canBeRegenerated, mesh,
  40068. /**
  40069. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40070. */
  40071. side) {
  40072. if (mesh === void 0) { mesh = null; }
  40073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40075. _this.radius = radius;
  40076. _this.tessellation = tessellation;
  40077. _this.side = side;
  40078. return _this;
  40079. }
  40080. DiscGeometry.prototype._regenerateVertexData = function () {
  40081. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40082. };
  40083. DiscGeometry.prototype.copy = function (id) {
  40084. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40085. };
  40086. return DiscGeometry;
  40087. }(_PrimitiveGeometry));
  40088. BABYLON.DiscGeometry = DiscGeometry;
  40089. /**
  40090. * Creates a new cylinder geometry
  40091. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40092. */
  40093. var CylinderGeometry = /** @class */ (function (_super) {
  40094. __extends(CylinderGeometry, _super);
  40095. /**
  40096. * Creates a new cylinder geometry
  40097. * @param id defines the unique ID of the geometry
  40098. * @param scene defines the hosting scene
  40099. * @param height defines the height of the cylinder
  40100. * @param diameterTop defines the diameter of the cylinder's top cap
  40101. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40102. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40103. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40104. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40105. * @param mesh defines the hosting mesh (can be null)
  40106. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40107. */
  40108. function CylinderGeometry(id, scene,
  40109. /**
  40110. * Defines the height of the cylinder
  40111. */
  40112. height,
  40113. /**
  40114. * Defines the diameter of the cylinder's top cap
  40115. */
  40116. diameterTop,
  40117. /**
  40118. * Defines the diameter of the cylinder's bottom cap
  40119. */
  40120. diameterBottom,
  40121. /**
  40122. * Defines the tessellation factor to apply to the cylinder
  40123. */
  40124. tessellation,
  40125. /**
  40126. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40127. */
  40128. subdivisions, canBeRegenerated, mesh,
  40129. /**
  40130. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40131. */
  40132. side) {
  40133. if (subdivisions === void 0) { subdivisions = 1; }
  40134. if (mesh === void 0) { mesh = null; }
  40135. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40137. _this.height = height;
  40138. _this.diameterTop = diameterTop;
  40139. _this.diameterBottom = diameterBottom;
  40140. _this.tessellation = tessellation;
  40141. _this.subdivisions = subdivisions;
  40142. _this.side = side;
  40143. return _this;
  40144. }
  40145. CylinderGeometry.prototype._regenerateVertexData = function () {
  40146. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40147. };
  40148. CylinderGeometry.prototype.copy = function (id) {
  40149. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40150. };
  40151. CylinderGeometry.prototype.serialize = function () {
  40152. var serializationObject = _super.prototype.serialize.call(this);
  40153. serializationObject.height = this.height;
  40154. serializationObject.diameterTop = this.diameterTop;
  40155. serializationObject.diameterBottom = this.diameterBottom;
  40156. serializationObject.tessellation = this.tessellation;
  40157. return serializationObject;
  40158. };
  40159. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40160. if (scene.getGeometryByID(parsedCylinder.id)) {
  40161. return null; // null since geometry could be something else than a cylinder...
  40162. }
  40163. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40164. if (BABYLON.Tags) {
  40165. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40166. }
  40167. scene.pushGeometry(cylinder, true);
  40168. return cylinder;
  40169. };
  40170. return CylinderGeometry;
  40171. }(_PrimitiveGeometry));
  40172. BABYLON.CylinderGeometry = CylinderGeometry;
  40173. /**
  40174. * Creates a new torus geometry
  40175. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40176. */
  40177. var TorusGeometry = /** @class */ (function (_super) {
  40178. __extends(TorusGeometry, _super);
  40179. /**
  40180. * Creates a new torus geometry
  40181. * @param id defines the unique ID of the geometry
  40182. * @param scene defines the hosting scene
  40183. * @param diameter defines the diameter of the torus
  40184. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40185. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40186. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40187. * @param mesh defines the hosting mesh (can be null)
  40188. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40189. */
  40190. function TorusGeometry(id, scene,
  40191. /**
  40192. * Defines the diameter of the torus
  40193. */
  40194. diameter,
  40195. /**
  40196. * Defines the thickness of the torus (ie. internal diameter)
  40197. */
  40198. thickness,
  40199. /**
  40200. * Defines the tesselation factor to apply to the torus
  40201. */
  40202. tessellation, canBeRegenerated, mesh,
  40203. /**
  40204. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40205. */
  40206. side) {
  40207. if (mesh === void 0) { mesh = null; }
  40208. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40209. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40210. _this.diameter = diameter;
  40211. _this.thickness = thickness;
  40212. _this.tessellation = tessellation;
  40213. _this.side = side;
  40214. return _this;
  40215. }
  40216. TorusGeometry.prototype._regenerateVertexData = function () {
  40217. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40218. };
  40219. TorusGeometry.prototype.copy = function (id) {
  40220. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40221. };
  40222. TorusGeometry.prototype.serialize = function () {
  40223. var serializationObject = _super.prototype.serialize.call(this);
  40224. serializationObject.diameter = this.diameter;
  40225. serializationObject.thickness = this.thickness;
  40226. serializationObject.tessellation = this.tessellation;
  40227. return serializationObject;
  40228. };
  40229. TorusGeometry.Parse = function (parsedTorus, scene) {
  40230. if (scene.getGeometryByID(parsedTorus.id)) {
  40231. return null; // null since geometry could be something else than a torus...
  40232. }
  40233. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40234. if (BABYLON.Tags) {
  40235. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40236. }
  40237. scene.pushGeometry(torus, true);
  40238. return torus;
  40239. };
  40240. return TorusGeometry;
  40241. }(_PrimitiveGeometry));
  40242. BABYLON.TorusGeometry = TorusGeometry;
  40243. /**
  40244. * Creates a new ground geometry
  40245. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40246. */
  40247. var GroundGeometry = /** @class */ (function (_super) {
  40248. __extends(GroundGeometry, _super);
  40249. /**
  40250. * Creates a new ground geometry
  40251. * @param id defines the unique ID of the geometry
  40252. * @param scene defines the hosting scene
  40253. * @param width defines the width of the ground
  40254. * @param height defines the height of the ground
  40255. * @param subdivisions defines the subdivisions to apply to the ground
  40256. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40257. * @param mesh defines the hosting mesh (can be null)
  40258. */
  40259. function GroundGeometry(id, scene,
  40260. /**
  40261. * Defines the width of the ground
  40262. */
  40263. width,
  40264. /**
  40265. * Defines the height of the ground
  40266. */
  40267. height,
  40268. /**
  40269. * Defines the subdivisions to apply to the ground
  40270. */
  40271. subdivisions, canBeRegenerated, mesh) {
  40272. if (mesh === void 0) { mesh = null; }
  40273. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40274. _this.width = width;
  40275. _this.height = height;
  40276. _this.subdivisions = subdivisions;
  40277. return _this;
  40278. }
  40279. GroundGeometry.prototype._regenerateVertexData = function () {
  40280. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40281. };
  40282. GroundGeometry.prototype.copy = function (id) {
  40283. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40284. };
  40285. GroundGeometry.prototype.serialize = function () {
  40286. var serializationObject = _super.prototype.serialize.call(this);
  40287. serializationObject.width = this.width;
  40288. serializationObject.height = this.height;
  40289. serializationObject.subdivisions = this.subdivisions;
  40290. return serializationObject;
  40291. };
  40292. GroundGeometry.Parse = function (parsedGround, scene) {
  40293. if (scene.getGeometryByID(parsedGround.id)) {
  40294. return null; // null since geometry could be something else than a ground...
  40295. }
  40296. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40297. if (BABYLON.Tags) {
  40298. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40299. }
  40300. scene.pushGeometry(ground, true);
  40301. return ground;
  40302. };
  40303. return GroundGeometry;
  40304. }(_PrimitiveGeometry));
  40305. BABYLON.GroundGeometry = GroundGeometry;
  40306. /**
  40307. * Creates a tiled ground geometry
  40308. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40309. */
  40310. var TiledGroundGeometry = /** @class */ (function (_super) {
  40311. __extends(TiledGroundGeometry, _super);
  40312. /**
  40313. * Creates a tiled ground geometry
  40314. * @param id defines the unique ID of the geometry
  40315. * @param scene defines the hosting scene
  40316. * @param xmin defines the minimum value on X axis
  40317. * @param zmin defines the minimum value on Z axis
  40318. * @param xmax defines the maximum value on X axis
  40319. * @param zmax defines the maximum value on Z axis
  40320. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40321. * @param precision defines the precision to use when computing the tiles
  40322. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40323. * @param mesh defines the hosting mesh (can be null)
  40324. */
  40325. function TiledGroundGeometry(id, scene,
  40326. /**
  40327. * Defines the minimum value on X axis
  40328. */
  40329. xmin,
  40330. /**
  40331. * Defines the minimum value on Z axis
  40332. */
  40333. zmin,
  40334. /**
  40335. * Defines the maximum value on X axis
  40336. */
  40337. xmax,
  40338. /**
  40339. * Defines the maximum value on Z axis
  40340. */
  40341. zmax,
  40342. /**
  40343. * Defines the subdivisions to apply to the ground
  40344. */
  40345. subdivisions,
  40346. /**
  40347. * Defines the precision to use when computing the tiles
  40348. */
  40349. precision, canBeRegenerated, mesh) {
  40350. if (mesh === void 0) { mesh = null; }
  40351. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40352. _this.xmin = xmin;
  40353. _this.zmin = zmin;
  40354. _this.xmax = xmax;
  40355. _this.zmax = zmax;
  40356. _this.subdivisions = subdivisions;
  40357. _this.precision = precision;
  40358. return _this;
  40359. }
  40360. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40361. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40362. };
  40363. TiledGroundGeometry.prototype.copy = function (id) {
  40364. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40365. };
  40366. return TiledGroundGeometry;
  40367. }(_PrimitiveGeometry));
  40368. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40369. /**
  40370. * Creates a plane geometry
  40371. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40372. */
  40373. var PlaneGeometry = /** @class */ (function (_super) {
  40374. __extends(PlaneGeometry, _super);
  40375. /**
  40376. * Creates a plane geometry
  40377. * @param id defines the unique ID of the geometry
  40378. * @param scene defines the hosting scene
  40379. * @param size defines the size of the plane (width === height)
  40380. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40381. * @param mesh defines the hosting mesh (can be null)
  40382. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40383. */
  40384. function PlaneGeometry(id, scene,
  40385. /**
  40386. * Defines the size of the plane (width === height)
  40387. */
  40388. size, canBeRegenerated, mesh,
  40389. /**
  40390. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40391. */
  40392. side) {
  40393. if (mesh === void 0) { mesh = null; }
  40394. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40395. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40396. _this.size = size;
  40397. _this.side = side;
  40398. return _this;
  40399. }
  40400. PlaneGeometry.prototype._regenerateVertexData = function () {
  40401. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40402. };
  40403. PlaneGeometry.prototype.copy = function (id) {
  40404. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40405. };
  40406. PlaneGeometry.prototype.serialize = function () {
  40407. var serializationObject = _super.prototype.serialize.call(this);
  40408. serializationObject.size = this.size;
  40409. return serializationObject;
  40410. };
  40411. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40412. if (scene.getGeometryByID(parsedPlane.id)) {
  40413. return null; // null since geometry could be something else than a ground...
  40414. }
  40415. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40416. if (BABYLON.Tags) {
  40417. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40418. }
  40419. scene.pushGeometry(plane, true);
  40420. return plane;
  40421. };
  40422. return PlaneGeometry;
  40423. }(_PrimitiveGeometry));
  40424. BABYLON.PlaneGeometry = PlaneGeometry;
  40425. /**
  40426. * Creates a torus knot geometry
  40427. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40428. */
  40429. var TorusKnotGeometry = /** @class */ (function (_super) {
  40430. __extends(TorusKnotGeometry, _super);
  40431. /**
  40432. * Creates a torus knot geometry
  40433. * @param id defines the unique ID of the geometry
  40434. * @param scene defines the hosting scene
  40435. * @param radius defines the radius of the torus knot
  40436. * @param tube defines the thickness of the torus knot tube
  40437. * @param radialSegments defines the number of radial segments
  40438. * @param tubularSegments defines the number of tubular segments
  40439. * @param p defines the first number of windings
  40440. * @param q defines the second number of windings
  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. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40444. */
  40445. function TorusKnotGeometry(id, scene,
  40446. /**
  40447. * Defines the radius of the torus knot
  40448. */
  40449. radius,
  40450. /**
  40451. * Defines the thickness of the torus knot tube
  40452. */
  40453. tube,
  40454. /**
  40455. * Defines the number of radial segments
  40456. */
  40457. radialSegments,
  40458. /**
  40459. * Defines the number of tubular segments
  40460. */
  40461. tubularSegments,
  40462. /**
  40463. * Defines the first number of windings
  40464. */
  40465. p,
  40466. /**
  40467. * Defines the second number of windings
  40468. */
  40469. q, canBeRegenerated, mesh,
  40470. /**
  40471. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40472. */
  40473. side) {
  40474. if (mesh === void 0) { mesh = null; }
  40475. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40476. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40477. _this.radius = radius;
  40478. _this.tube = tube;
  40479. _this.radialSegments = radialSegments;
  40480. _this.tubularSegments = tubularSegments;
  40481. _this.p = p;
  40482. _this.q = q;
  40483. _this.side = side;
  40484. return _this;
  40485. }
  40486. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40487. 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 });
  40488. };
  40489. TorusKnotGeometry.prototype.copy = function (id) {
  40490. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40491. };
  40492. TorusKnotGeometry.prototype.serialize = function () {
  40493. var serializationObject = _super.prototype.serialize.call(this);
  40494. serializationObject.radius = this.radius;
  40495. serializationObject.tube = this.tube;
  40496. serializationObject.radialSegments = this.radialSegments;
  40497. serializationObject.tubularSegments = this.tubularSegments;
  40498. serializationObject.p = this.p;
  40499. serializationObject.q = this.q;
  40500. return serializationObject;
  40501. };
  40502. ;
  40503. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40504. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40505. return null; // null since geometry could be something else than a ground...
  40506. }
  40507. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40508. if (BABYLON.Tags) {
  40509. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40510. }
  40511. scene.pushGeometry(torusKnot, true);
  40512. return torusKnot;
  40513. };
  40514. return TorusKnotGeometry;
  40515. }(_PrimitiveGeometry));
  40516. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40517. //}
  40518. })(BABYLON || (BABYLON = {}));
  40519. //# sourceMappingURL=babylon.geometry.js.map
  40520. var BABYLON;
  40521. (function (BABYLON) {
  40522. /**
  40523. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40524. */
  40525. var PerformanceMonitor = /** @class */ (function () {
  40526. /**
  40527. * constructor
  40528. * @param frameSampleSize The number of samples required to saturate the sliding window
  40529. */
  40530. function PerformanceMonitor(frameSampleSize) {
  40531. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40532. this._enabled = true;
  40533. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40534. }
  40535. /**
  40536. * Samples current frame
  40537. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40538. */
  40539. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40540. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40541. if (!this._enabled)
  40542. return;
  40543. if (this._lastFrameTimeMs != null) {
  40544. var dt = timeMs - this._lastFrameTimeMs;
  40545. this._rollingFrameTime.add(dt);
  40546. }
  40547. this._lastFrameTimeMs = timeMs;
  40548. };
  40549. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40550. /**
  40551. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40552. * @return Average frame time in milliseconds
  40553. */
  40554. get: function () {
  40555. return this._rollingFrameTime.average;
  40556. },
  40557. enumerable: true,
  40558. configurable: true
  40559. });
  40560. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40561. /**
  40562. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40563. * @return Frame time variance in milliseconds squared
  40564. */
  40565. get: function () {
  40566. return this._rollingFrameTime.variance;
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40572. /**
  40573. * Returns the frame time of the most recent frame
  40574. * @return Frame time in milliseconds
  40575. */
  40576. get: function () {
  40577. return this._rollingFrameTime.history(0);
  40578. },
  40579. enumerable: true,
  40580. configurable: true
  40581. });
  40582. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40583. /**
  40584. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40585. * @return Framerate in frames per second
  40586. */
  40587. get: function () {
  40588. return 1000.0 / this._rollingFrameTime.average;
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40594. /**
  40595. * Returns the average framerate in frames per second using the most recent frame time
  40596. * @return Framerate in frames per second
  40597. */
  40598. get: function () {
  40599. var history = this._rollingFrameTime.history(0);
  40600. if (history === 0) {
  40601. return 0;
  40602. }
  40603. return 1000.0 / history;
  40604. },
  40605. enumerable: true,
  40606. configurable: true
  40607. });
  40608. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40609. /**
  40610. * Returns true if enough samples have been taken to completely fill the sliding window
  40611. * @return true if saturated
  40612. */
  40613. get: function () {
  40614. return this._rollingFrameTime.isSaturated();
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. /**
  40620. * Enables contributions to the sliding window sample set
  40621. */
  40622. PerformanceMonitor.prototype.enable = function () {
  40623. this._enabled = true;
  40624. };
  40625. /**
  40626. * Disables contributions to the sliding window sample set
  40627. * Samples will not be interpolated over the disabled period
  40628. */
  40629. PerformanceMonitor.prototype.disable = function () {
  40630. this._enabled = false;
  40631. //clear last sample to avoid interpolating over the disabled period when next enabled
  40632. this._lastFrameTimeMs = null;
  40633. };
  40634. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40635. /**
  40636. * Returns true if sampling is enabled
  40637. * @return true if enabled
  40638. */
  40639. get: function () {
  40640. return this._enabled;
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. /**
  40646. * Resets performance monitor
  40647. */
  40648. PerformanceMonitor.prototype.reset = function () {
  40649. //clear last sample to avoid interpolating over the disabled period when next enabled
  40650. this._lastFrameTimeMs = null;
  40651. //wipe record
  40652. this._rollingFrameTime.reset();
  40653. };
  40654. return PerformanceMonitor;
  40655. }());
  40656. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40657. /**
  40658. * RollingAverage
  40659. *
  40660. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40661. */
  40662. var RollingAverage = /** @class */ (function () {
  40663. /**
  40664. * constructor
  40665. * @param length The number of samples required to saturate the sliding window
  40666. */
  40667. function RollingAverage(length) {
  40668. this._samples = new Array(length);
  40669. this.reset();
  40670. }
  40671. /**
  40672. * Adds a sample to the sample set
  40673. * @param v The sample value
  40674. */
  40675. RollingAverage.prototype.add = function (v) {
  40676. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40677. var delta;
  40678. //we need to check if we've already wrapped round
  40679. if (this.isSaturated()) {
  40680. //remove bottom of stack from mean
  40681. var bottomValue = this._samples[this._pos];
  40682. delta = bottomValue - this.average;
  40683. this.average -= delta / (this._sampleCount - 1);
  40684. this._m2 -= delta * (bottomValue - this.average);
  40685. }
  40686. else {
  40687. this._sampleCount++;
  40688. }
  40689. //add new value to mean
  40690. delta = v - this.average;
  40691. this.average += delta / (this._sampleCount);
  40692. this._m2 += delta * (v - this.average);
  40693. //set the new variance
  40694. this.variance = this._m2 / (this._sampleCount - 1);
  40695. this._samples[this._pos] = v;
  40696. this._pos++;
  40697. this._pos %= this._samples.length; //positive wrap around
  40698. };
  40699. /**
  40700. * Returns previously added values or null if outside of history or outside the sliding window domain
  40701. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40702. * @return Value previously recorded with add() or null if outside of range
  40703. */
  40704. RollingAverage.prototype.history = function (i) {
  40705. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40706. return 0;
  40707. }
  40708. var i0 = this._wrapPosition(this._pos - 1.0);
  40709. return this._samples[this._wrapPosition(i0 - i)];
  40710. };
  40711. /**
  40712. * Returns true if enough samples have been taken to completely fill the sliding window
  40713. * @return true if sample-set saturated
  40714. */
  40715. RollingAverage.prototype.isSaturated = function () {
  40716. return this._sampleCount >= this._samples.length;
  40717. };
  40718. /**
  40719. * Resets the rolling average (equivalent to 0 samples taken so far)
  40720. */
  40721. RollingAverage.prototype.reset = function () {
  40722. this.average = 0;
  40723. this.variance = 0;
  40724. this._sampleCount = 0;
  40725. this._pos = 0;
  40726. this._m2 = 0;
  40727. };
  40728. /**
  40729. * Wraps a value around the sample range boundaries
  40730. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40731. * @return Wrapped position in sample range
  40732. */
  40733. RollingAverage.prototype._wrapPosition = function (i) {
  40734. var max = this._samples.length;
  40735. return ((i % max) + max) % max;
  40736. };
  40737. return RollingAverage;
  40738. }());
  40739. BABYLON.RollingAverage = RollingAverage;
  40740. })(BABYLON || (BABYLON = {}));
  40741. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40742. var BABYLON;
  40743. (function (BABYLON) {
  40744. /**
  40745. * "Static Class" containing the most commonly used helper while dealing with material for
  40746. * rendering purpose.
  40747. *
  40748. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40749. *
  40750. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40751. */
  40752. var MaterialHelper = /** @class */ (function () {
  40753. function MaterialHelper() {
  40754. }
  40755. /**
  40756. * Bind the current view position to an effect.
  40757. * @param effect The effect to be bound
  40758. * @param scene The scene the eyes position is used from
  40759. */
  40760. MaterialHelper.BindEyePosition = function (effect, scene) {
  40761. if (scene._forcedViewPosition) {
  40762. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40763. return;
  40764. }
  40765. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40766. };
  40767. /**
  40768. * Helps preparing the defines values about the UVs in used in the effect.
  40769. * UVs are shared as much as we can accross chanels in the shaders.
  40770. * @param texture The texture we are preparing the UVs for
  40771. * @param defines The defines to update
  40772. * @param key The chanel key "diffuse", "specular"... used in the shader
  40773. */
  40774. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40775. defines._needUVs = true;
  40776. defines[key] = true;
  40777. if (texture.getTextureMatrix().isIdentity(true)) {
  40778. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40779. if (texture.coordinatesIndex === 0) {
  40780. defines["MAINUV1"] = true;
  40781. }
  40782. else {
  40783. defines["MAINUV2"] = true;
  40784. }
  40785. }
  40786. else {
  40787. defines[key + "DIRECTUV"] = 0;
  40788. }
  40789. };
  40790. /**
  40791. * Binds a texture matrix value to its corrsponding uniform
  40792. * @param texture The texture to bind the matrix for
  40793. * @param uniformBuffer The uniform buffer receivin the data
  40794. * @param key The chanel key "diffuse", "specular"... used in the shader
  40795. */
  40796. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40797. var matrix = texture.getTextureMatrix();
  40798. if (!matrix.isIdentity(true)) {
  40799. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40800. }
  40801. };
  40802. /**
  40803. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40804. * @param mesh defines the current mesh
  40805. * @param scene defines the current scene
  40806. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40807. * @param pointsCloud defines if point cloud rendering has to be turned on
  40808. * @param fogEnabled defines if fog has to be turned on
  40809. * @param alphaTest defines if alpha testing has to be turned on
  40810. * @param defines defines the current list of defines
  40811. */
  40812. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40813. if (defines._areMiscDirty) {
  40814. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40815. defines["POINTSIZE"] = pointsCloud;
  40816. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40817. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40818. defines["ALPHATEST"] = alphaTest;
  40819. }
  40820. };
  40821. /**
  40822. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40823. * @param scene defines the current scene
  40824. * @param engine defines the current engine
  40825. * @param defines specifies the list of active defines
  40826. * @param useInstances defines if instances have to be turned on
  40827. * @param useClipPlane defines if clip plane have to be turned on
  40828. */
  40829. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40830. if (useClipPlane === void 0) { useClipPlane = null; }
  40831. var changed = false;
  40832. if (useClipPlane == null) {
  40833. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40834. }
  40835. if (defines["CLIPPLANE"] !== useClipPlane) {
  40836. defines["CLIPPLANE"] = useClipPlane;
  40837. changed = true;
  40838. }
  40839. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40840. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40841. changed = true;
  40842. }
  40843. if (defines["INSTANCES"] !== useInstances) {
  40844. defines["INSTANCES"] = useInstances;
  40845. changed = true;
  40846. }
  40847. if (changed) {
  40848. defines.markAsUnprocessed();
  40849. }
  40850. };
  40851. /**
  40852. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40853. * @param mesh The mesh containing the geometry data we will draw
  40854. * @param defines The defines to update
  40855. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40856. * @param useBones Precise whether bones should be used or not (override mesh info)
  40857. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40858. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40859. * @returns false if defines are considered not dirty and have not been checked
  40860. */
  40861. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40862. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40863. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40864. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40865. return false;
  40866. }
  40867. defines._normals = defines._needNormals;
  40868. defines._uvs = defines._needUVs;
  40869. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40870. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40871. defines["TANGENT"] = true;
  40872. }
  40873. if (defines._needUVs) {
  40874. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40875. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40876. }
  40877. else {
  40878. defines["UV1"] = false;
  40879. defines["UV2"] = false;
  40880. }
  40881. if (useVertexColor) {
  40882. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40883. defines["VERTEXCOLOR"] = hasVertexColors;
  40884. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40885. }
  40886. if (useBones) {
  40887. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40888. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40889. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40890. }
  40891. else {
  40892. defines["NUM_BONE_INFLUENCERS"] = 0;
  40893. defines["BonesPerMesh"] = 0;
  40894. }
  40895. }
  40896. if (useMorphTargets) {
  40897. var manager = mesh.morphTargetManager;
  40898. if (manager) {
  40899. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40900. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40901. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40902. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40903. }
  40904. else {
  40905. defines["MORPHTARGETS_TANGENT"] = false;
  40906. defines["MORPHTARGETS_NORMAL"] = false;
  40907. defines["MORPHTARGETS"] = false;
  40908. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40909. }
  40910. }
  40911. return true;
  40912. };
  40913. /**
  40914. * Prepares the defines related to the light information passed in parameter
  40915. * @param scene The scene we are intending to draw
  40916. * @param mesh The mesh the effect is compiling for
  40917. * @param defines The defines to update
  40918. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40919. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40920. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40921. * @returns true if normals will be required for the rest of the effect
  40922. */
  40923. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40924. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40925. if (disableLighting === void 0) { disableLighting = false; }
  40926. if (!defines._areLightsDirty) {
  40927. return defines._needNormals;
  40928. }
  40929. var lightIndex = 0;
  40930. var needNormals = false;
  40931. var needRebuild = false;
  40932. var lightmapMode = false;
  40933. var shadowEnabled = false;
  40934. var specularEnabled = false;
  40935. if (scene.lightsEnabled && !disableLighting) {
  40936. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40937. var light = _a[_i];
  40938. needNormals = true;
  40939. if (defines["LIGHT" + lightIndex] === undefined) {
  40940. needRebuild = true;
  40941. }
  40942. defines["LIGHT" + lightIndex] = true;
  40943. defines["SPOTLIGHT" + lightIndex] = false;
  40944. defines["HEMILIGHT" + lightIndex] = false;
  40945. defines["POINTLIGHT" + lightIndex] = false;
  40946. defines["DIRLIGHT" + lightIndex] = false;
  40947. light.prepareLightSpecificDefines(defines, lightIndex);
  40948. // Specular
  40949. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40950. specularEnabled = true;
  40951. }
  40952. // Shadows
  40953. defines["SHADOW" + lightIndex] = false;
  40954. defines["SHADOWPCF" + lightIndex] = false;
  40955. defines["SHADOWPCSS" + lightIndex] = false;
  40956. defines["SHADOWPOISSON" + lightIndex] = false;
  40957. defines["SHADOWESM" + lightIndex] = false;
  40958. defines["SHADOWCUBE" + lightIndex] = false;
  40959. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40960. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40961. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40962. var shadowGenerator = light.getShadowGenerator();
  40963. if (shadowGenerator) {
  40964. var shadowMap = shadowGenerator.getShadowMap();
  40965. if (shadowMap) {
  40966. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40967. shadowEnabled = true;
  40968. shadowGenerator.prepareDefines(defines, lightIndex);
  40969. }
  40970. }
  40971. }
  40972. }
  40973. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40974. lightmapMode = true;
  40975. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40976. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40977. }
  40978. else {
  40979. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40980. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40981. }
  40982. lightIndex++;
  40983. if (lightIndex === maxSimultaneousLights)
  40984. break;
  40985. }
  40986. }
  40987. defines["SPECULARTERM"] = specularEnabled;
  40988. defines["SHADOWS"] = shadowEnabled;
  40989. // Resetting all other lights if any
  40990. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40991. if (defines["LIGHT" + index] !== undefined) {
  40992. defines["LIGHT" + index] = false;
  40993. defines["HEMILIGHT" + lightIndex] = false;
  40994. defines["POINTLIGHT" + lightIndex] = false;
  40995. defines["DIRLIGHT" + lightIndex] = false;
  40996. defines["SPOTLIGHT" + lightIndex] = false;
  40997. defines["SHADOW" + lightIndex] = false;
  40998. }
  40999. }
  41000. var caps = scene.getEngine().getCaps();
  41001. if (defines["SHADOWFLOAT"] === undefined) {
  41002. needRebuild = true;
  41003. }
  41004. defines["SHADOWFLOAT"] = shadowEnabled &&
  41005. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41006. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41007. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41008. if (needRebuild) {
  41009. defines.rebuild();
  41010. }
  41011. return needNormals;
  41012. };
  41013. /**
  41014. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41015. * that won t be acctive due to defines being turned off.
  41016. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41017. * @param samplersList The samplers list
  41018. * @param defines The defines helping in the list generation
  41019. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41020. */
  41021. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41022. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41023. var uniformsList;
  41024. var uniformBuffersList = null;
  41025. if (uniformsListOrOptions.uniformsNames) {
  41026. var options = uniformsListOrOptions;
  41027. uniformsList = options.uniformsNames;
  41028. uniformBuffersList = options.uniformBuffersNames;
  41029. samplersList = options.samplers;
  41030. defines = options.defines;
  41031. maxSimultaneousLights = options.maxSimultaneousLights;
  41032. }
  41033. else {
  41034. uniformsList = uniformsListOrOptions;
  41035. if (!samplersList) {
  41036. samplersList = [];
  41037. }
  41038. }
  41039. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41040. if (!defines["LIGHT" + lightIndex]) {
  41041. break;
  41042. }
  41043. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41044. if (uniformBuffersList) {
  41045. uniformBuffersList.push("Light" + lightIndex);
  41046. }
  41047. samplersList.push("shadowSampler" + lightIndex);
  41048. samplersList.push("depthSampler" + lightIndex);
  41049. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41050. samplersList.push("projectionLightSampler" + lightIndex);
  41051. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41052. }
  41053. }
  41054. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41055. uniformsList.push("morphTargetInfluences");
  41056. }
  41057. };
  41058. /**
  41059. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41060. * @param defines The defines to update while falling back
  41061. * @param fallbacks The authorized effect fallbacks
  41062. * @param maxSimultaneousLights The maximum number of lights allowed
  41063. * @param rank the current rank of the Effect
  41064. * @returns The newly affected rank
  41065. */
  41066. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41067. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41068. if (rank === void 0) { rank = 0; }
  41069. var lightFallbackRank = 0;
  41070. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41071. if (!defines["LIGHT" + lightIndex]) {
  41072. break;
  41073. }
  41074. if (lightIndex > 0) {
  41075. lightFallbackRank = rank + lightIndex;
  41076. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41077. }
  41078. if (!defines["SHADOWS"]) {
  41079. if (defines["SHADOW" + lightIndex]) {
  41080. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41081. }
  41082. if (defines["SHADOWPCF" + lightIndex]) {
  41083. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41084. }
  41085. if (defines["SHADOWPCSS" + lightIndex]) {
  41086. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41087. }
  41088. if (defines["SHADOWPOISSON" + lightIndex]) {
  41089. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41090. }
  41091. if (defines["SHADOWESM" + lightIndex]) {
  41092. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41093. }
  41094. }
  41095. }
  41096. return lightFallbackRank++;
  41097. };
  41098. /**
  41099. * Prepares the list of attributes required for morph targets according to the effect defines.
  41100. * @param attribs The current list of supported attribs
  41101. * @param mesh The mesh to prepare the morph targets attributes for
  41102. * @param defines The current Defines of the effect
  41103. */
  41104. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41105. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41106. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41107. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41108. var manager = mesh.morphTargetManager;
  41109. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41110. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41111. for (var index = 0; index < influencers; index++) {
  41112. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41113. if (normal) {
  41114. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41115. }
  41116. if (tangent) {
  41117. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41118. }
  41119. if (attribs.length > maxAttributesCount) {
  41120. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41121. }
  41122. }
  41123. }
  41124. };
  41125. /**
  41126. * Prepares the list of attributes required for bones according to the effect defines.
  41127. * @param attribs The current list of supported attribs
  41128. * @param mesh The mesh to prepare the bones attributes for
  41129. * @param defines The current Defines of the effect
  41130. * @param fallbacks The current efffect fallback strategy
  41131. */
  41132. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41133. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41134. fallbacks.addCPUSkinningFallback(0, mesh);
  41135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41137. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41140. }
  41141. }
  41142. };
  41143. /**
  41144. * Prepares the list of attributes required for instances according to the effect defines.
  41145. * @param attribs The current list of supported attribs
  41146. * @param defines The current Defines of the effect
  41147. */
  41148. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41149. if (defines["INSTANCES"]) {
  41150. attribs.push("world0");
  41151. attribs.push("world1");
  41152. attribs.push("world2");
  41153. attribs.push("world3");
  41154. }
  41155. };
  41156. /**
  41157. * Binds the light shadow information to the effect for the given mesh.
  41158. * @param light The light containing the generator
  41159. * @param scene The scene the lights belongs to
  41160. * @param mesh The mesh we are binding the information to render
  41161. * @param lightIndex The light index in the effect used to render the mesh
  41162. * @param effect The effect we are binding the data to
  41163. */
  41164. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41165. if (light.shadowEnabled && mesh.receiveShadows) {
  41166. var shadowGenerator = light.getShadowGenerator();
  41167. if (shadowGenerator) {
  41168. shadowGenerator.bindShadowLight(lightIndex, effect);
  41169. }
  41170. }
  41171. };
  41172. /**
  41173. * Binds the light information to the effect.
  41174. * @param light The light containing the generator
  41175. * @param effect The effect we are binding the data to
  41176. * @param lightIndex The light index in the effect used to render
  41177. */
  41178. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41179. light.transferToEffect(effect, lightIndex + "");
  41180. };
  41181. /**
  41182. * Binds the lights information from the scene to the effect for the given mesh.
  41183. * @param scene The scene the lights belongs to
  41184. * @param mesh The mesh we are binding the information to render
  41185. * @param effect The effect we are binding the data to
  41186. * @param defines The generated defines for the effect
  41187. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41188. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41189. */
  41190. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41191. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41192. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41193. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41194. for (var i = 0; i < len; i++) {
  41195. var light = mesh._lightSources[i];
  41196. var iAsString = i.toString();
  41197. var scaledIntensity = light.getScaledIntensity();
  41198. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41199. MaterialHelper.BindLightProperties(light, effect, i);
  41200. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41201. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41202. if (defines["SPECULARTERM"]) {
  41203. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41204. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41205. }
  41206. // Shadows
  41207. if (scene.shadowsEnabled) {
  41208. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41209. }
  41210. light._uniformBuffer.update();
  41211. }
  41212. };
  41213. /**
  41214. * Binds the fog information from the scene to the effect for the given mesh.
  41215. * @param scene The scene the lights belongs to
  41216. * @param mesh The mesh we are binding the information to render
  41217. * @param effect The effect we are binding the data to
  41218. */
  41219. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41220. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41221. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41222. effect.setColor3("vFogColor", scene.fogColor);
  41223. }
  41224. };
  41225. /**
  41226. * Binds the bones information from the mesh to the effect.
  41227. * @param mesh The mesh we are binding the information to render
  41228. * @param effect The effect we are binding the data to
  41229. */
  41230. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41231. if (!effect || !mesh) {
  41232. return;
  41233. }
  41234. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41235. mesh.computeBonesUsingShaders = false;
  41236. }
  41237. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41238. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41239. if (matrices) {
  41240. effect.setMatrices("mBones", matrices);
  41241. }
  41242. }
  41243. };
  41244. /**
  41245. * Binds the morph targets information from the mesh to the effect.
  41246. * @param abstractMesh The mesh we are binding the information to render
  41247. * @param effect The effect we are binding the data to
  41248. */
  41249. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41250. var manager = abstractMesh.morphTargetManager;
  41251. if (!abstractMesh || !manager) {
  41252. return;
  41253. }
  41254. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41255. };
  41256. /**
  41257. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41258. * @param defines The generated defines used in the effect
  41259. * @param effect The effect we are binding the data to
  41260. * @param scene The scene we are willing to render with logarithmic scale for
  41261. */
  41262. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41263. if (defines["LOGARITHMICDEPTH"]) {
  41264. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41265. }
  41266. };
  41267. /**
  41268. * Binds the clip plane information from the scene to the effect.
  41269. * @param scene The scene the clip plane information are extracted from
  41270. * @param effect The effect we are binding the data to
  41271. */
  41272. MaterialHelper.BindClipPlane = function (effect, scene) {
  41273. if (scene.clipPlane) {
  41274. var clipPlane = scene.clipPlane;
  41275. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41276. }
  41277. };
  41278. return MaterialHelper;
  41279. }());
  41280. BABYLON.MaterialHelper = MaterialHelper;
  41281. })(BABYLON || (BABYLON = {}));
  41282. //# sourceMappingURL=babylon.materialHelper.js.map
  41283. var BABYLON;
  41284. (function (BABYLON) {
  41285. var PushMaterial = /** @class */ (function (_super) {
  41286. __extends(PushMaterial, _super);
  41287. function PushMaterial(name, scene) {
  41288. var _this = _super.call(this, name, scene) || this;
  41289. _this._normalMatrix = new BABYLON.Matrix();
  41290. _this.storeEffectOnSubMeshes = true;
  41291. return _this;
  41292. }
  41293. PushMaterial.prototype.getEffect = function () {
  41294. return this._activeEffect;
  41295. };
  41296. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41297. if (!mesh) {
  41298. return false;
  41299. }
  41300. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41301. return true;
  41302. }
  41303. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41304. };
  41305. /**
  41306. * Binds the given world matrix to the active effect
  41307. *
  41308. * @param world the matrix to bind
  41309. */
  41310. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41311. this._activeEffect.setMatrix("world", world);
  41312. };
  41313. /**
  41314. * Binds the given normal matrix to the active effect
  41315. *
  41316. * @param normalMatrix the matrix to bind
  41317. */
  41318. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41319. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41320. };
  41321. PushMaterial.prototype.bind = function (world, mesh) {
  41322. if (!mesh) {
  41323. return;
  41324. }
  41325. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41326. };
  41327. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41328. if (effect === void 0) { effect = null; }
  41329. _super.prototype._afterBind.call(this, mesh);
  41330. this.getScene()._cachedEffect = effect;
  41331. };
  41332. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41333. if (visibility === void 0) { visibility = 1; }
  41334. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41335. };
  41336. return PushMaterial;
  41337. }(BABYLON.Material));
  41338. BABYLON.PushMaterial = PushMaterial;
  41339. })(BABYLON || (BABYLON = {}));
  41340. //# sourceMappingURL=babylon.pushMaterial.js.map
  41341. var BABYLON;
  41342. (function (BABYLON) {
  41343. /** @hidden */
  41344. var StandardMaterialDefines = /** @class */ (function (_super) {
  41345. __extends(StandardMaterialDefines, _super);
  41346. function StandardMaterialDefines() {
  41347. var _this = _super.call(this) || this;
  41348. _this.MAINUV1 = false;
  41349. _this.MAINUV2 = false;
  41350. _this.DIFFUSE = false;
  41351. _this.DIFFUSEDIRECTUV = 0;
  41352. _this.AMBIENT = false;
  41353. _this.AMBIENTDIRECTUV = 0;
  41354. _this.OPACITY = false;
  41355. _this.OPACITYDIRECTUV = 0;
  41356. _this.OPACITYRGB = false;
  41357. _this.REFLECTION = false;
  41358. _this.EMISSIVE = false;
  41359. _this.EMISSIVEDIRECTUV = 0;
  41360. _this.SPECULAR = false;
  41361. _this.SPECULARDIRECTUV = 0;
  41362. _this.BUMP = false;
  41363. _this.BUMPDIRECTUV = 0;
  41364. _this.PARALLAX = false;
  41365. _this.PARALLAXOCCLUSION = false;
  41366. _this.SPECULAROVERALPHA = false;
  41367. _this.CLIPPLANE = false;
  41368. _this.ALPHATEST = false;
  41369. _this.DEPTHPREPASS = false;
  41370. _this.ALPHAFROMDIFFUSE = false;
  41371. _this.POINTSIZE = false;
  41372. _this.FOG = false;
  41373. _this.SPECULARTERM = false;
  41374. _this.DIFFUSEFRESNEL = false;
  41375. _this.OPACITYFRESNEL = false;
  41376. _this.REFLECTIONFRESNEL = false;
  41377. _this.REFRACTIONFRESNEL = false;
  41378. _this.EMISSIVEFRESNEL = false;
  41379. _this.FRESNEL = false;
  41380. _this.NORMAL = false;
  41381. _this.UV1 = false;
  41382. _this.UV2 = false;
  41383. _this.VERTEXCOLOR = false;
  41384. _this.VERTEXALPHA = false;
  41385. _this.NUM_BONE_INFLUENCERS = 0;
  41386. _this.BonesPerMesh = 0;
  41387. _this.INSTANCES = false;
  41388. _this.GLOSSINESS = false;
  41389. _this.ROUGHNESS = false;
  41390. _this.EMISSIVEASILLUMINATION = false;
  41391. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41392. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41393. _this.LIGHTMAP = false;
  41394. _this.LIGHTMAPDIRECTUV = 0;
  41395. _this.OBJECTSPACE_NORMALMAP = false;
  41396. _this.USELIGHTMAPASSHADOWMAP = false;
  41397. _this.REFLECTIONMAP_3D = false;
  41398. _this.REFLECTIONMAP_SPHERICAL = false;
  41399. _this.REFLECTIONMAP_PLANAR = false;
  41400. _this.REFLECTIONMAP_CUBIC = false;
  41401. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41402. _this.REFLECTIONMAP_PROJECTION = false;
  41403. _this.REFLECTIONMAP_SKYBOX = false;
  41404. _this.REFLECTIONMAP_EXPLICIT = false;
  41405. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41406. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41407. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41408. _this.INVERTCUBICMAP = false;
  41409. _this.LOGARITHMICDEPTH = false;
  41410. _this.REFRACTION = false;
  41411. _this.REFRACTIONMAP_3D = false;
  41412. _this.REFLECTIONOVERALPHA = false;
  41413. _this.TWOSIDEDLIGHTING = false;
  41414. _this.SHADOWFLOAT = false;
  41415. _this.MORPHTARGETS = false;
  41416. _this.MORPHTARGETS_NORMAL = false;
  41417. _this.MORPHTARGETS_TANGENT = false;
  41418. _this.NUM_MORPH_INFLUENCERS = 0;
  41419. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41420. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41421. _this.IMAGEPROCESSING = false;
  41422. _this.VIGNETTE = false;
  41423. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41424. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41425. _this.TONEMAPPING = false;
  41426. _this.CONTRAST = false;
  41427. _this.COLORCURVES = false;
  41428. _this.COLORGRADING = false;
  41429. _this.COLORGRADING3D = false;
  41430. _this.SAMPLER3DGREENDEPTH = false;
  41431. _this.SAMPLER3DBGRMAP = false;
  41432. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41433. /**
  41434. * If the reflection texture on this material is in linear color space
  41435. * @hidden
  41436. */
  41437. _this.IS_REFLECTION_LINEAR = false;
  41438. /**
  41439. * If the refraction texture on this material is in linear color space
  41440. * @hidden
  41441. */
  41442. _this.IS_REFRACTION_LINEAR = false;
  41443. _this.EXPOSURE = false;
  41444. _this.rebuild();
  41445. return _this;
  41446. }
  41447. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41448. var modes = [
  41449. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41450. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41451. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41452. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41453. ];
  41454. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41455. var mode = modes_1[_i];
  41456. this[mode] = (mode === modeToEnable);
  41457. }
  41458. };
  41459. return StandardMaterialDefines;
  41460. }(BABYLON.MaterialDefines));
  41461. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41462. var StandardMaterial = /** @class */ (function (_super) {
  41463. __extends(StandardMaterial, _super);
  41464. function StandardMaterial(name, scene) {
  41465. var _this = _super.call(this, name, scene) || this;
  41466. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41467. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41468. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41469. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41470. _this.specularPower = 64;
  41471. _this._useAlphaFromDiffuseTexture = false;
  41472. _this._useEmissiveAsIllumination = false;
  41473. _this._linkEmissiveWithDiffuse = false;
  41474. _this._useSpecularOverAlpha = false;
  41475. _this._useReflectionOverAlpha = false;
  41476. _this._disableLighting = false;
  41477. _this._useObjectSpaceNormalMap = false;
  41478. _this._useParallax = false;
  41479. _this._useParallaxOcclusion = false;
  41480. _this.parallaxScaleBias = 0.05;
  41481. _this._roughness = 0;
  41482. _this.indexOfRefraction = 0.98;
  41483. _this.invertRefractionY = true;
  41484. /**
  41485. * Defines the alpha limits in alpha test mode
  41486. */
  41487. _this.alphaCutOff = 0.4;
  41488. _this._useLightmapAsShadowmap = false;
  41489. _this._useReflectionFresnelFromSpecular = false;
  41490. _this._useGlossinessFromSpecularMapAlpha = false;
  41491. _this._maxSimultaneousLights = 4;
  41492. /**
  41493. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41494. */
  41495. _this._invertNormalMapX = false;
  41496. /**
  41497. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41498. */
  41499. _this._invertNormalMapY = false;
  41500. /**
  41501. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41502. */
  41503. _this._twoSidedLighting = false;
  41504. _this._renderTargets = new BABYLON.SmartArray(16);
  41505. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41506. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41507. // Setup the default processing configuration to the scene.
  41508. _this._attachImageProcessingConfiguration(null);
  41509. _this.getRenderTargetTextures = function () {
  41510. _this._renderTargets.reset();
  41511. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41512. _this._renderTargets.push(_this._reflectionTexture);
  41513. }
  41514. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41515. _this._renderTargets.push(_this._refractionTexture);
  41516. }
  41517. return _this._renderTargets;
  41518. };
  41519. return _this;
  41520. }
  41521. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41522. /**
  41523. * Gets the image processing configuration used either in this material.
  41524. */
  41525. get: function () {
  41526. return this._imageProcessingConfiguration;
  41527. },
  41528. /**
  41529. * Sets the Default image processing configuration used either in the this material.
  41530. *
  41531. * If sets to null, the scene one is in use.
  41532. */
  41533. set: function (value) {
  41534. this._attachImageProcessingConfiguration(value);
  41535. // Ensure the effect will be rebuilt.
  41536. this._markAllSubMeshesAsTexturesDirty();
  41537. },
  41538. enumerable: true,
  41539. configurable: true
  41540. });
  41541. /**
  41542. * Attaches a new image processing configuration to the Standard Material.
  41543. * @param configuration
  41544. */
  41545. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41546. var _this = this;
  41547. if (configuration === this._imageProcessingConfiguration) {
  41548. return;
  41549. }
  41550. // Detaches observer.
  41551. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41552. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41553. }
  41554. // Pick the scene configuration if needed.
  41555. if (!configuration) {
  41556. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41557. }
  41558. else {
  41559. this._imageProcessingConfiguration = configuration;
  41560. }
  41561. // Attaches observer.
  41562. if (this._imageProcessingConfiguration) {
  41563. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41564. _this._markAllSubMeshesAsImageProcessingDirty();
  41565. });
  41566. }
  41567. };
  41568. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41569. /**
  41570. * Gets wether the color curves effect is enabled.
  41571. */
  41572. get: function () {
  41573. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41574. },
  41575. /**
  41576. * Sets wether the color curves effect is enabled.
  41577. */
  41578. set: function (value) {
  41579. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41585. /**
  41586. * Gets wether the color grading effect is enabled.
  41587. */
  41588. get: function () {
  41589. return this.imageProcessingConfiguration.colorGradingEnabled;
  41590. },
  41591. /**
  41592. * Gets wether the color grading effect is enabled.
  41593. */
  41594. set: function (value) {
  41595. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41596. },
  41597. enumerable: true,
  41598. configurable: true
  41599. });
  41600. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41601. /**
  41602. * Gets wether tonemapping is enabled or not.
  41603. */
  41604. get: function () {
  41605. return this._imageProcessingConfiguration.toneMappingEnabled;
  41606. },
  41607. /**
  41608. * Sets wether tonemapping is enabled or not
  41609. */
  41610. set: function (value) {
  41611. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41612. },
  41613. enumerable: true,
  41614. configurable: true
  41615. });
  41616. ;
  41617. ;
  41618. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41619. /**
  41620. * The camera exposure used on this material.
  41621. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41622. * This corresponds to a photographic exposure.
  41623. */
  41624. get: function () {
  41625. return this._imageProcessingConfiguration.exposure;
  41626. },
  41627. /**
  41628. * The camera exposure used on this material.
  41629. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41630. * This corresponds to a photographic exposure.
  41631. */
  41632. set: function (value) {
  41633. this._imageProcessingConfiguration.exposure = value;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. ;
  41639. ;
  41640. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41641. /**
  41642. * Gets The camera contrast used on this material.
  41643. */
  41644. get: function () {
  41645. return this._imageProcessingConfiguration.contrast;
  41646. },
  41647. /**
  41648. * Sets The camera contrast used on this material.
  41649. */
  41650. set: function (value) {
  41651. this._imageProcessingConfiguration.contrast = value;
  41652. },
  41653. enumerable: true,
  41654. configurable: true
  41655. });
  41656. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41657. /**
  41658. * Gets the Color Grading 2D Lookup Texture.
  41659. */
  41660. get: function () {
  41661. return this._imageProcessingConfiguration.colorGradingTexture;
  41662. },
  41663. /**
  41664. * Sets the Color Grading 2D Lookup Texture.
  41665. */
  41666. set: function (value) {
  41667. this._imageProcessingConfiguration.colorGradingTexture = value;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41673. /**
  41674. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41675. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41676. * 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;
  41677. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41678. */
  41679. get: function () {
  41680. return this._imageProcessingConfiguration.colorCurves;
  41681. },
  41682. /**
  41683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41685. * 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;
  41686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41687. */
  41688. set: function (value) {
  41689. this._imageProcessingConfiguration.colorCurves = value;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. StandardMaterial.prototype.getClassName = function () {
  41695. return "StandardMaterial";
  41696. };
  41697. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41698. get: function () {
  41699. return this._useLogarithmicDepth;
  41700. },
  41701. set: function (value) {
  41702. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41703. this._markAllSubMeshesAsMiscDirty();
  41704. },
  41705. enumerable: true,
  41706. configurable: true
  41707. });
  41708. StandardMaterial.prototype.needAlphaBlending = function () {
  41709. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41710. };
  41711. StandardMaterial.prototype.needAlphaTesting = function () {
  41712. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41713. };
  41714. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41715. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41716. };
  41717. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41718. return this._diffuseTexture;
  41719. };
  41720. /**
  41721. * Child classes can use it to update shaders
  41722. */
  41723. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41724. if (useInstances === void 0) { useInstances = false; }
  41725. if (subMesh.effect && this.isFrozen) {
  41726. if (this._wasPreviouslyReady && subMesh.effect) {
  41727. return true;
  41728. }
  41729. }
  41730. if (!subMesh._materialDefines) {
  41731. subMesh._materialDefines = new StandardMaterialDefines();
  41732. }
  41733. var scene = this.getScene();
  41734. var defines = subMesh._materialDefines;
  41735. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41736. if (defines._renderId === scene.getRenderId()) {
  41737. return true;
  41738. }
  41739. }
  41740. var engine = scene.getEngine();
  41741. // Lights
  41742. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41743. // Textures
  41744. if (defines._areTexturesDirty) {
  41745. defines._needUVs = false;
  41746. defines.MAINUV1 = false;
  41747. defines.MAINUV2 = false;
  41748. if (scene.texturesEnabled) {
  41749. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41750. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41751. return false;
  41752. }
  41753. else {
  41754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41755. }
  41756. }
  41757. else {
  41758. defines.DIFFUSE = false;
  41759. }
  41760. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41761. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41762. return false;
  41763. }
  41764. else {
  41765. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41766. }
  41767. }
  41768. else {
  41769. defines.AMBIENT = false;
  41770. }
  41771. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41772. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41773. return false;
  41774. }
  41775. else {
  41776. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41777. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41778. }
  41779. }
  41780. else {
  41781. defines.OPACITY = false;
  41782. }
  41783. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41784. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41785. return false;
  41786. }
  41787. else {
  41788. defines._needNormals = true;
  41789. defines.REFLECTION = true;
  41790. defines.ROUGHNESS = (this._roughness > 0);
  41791. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41792. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41793. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41794. switch (this._reflectionTexture.coordinatesMode) {
  41795. case BABYLON.Texture.EXPLICIT_MODE:
  41796. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41797. break;
  41798. case BABYLON.Texture.PLANAR_MODE:
  41799. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41800. break;
  41801. case BABYLON.Texture.PROJECTION_MODE:
  41802. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41803. break;
  41804. case BABYLON.Texture.SKYBOX_MODE:
  41805. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41806. break;
  41807. case BABYLON.Texture.SPHERICAL_MODE:
  41808. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41809. break;
  41810. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41811. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41812. break;
  41813. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41814. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41815. break;
  41816. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41817. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41818. break;
  41819. case BABYLON.Texture.CUBIC_MODE:
  41820. case BABYLON.Texture.INVCUBIC_MODE:
  41821. default:
  41822. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41823. break;
  41824. }
  41825. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41826. }
  41827. }
  41828. else {
  41829. defines.REFLECTION = false;
  41830. }
  41831. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41832. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41833. return false;
  41834. }
  41835. else {
  41836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41837. }
  41838. }
  41839. else {
  41840. defines.EMISSIVE = false;
  41841. }
  41842. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41843. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41844. return false;
  41845. }
  41846. else {
  41847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41848. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41849. }
  41850. }
  41851. else {
  41852. defines.LIGHTMAP = false;
  41853. }
  41854. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41855. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41856. return false;
  41857. }
  41858. else {
  41859. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41860. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41861. }
  41862. }
  41863. else {
  41864. defines.SPECULAR = false;
  41865. }
  41866. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41867. // Bump texure can not be not blocking.
  41868. if (!this._bumpTexture.isReady()) {
  41869. return false;
  41870. }
  41871. else {
  41872. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41873. defines.PARALLAX = this._useParallax;
  41874. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41875. }
  41876. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41877. }
  41878. else {
  41879. defines.BUMP = false;
  41880. }
  41881. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41882. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41883. return false;
  41884. }
  41885. else {
  41886. defines._needUVs = true;
  41887. defines.REFRACTION = true;
  41888. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41889. }
  41890. }
  41891. else {
  41892. defines.REFRACTION = false;
  41893. }
  41894. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41895. }
  41896. else {
  41897. defines.DIFFUSE = false;
  41898. defines.AMBIENT = false;
  41899. defines.OPACITY = false;
  41900. defines.REFLECTION = false;
  41901. defines.EMISSIVE = false;
  41902. defines.LIGHTMAP = false;
  41903. defines.BUMP = false;
  41904. defines.REFRACTION = false;
  41905. }
  41906. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41907. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41908. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41909. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41910. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41911. }
  41912. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41913. if (!this._imageProcessingConfiguration.isReady()) {
  41914. return false;
  41915. }
  41916. this._imageProcessingConfiguration.prepareDefines(defines);
  41917. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41918. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41919. }
  41920. if (defines._areFresnelDirty) {
  41921. if (StandardMaterial.FresnelEnabled) {
  41922. // Fresnel
  41923. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41924. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41925. this._reflectionFresnelParameters) {
  41926. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41927. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41928. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41929. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41930. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41931. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41932. defines._needNormals = true;
  41933. defines.FRESNEL = true;
  41934. }
  41935. }
  41936. else {
  41937. defines.FRESNEL = false;
  41938. }
  41939. }
  41940. // Misc.
  41941. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41942. // Attribs
  41943. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41944. // Values that need to be evaluated on every frame
  41945. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41946. // Get correct effect
  41947. if (defines.isDirty) {
  41948. defines.markAsProcessed();
  41949. scene.resetCachedMaterial();
  41950. // Fallbacks
  41951. var fallbacks = new BABYLON.EffectFallbacks();
  41952. if (defines.REFLECTION) {
  41953. fallbacks.addFallback(0, "REFLECTION");
  41954. }
  41955. if (defines.SPECULAR) {
  41956. fallbacks.addFallback(0, "SPECULAR");
  41957. }
  41958. if (defines.BUMP) {
  41959. fallbacks.addFallback(0, "BUMP");
  41960. }
  41961. if (defines.PARALLAX) {
  41962. fallbacks.addFallback(1, "PARALLAX");
  41963. }
  41964. if (defines.PARALLAXOCCLUSION) {
  41965. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41966. }
  41967. if (defines.SPECULAROVERALPHA) {
  41968. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41969. }
  41970. if (defines.FOG) {
  41971. fallbacks.addFallback(1, "FOG");
  41972. }
  41973. if (defines.POINTSIZE) {
  41974. fallbacks.addFallback(0, "POINTSIZE");
  41975. }
  41976. if (defines.LOGARITHMICDEPTH) {
  41977. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41978. }
  41979. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41980. if (defines.SPECULARTERM) {
  41981. fallbacks.addFallback(0, "SPECULARTERM");
  41982. }
  41983. if (defines.DIFFUSEFRESNEL) {
  41984. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41985. }
  41986. if (defines.OPACITYFRESNEL) {
  41987. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41988. }
  41989. if (defines.REFLECTIONFRESNEL) {
  41990. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41991. }
  41992. if (defines.EMISSIVEFRESNEL) {
  41993. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41994. }
  41995. if (defines.FRESNEL) {
  41996. fallbacks.addFallback(4, "FRESNEL");
  41997. }
  41998. //Attributes
  41999. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42000. if (defines.NORMAL) {
  42001. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42002. }
  42003. if (defines.UV1) {
  42004. attribs.push(BABYLON.VertexBuffer.UVKind);
  42005. }
  42006. if (defines.UV2) {
  42007. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42008. }
  42009. if (defines.VERTEXCOLOR) {
  42010. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42011. }
  42012. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42013. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42014. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42015. var shaderName = "default";
  42016. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42017. "vFogInfos", "vFogColor", "pointSize",
  42018. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42019. "mBones",
  42020. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42021. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42022. "vReflectionPosition", "vReflectionSize",
  42023. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42024. ];
  42025. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42026. var uniformBuffers = ["Material", "Scene"];
  42027. if (BABYLON.ImageProcessingConfiguration) {
  42028. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42029. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42030. }
  42031. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42032. uniformsNames: uniforms,
  42033. uniformBuffersNames: uniformBuffers,
  42034. samplers: samplers,
  42035. defines: defines,
  42036. maxSimultaneousLights: this._maxSimultaneousLights
  42037. });
  42038. if (this.customShaderNameResolve) {
  42039. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42040. }
  42041. var join = defines.toString();
  42042. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42043. attributes: attribs,
  42044. uniformsNames: uniforms,
  42045. uniformBuffersNames: uniformBuffers,
  42046. samplers: samplers,
  42047. defines: join,
  42048. fallbacks: fallbacks,
  42049. onCompiled: this.onCompiled,
  42050. onError: this.onError,
  42051. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42052. }, engine), defines);
  42053. this.buildUniformLayout();
  42054. }
  42055. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42056. return false;
  42057. }
  42058. defines._renderId = scene.getRenderId();
  42059. this._wasPreviouslyReady = true;
  42060. return true;
  42061. };
  42062. StandardMaterial.prototype.buildUniformLayout = function () {
  42063. // Order is important !
  42064. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42065. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42066. this._uniformBuffer.addUniform("opacityParts", 4);
  42067. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42068. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42069. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42070. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42071. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42072. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42073. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42074. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42075. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42076. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42077. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42078. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42079. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42080. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42081. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42082. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42083. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42084. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42085. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42086. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42087. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42088. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42089. this._uniformBuffer.addUniform("specularMatrix", 16);
  42090. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42091. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42092. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42093. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42094. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42095. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42096. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42097. this._uniformBuffer.addUniform("pointSize", 1);
  42098. this._uniformBuffer.create();
  42099. };
  42100. StandardMaterial.prototype.unbind = function () {
  42101. if (this._activeEffect) {
  42102. var needFlag = false;
  42103. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42104. this._activeEffect.setTexture("reflection2DSampler", null);
  42105. needFlag = true;
  42106. }
  42107. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42108. this._activeEffect.setTexture("refraction2DSampler", null);
  42109. needFlag = true;
  42110. }
  42111. if (needFlag) {
  42112. this._markAllSubMeshesAsTexturesDirty();
  42113. }
  42114. }
  42115. _super.prototype.unbind.call(this);
  42116. };
  42117. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42118. var scene = this.getScene();
  42119. var defines = subMesh._materialDefines;
  42120. if (!defines) {
  42121. return;
  42122. }
  42123. var effect = subMesh.effect;
  42124. if (!effect) {
  42125. return;
  42126. }
  42127. this._activeEffect = effect;
  42128. // Matrices
  42129. this.bindOnlyWorldMatrix(world);
  42130. // Normal Matrix
  42131. if (defines.OBJECTSPACE_NORMALMAP) {
  42132. world.toNormalMatrix(this._normalMatrix);
  42133. this.bindOnlyNormalMatrix(this._normalMatrix);
  42134. }
  42135. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42136. // Bones
  42137. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42138. if (mustRebind) {
  42139. this._uniformBuffer.bindToEffect(effect, "Material");
  42140. this.bindViewProjection(effect);
  42141. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42142. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42143. // Fresnel
  42144. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42145. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42146. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42147. }
  42148. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42149. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42150. }
  42151. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42152. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42153. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42154. }
  42155. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42156. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42157. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42158. }
  42159. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42160. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42161. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42162. }
  42163. }
  42164. // Textures
  42165. if (scene.texturesEnabled) {
  42166. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42167. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42168. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42169. if (this._diffuseTexture.hasAlpha) {
  42170. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42171. }
  42172. }
  42173. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42174. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42175. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42176. }
  42177. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42178. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42179. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42180. }
  42181. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42182. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42183. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42184. if (this._reflectionTexture.boundingBoxSize) {
  42185. var cubeTexture = this._reflectionTexture;
  42186. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42187. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42188. }
  42189. }
  42190. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42191. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42192. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42193. }
  42194. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42195. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42196. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42197. }
  42198. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42199. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42200. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42201. }
  42202. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42203. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42204. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42205. if (scene._mirroredCameraPosition) {
  42206. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42207. }
  42208. else {
  42209. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42210. }
  42211. }
  42212. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42213. var depth = 1.0;
  42214. if (!this._refractionTexture.isCube) {
  42215. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42216. if (this._refractionTexture.depth) {
  42217. depth = this._refractionTexture.depth;
  42218. }
  42219. }
  42220. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42221. }
  42222. }
  42223. // Point size
  42224. if (this.pointsCloud) {
  42225. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42226. }
  42227. if (defines.SPECULARTERM) {
  42228. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42229. }
  42230. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42231. // Diffuse
  42232. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42233. }
  42234. // Textures
  42235. if (scene.texturesEnabled) {
  42236. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42237. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42238. }
  42239. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42240. effect.setTexture("ambientSampler", this._ambientTexture);
  42241. }
  42242. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42243. effect.setTexture("opacitySampler", this._opacityTexture);
  42244. }
  42245. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42246. if (this._reflectionTexture.isCube) {
  42247. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42248. }
  42249. else {
  42250. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42251. }
  42252. }
  42253. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42254. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42255. }
  42256. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42257. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42258. }
  42259. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42260. effect.setTexture("specularSampler", this._specularTexture);
  42261. }
  42262. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42263. effect.setTexture("bumpSampler", this._bumpTexture);
  42264. }
  42265. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42266. var depth = 1.0;
  42267. if (this._refractionTexture.isCube) {
  42268. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42269. }
  42270. else {
  42271. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42272. }
  42273. }
  42274. }
  42275. // Clip plane
  42276. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42277. // Colors
  42278. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42279. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42280. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42281. }
  42282. if (mustRebind || !this.isFrozen) {
  42283. // Lights
  42284. if (scene.lightsEnabled && !this._disableLighting) {
  42285. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42286. }
  42287. // View
  42288. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42289. this.bindView(effect);
  42290. }
  42291. // Fog
  42292. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42293. // Morph targets
  42294. if (defines.NUM_MORPH_INFLUENCERS) {
  42295. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42296. }
  42297. // Log. depth
  42298. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42299. // image processing
  42300. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42301. this._imageProcessingConfiguration.bind(this._activeEffect);
  42302. }
  42303. }
  42304. this._uniformBuffer.update();
  42305. this._afterBind(mesh, this._activeEffect);
  42306. };
  42307. StandardMaterial.prototype.getAnimatables = function () {
  42308. var results = [];
  42309. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42310. results.push(this._diffuseTexture);
  42311. }
  42312. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42313. results.push(this._ambientTexture);
  42314. }
  42315. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42316. results.push(this._opacityTexture);
  42317. }
  42318. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42319. results.push(this._reflectionTexture);
  42320. }
  42321. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42322. results.push(this._emissiveTexture);
  42323. }
  42324. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42325. results.push(this._specularTexture);
  42326. }
  42327. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42328. results.push(this._bumpTexture);
  42329. }
  42330. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42331. results.push(this._lightmapTexture);
  42332. }
  42333. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42334. results.push(this._refractionTexture);
  42335. }
  42336. return results;
  42337. };
  42338. StandardMaterial.prototype.getActiveTextures = function () {
  42339. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42340. if (this._diffuseTexture) {
  42341. activeTextures.push(this._diffuseTexture);
  42342. }
  42343. if (this._ambientTexture) {
  42344. activeTextures.push(this._ambientTexture);
  42345. }
  42346. if (this._opacityTexture) {
  42347. activeTextures.push(this._opacityTexture);
  42348. }
  42349. if (this._reflectionTexture) {
  42350. activeTextures.push(this._reflectionTexture);
  42351. }
  42352. if (this._emissiveTexture) {
  42353. activeTextures.push(this._emissiveTexture);
  42354. }
  42355. if (this._specularTexture) {
  42356. activeTextures.push(this._specularTexture);
  42357. }
  42358. if (this._bumpTexture) {
  42359. activeTextures.push(this._bumpTexture);
  42360. }
  42361. if (this._lightmapTexture) {
  42362. activeTextures.push(this._lightmapTexture);
  42363. }
  42364. if (this._refractionTexture) {
  42365. activeTextures.push(this._refractionTexture);
  42366. }
  42367. return activeTextures;
  42368. };
  42369. StandardMaterial.prototype.hasTexture = function (texture) {
  42370. if (_super.prototype.hasTexture.call(this, texture)) {
  42371. return true;
  42372. }
  42373. if (this._diffuseTexture === texture) {
  42374. return true;
  42375. }
  42376. if (this._ambientTexture === texture) {
  42377. return true;
  42378. }
  42379. if (this._opacityTexture === texture) {
  42380. return true;
  42381. }
  42382. if (this._reflectionTexture === texture) {
  42383. return true;
  42384. }
  42385. if (this._emissiveTexture === texture) {
  42386. return true;
  42387. }
  42388. if (this._specularTexture === texture) {
  42389. return true;
  42390. }
  42391. if (this._bumpTexture === texture) {
  42392. return true;
  42393. }
  42394. if (this._lightmapTexture === texture) {
  42395. return true;
  42396. }
  42397. if (this._refractionTexture === texture) {
  42398. return true;
  42399. }
  42400. return false;
  42401. };
  42402. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42403. if (forceDisposeTextures) {
  42404. if (this._diffuseTexture) {
  42405. this._diffuseTexture.dispose();
  42406. }
  42407. if (this._ambientTexture) {
  42408. this._ambientTexture.dispose();
  42409. }
  42410. if (this._opacityTexture) {
  42411. this._opacityTexture.dispose();
  42412. }
  42413. if (this._reflectionTexture) {
  42414. this._reflectionTexture.dispose();
  42415. }
  42416. if (this._emissiveTexture) {
  42417. this._emissiveTexture.dispose();
  42418. }
  42419. if (this._specularTexture) {
  42420. this._specularTexture.dispose();
  42421. }
  42422. if (this._bumpTexture) {
  42423. this._bumpTexture.dispose();
  42424. }
  42425. if (this._lightmapTexture) {
  42426. this._lightmapTexture.dispose();
  42427. }
  42428. if (this._refractionTexture) {
  42429. this._refractionTexture.dispose();
  42430. }
  42431. }
  42432. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42433. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42434. }
  42435. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42436. };
  42437. StandardMaterial.prototype.clone = function (name) {
  42438. var _this = this;
  42439. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42440. result.name = name;
  42441. result.id = name;
  42442. return result;
  42443. };
  42444. StandardMaterial.prototype.serialize = function () {
  42445. return BABYLON.SerializationHelper.Serialize(this);
  42446. };
  42447. // Statics
  42448. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42449. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42450. };
  42451. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42452. get: function () {
  42453. return StandardMaterial._DiffuseTextureEnabled;
  42454. },
  42455. set: function (value) {
  42456. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42457. return;
  42458. }
  42459. StandardMaterial._DiffuseTextureEnabled = value;
  42460. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42461. },
  42462. enumerable: true,
  42463. configurable: true
  42464. });
  42465. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42466. get: function () {
  42467. return StandardMaterial._AmbientTextureEnabled;
  42468. },
  42469. set: function (value) {
  42470. if (StandardMaterial._AmbientTextureEnabled === value) {
  42471. return;
  42472. }
  42473. StandardMaterial._AmbientTextureEnabled = value;
  42474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42475. },
  42476. enumerable: true,
  42477. configurable: true
  42478. });
  42479. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42480. get: function () {
  42481. return StandardMaterial._OpacityTextureEnabled;
  42482. },
  42483. set: function (value) {
  42484. if (StandardMaterial._OpacityTextureEnabled === value) {
  42485. return;
  42486. }
  42487. StandardMaterial._OpacityTextureEnabled = value;
  42488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42489. },
  42490. enumerable: true,
  42491. configurable: true
  42492. });
  42493. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42494. get: function () {
  42495. return StandardMaterial._ReflectionTextureEnabled;
  42496. },
  42497. set: function (value) {
  42498. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42499. return;
  42500. }
  42501. StandardMaterial._ReflectionTextureEnabled = value;
  42502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42503. },
  42504. enumerable: true,
  42505. configurable: true
  42506. });
  42507. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42508. get: function () {
  42509. return StandardMaterial._EmissiveTextureEnabled;
  42510. },
  42511. set: function (value) {
  42512. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42513. return;
  42514. }
  42515. StandardMaterial._EmissiveTextureEnabled = value;
  42516. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42522. get: function () {
  42523. return StandardMaterial._SpecularTextureEnabled;
  42524. },
  42525. set: function (value) {
  42526. if (StandardMaterial._SpecularTextureEnabled === value) {
  42527. return;
  42528. }
  42529. StandardMaterial._SpecularTextureEnabled = value;
  42530. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42536. get: function () {
  42537. return StandardMaterial._BumpTextureEnabled;
  42538. },
  42539. set: function (value) {
  42540. if (StandardMaterial._BumpTextureEnabled === value) {
  42541. return;
  42542. }
  42543. StandardMaterial._BumpTextureEnabled = value;
  42544. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42545. },
  42546. enumerable: true,
  42547. configurable: true
  42548. });
  42549. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42550. get: function () {
  42551. return StandardMaterial._LightmapTextureEnabled;
  42552. },
  42553. set: function (value) {
  42554. if (StandardMaterial._LightmapTextureEnabled === value) {
  42555. return;
  42556. }
  42557. StandardMaterial._LightmapTextureEnabled = value;
  42558. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42559. },
  42560. enumerable: true,
  42561. configurable: true
  42562. });
  42563. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42564. get: function () {
  42565. return StandardMaterial._RefractionTextureEnabled;
  42566. },
  42567. set: function (value) {
  42568. if (StandardMaterial._RefractionTextureEnabled === value) {
  42569. return;
  42570. }
  42571. StandardMaterial._RefractionTextureEnabled = value;
  42572. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42578. get: function () {
  42579. return StandardMaterial._ColorGradingTextureEnabled;
  42580. },
  42581. set: function (value) {
  42582. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42583. return;
  42584. }
  42585. StandardMaterial._ColorGradingTextureEnabled = value;
  42586. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42587. },
  42588. enumerable: true,
  42589. configurable: true
  42590. });
  42591. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42592. get: function () {
  42593. return StandardMaterial._FresnelEnabled;
  42594. },
  42595. set: function (value) {
  42596. if (StandardMaterial._FresnelEnabled === value) {
  42597. return;
  42598. }
  42599. StandardMaterial._FresnelEnabled = value;
  42600. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42601. },
  42602. enumerable: true,
  42603. configurable: true
  42604. });
  42605. // Flags used to enable or disable a type of texture for all Standard Materials
  42606. StandardMaterial._DiffuseTextureEnabled = true;
  42607. StandardMaterial._AmbientTextureEnabled = true;
  42608. StandardMaterial._OpacityTextureEnabled = true;
  42609. StandardMaterial._ReflectionTextureEnabled = true;
  42610. StandardMaterial._EmissiveTextureEnabled = true;
  42611. StandardMaterial._SpecularTextureEnabled = true;
  42612. StandardMaterial._BumpTextureEnabled = true;
  42613. StandardMaterial._LightmapTextureEnabled = true;
  42614. StandardMaterial._RefractionTextureEnabled = true;
  42615. StandardMaterial._ColorGradingTextureEnabled = true;
  42616. StandardMaterial._FresnelEnabled = true;
  42617. __decorate([
  42618. BABYLON.serializeAsTexture("diffuseTexture")
  42619. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42620. __decorate([
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42622. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42623. __decorate([
  42624. BABYLON.serializeAsTexture("ambientTexture")
  42625. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42626. __decorate([
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42628. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42629. __decorate([
  42630. BABYLON.serializeAsTexture("opacityTexture")
  42631. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42632. __decorate([
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42634. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42635. __decorate([
  42636. BABYLON.serializeAsTexture("reflectionTexture")
  42637. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42638. __decorate([
  42639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42640. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42641. __decorate([
  42642. BABYLON.serializeAsTexture("emissiveTexture")
  42643. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42644. __decorate([
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42647. __decorate([
  42648. BABYLON.serializeAsTexture("specularTexture")
  42649. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42650. __decorate([
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42652. ], StandardMaterial.prototype, "specularTexture", void 0);
  42653. __decorate([
  42654. BABYLON.serializeAsTexture("bumpTexture")
  42655. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42656. __decorate([
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42659. __decorate([
  42660. BABYLON.serializeAsTexture("lightmapTexture")
  42661. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42662. __decorate([
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42664. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42665. __decorate([
  42666. BABYLON.serializeAsTexture("refractionTexture")
  42667. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42668. __decorate([
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42671. __decorate([
  42672. BABYLON.serializeAsColor3("ambient")
  42673. ], StandardMaterial.prototype, "ambientColor", void 0);
  42674. __decorate([
  42675. BABYLON.serializeAsColor3("diffuse")
  42676. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42677. __decorate([
  42678. BABYLON.serializeAsColor3("specular")
  42679. ], StandardMaterial.prototype, "specularColor", void 0);
  42680. __decorate([
  42681. BABYLON.serializeAsColor3("emissive")
  42682. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42683. __decorate([
  42684. BABYLON.serialize()
  42685. ], StandardMaterial.prototype, "specularPower", void 0);
  42686. __decorate([
  42687. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42688. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42692. __decorate([
  42693. BABYLON.serialize("useEmissiveAsIllumination")
  42694. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42695. __decorate([
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42698. __decorate([
  42699. BABYLON.serialize("linkEmissiveWithDiffuse")
  42700. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42701. __decorate([
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42703. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42704. __decorate([
  42705. BABYLON.serialize("useSpecularOverAlpha")
  42706. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42710. __decorate([
  42711. BABYLON.serialize("useReflectionOverAlpha")
  42712. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42716. __decorate([
  42717. BABYLON.serialize("disableLighting")
  42718. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42719. __decorate([
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42721. ], StandardMaterial.prototype, "disableLighting", void 0);
  42722. __decorate([
  42723. BABYLON.serialize("useObjectSpaceNormalMap")
  42724. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42725. __decorate([
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42727. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42728. __decorate([
  42729. BABYLON.serialize("useParallax")
  42730. ], StandardMaterial.prototype, "_useParallax", void 0);
  42731. __decorate([
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], StandardMaterial.prototype, "useParallax", void 0);
  42734. __decorate([
  42735. BABYLON.serialize("useParallaxOcclusion")
  42736. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42737. __decorate([
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42740. __decorate([
  42741. BABYLON.serialize()
  42742. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42743. __decorate([
  42744. BABYLON.serialize("roughness")
  42745. ], StandardMaterial.prototype, "_roughness", void 0);
  42746. __decorate([
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42748. ], StandardMaterial.prototype, "roughness", void 0);
  42749. __decorate([
  42750. BABYLON.serialize()
  42751. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42752. __decorate([
  42753. BABYLON.serialize()
  42754. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42755. __decorate([
  42756. BABYLON.serialize()
  42757. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42758. __decorate([
  42759. BABYLON.serialize("useLightmapAsShadowmap")
  42760. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42761. __decorate([
  42762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42763. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42764. __decorate([
  42765. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42766. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42767. __decorate([
  42768. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42769. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42770. __decorate([
  42771. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42772. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42773. __decorate([
  42774. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42775. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42776. __decorate([
  42777. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42778. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42779. __decorate([
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42781. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42782. __decorate([
  42783. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42784. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42785. __decorate([
  42786. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42787. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42788. __decorate([
  42789. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42790. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42791. __decorate([
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42793. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42794. __decorate([
  42795. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42796. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42797. __decorate([
  42798. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42799. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42800. __decorate([
  42801. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42802. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42803. __decorate([
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42805. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42806. __decorate([
  42807. BABYLON.serialize("maxSimultaneousLights")
  42808. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42809. __decorate([
  42810. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42811. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42812. __decorate([
  42813. BABYLON.serialize("invertNormalMapX")
  42814. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42815. __decorate([
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42817. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42818. __decorate([
  42819. BABYLON.serialize("invertNormalMapY")
  42820. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42821. __decorate([
  42822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42823. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42824. __decorate([
  42825. BABYLON.serialize("twoSidedLighting")
  42826. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42827. __decorate([
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42829. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42830. __decorate([
  42831. BABYLON.serialize()
  42832. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42833. return StandardMaterial;
  42834. }(BABYLON.PushMaterial));
  42835. BABYLON.StandardMaterial = StandardMaterial;
  42836. })(BABYLON || (BABYLON = {}));
  42837. //# sourceMappingURL=babylon.standardMaterial.js.map
  42838. var BABYLON;
  42839. (function (BABYLON) {
  42840. /**
  42841. * Manages the defines for the PBR Material.
  42842. * @hiddenChildren
  42843. */
  42844. var PBRMaterialDefines = /** @class */ (function (_super) {
  42845. __extends(PBRMaterialDefines, _super);
  42846. /**
  42847. * Initializes the PBR Material defines.
  42848. */
  42849. function PBRMaterialDefines() {
  42850. var _this = _super.call(this) || this;
  42851. _this.PBR = true;
  42852. _this.MAINUV1 = false;
  42853. _this.MAINUV2 = false;
  42854. _this.UV1 = false;
  42855. _this.UV2 = false;
  42856. _this.ALBEDO = false;
  42857. _this.ALBEDODIRECTUV = 0;
  42858. _this.VERTEXCOLOR = false;
  42859. _this.AMBIENT = false;
  42860. _this.AMBIENTDIRECTUV = 0;
  42861. _this.AMBIENTINGRAYSCALE = false;
  42862. _this.OPACITY = false;
  42863. _this.VERTEXALPHA = false;
  42864. _this.OPACITYDIRECTUV = 0;
  42865. _this.OPACITYRGB = false;
  42866. _this.ALPHATEST = false;
  42867. _this.DEPTHPREPASS = false;
  42868. _this.ALPHABLEND = false;
  42869. _this.ALPHAFROMALBEDO = false;
  42870. _this.ALPHATESTVALUE = "0.5";
  42871. _this.SPECULAROVERALPHA = false;
  42872. _this.RADIANCEOVERALPHA = false;
  42873. _this.ALPHAFRESNEL = false;
  42874. _this.LINEARALPHAFRESNEL = false;
  42875. _this.PREMULTIPLYALPHA = false;
  42876. _this.EMISSIVE = false;
  42877. _this.EMISSIVEDIRECTUV = 0;
  42878. _this.REFLECTIVITY = false;
  42879. _this.REFLECTIVITYDIRECTUV = 0;
  42880. _this.SPECULARTERM = false;
  42881. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  42882. _this.MICROSURFACEAUTOMATIC = false;
  42883. _this.LODBASEDMICROSFURACE = false;
  42884. _this.MICROSURFACEMAP = false;
  42885. _this.MICROSURFACEMAPDIRECTUV = 0;
  42886. _this.METALLICWORKFLOW = false;
  42887. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  42888. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  42889. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  42890. _this.AOSTOREINMETALMAPRED = false;
  42891. _this.ENVIRONMENTBRDF = false;
  42892. _this.NORMAL = false;
  42893. _this.TANGENT = false;
  42894. _this.BUMP = false;
  42895. _this.BUMPDIRECTUV = 0;
  42896. _this.OBJECTSPACE_NORMALMAP = false;
  42897. _this.PARALLAX = false;
  42898. _this.PARALLAXOCCLUSION = false;
  42899. _this.NORMALXYSCALE = true;
  42900. _this.LIGHTMAP = false;
  42901. _this.LIGHTMAPDIRECTUV = 0;
  42902. _this.USELIGHTMAPASSHADOWMAP = false;
  42903. _this.GAMMALIGHTMAP = false;
  42904. _this.REFLECTION = false;
  42905. _this.REFLECTIONMAP_3D = false;
  42906. _this.REFLECTIONMAP_SPHERICAL = false;
  42907. _this.REFLECTIONMAP_PLANAR = false;
  42908. _this.REFLECTIONMAP_CUBIC = false;
  42909. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42910. _this.REFLECTIONMAP_PROJECTION = false;
  42911. _this.REFLECTIONMAP_SKYBOX = false;
  42912. _this.REFLECTIONMAP_EXPLICIT = false;
  42913. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42914. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42915. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42916. _this.INVERTCUBICMAP = false;
  42917. _this.USESPHERICALFROMREFLECTIONMAP = false;
  42918. _this.USESPHERICALINVERTEX = false;
  42919. _this.REFLECTIONMAP_OPPOSITEZ = false;
  42920. _this.LODINREFLECTIONALPHA = false;
  42921. _this.GAMMAREFLECTION = false;
  42922. _this.RGBDREFLECTION = false;
  42923. _this.RADIANCEOCCLUSION = false;
  42924. _this.HORIZONOCCLUSION = false;
  42925. _this.REFRACTION = false;
  42926. _this.REFRACTIONMAP_3D = false;
  42927. _this.REFRACTIONMAP_OPPOSITEZ = false;
  42928. _this.LODINREFRACTIONALPHA = false;
  42929. _this.GAMMAREFRACTION = false;
  42930. _this.RGBDREFRACTION = false;
  42931. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  42932. _this.INSTANCES = false;
  42933. _this.NUM_BONE_INFLUENCERS = 0;
  42934. _this.BonesPerMesh = 0;
  42935. _this.NONUNIFORMSCALING = false;
  42936. _this.MORPHTARGETS = false;
  42937. _this.MORPHTARGETS_NORMAL = false;
  42938. _this.MORPHTARGETS_TANGENT = false;
  42939. _this.NUM_MORPH_INFLUENCERS = 0;
  42940. _this.IMAGEPROCESSING = false;
  42941. _this.VIGNETTE = false;
  42942. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42943. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42944. _this.TONEMAPPING = false;
  42945. _this.CONTRAST = false;
  42946. _this.COLORCURVES = false;
  42947. _this.COLORGRADING = false;
  42948. _this.COLORGRADING3D = false;
  42949. _this.SAMPLER3DGREENDEPTH = false;
  42950. _this.SAMPLER3DBGRMAP = false;
  42951. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42952. _this.EXPOSURE = false;
  42953. _this.USEPHYSICALLIGHTFALLOFF = false;
  42954. _this.TWOSIDEDLIGHTING = false;
  42955. _this.SHADOWFLOAT = false;
  42956. _this.CLIPPLANE = false;
  42957. _this.POINTSIZE = false;
  42958. _this.FOG = false;
  42959. _this.LOGARITHMICDEPTH = false;
  42960. _this.FORCENORMALFORWARD = false;
  42961. _this.SPECULARAA = false;
  42962. _this.UNLIT = false;
  42963. _this.rebuild();
  42964. return _this;
  42965. }
  42966. /**
  42967. * Resets the PBR Material defines.
  42968. */
  42969. PBRMaterialDefines.prototype.reset = function () {
  42970. _super.prototype.reset.call(this);
  42971. this.ALPHATESTVALUE = "0.5";
  42972. this.PBR = true;
  42973. };
  42974. return PBRMaterialDefines;
  42975. }(BABYLON.MaterialDefines));
  42976. /**
  42977. * The Physically based material base class of BJS.
  42978. *
  42979. * This offers the main features of a standard PBR material.
  42980. * For more information, please refer to the documentation :
  42981. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42982. */
  42983. var PBRBaseMaterial = /** @class */ (function (_super) {
  42984. __extends(PBRBaseMaterial, _super);
  42985. /**
  42986. * Instantiates a new PBRMaterial instance.
  42987. *
  42988. * @param name The material name
  42989. * @param scene The scene the material will be use in.
  42990. */
  42991. function PBRBaseMaterial(name, scene) {
  42992. var _this = _super.call(this, name, scene) || this;
  42993. /**
  42994. * Intensity of the direct lights e.g. the four lights available in your scene.
  42995. * This impacts both the direct diffuse and specular highlights.
  42996. */
  42997. _this._directIntensity = 1.0;
  42998. /**
  42999. * Intensity of the emissive part of the material.
  43000. * This helps controlling the emissive effect without modifying the emissive color.
  43001. */
  43002. _this._emissiveIntensity = 1.0;
  43003. /**
  43004. * Intensity of the environment e.g. how much the environment will light the object
  43005. * either through harmonics for rough material or through the refelction for shiny ones.
  43006. */
  43007. _this._environmentIntensity = 1.0;
  43008. /**
  43009. * This is a special control allowing the reduction of the specular highlights coming from the
  43010. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43011. */
  43012. _this._specularIntensity = 1.0;
  43013. /**
  43014. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43015. */
  43016. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43017. /**
  43018. * Debug Control allowing disabling the bump map on this material.
  43019. */
  43020. _this._disableBumpMap = false;
  43021. /**
  43022. * AKA Occlusion Texture Intensity in other nomenclature.
  43023. */
  43024. _this._ambientTextureStrength = 1.0;
  43025. /**
  43026. * The color of a material in ambient lighting.
  43027. */
  43028. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43029. /**
  43030. * AKA Diffuse Color in other nomenclature.
  43031. */
  43032. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43033. /**
  43034. * AKA Specular Color in other nomenclature.
  43035. */
  43036. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43037. /**
  43038. * The color applied when light is reflected from a material.
  43039. */
  43040. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43041. /**
  43042. * The color applied when light is emitted from a material.
  43043. */
  43044. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43045. /**
  43046. * AKA Glossiness in other nomenclature.
  43047. */
  43048. _this._microSurface = 0.9;
  43049. /**
  43050. * source material index of refraction (IOR)' / 'destination material IOR.
  43051. */
  43052. _this._indexOfRefraction = 0.66;
  43053. /**
  43054. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43055. */
  43056. _this._invertRefractionY = false;
  43057. /**
  43058. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43059. * Materials half opaque for instance using refraction could benefit from this control.
  43060. */
  43061. _this._linkRefractionWithTransparency = false;
  43062. /**
  43063. * Specifies that the material will use the light map as a show map.
  43064. */
  43065. _this._useLightmapAsShadowmap = false;
  43066. /**
  43067. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43068. * makes the reflect vector face the model (under horizon).
  43069. */
  43070. _this._useHorizonOcclusion = true;
  43071. /**
  43072. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43073. * too much the area relying on ambient texture to define their ambient occlusion.
  43074. */
  43075. _this._useRadianceOcclusion = true;
  43076. /**
  43077. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43078. */
  43079. _this._useAlphaFromAlbedoTexture = false;
  43080. /**
  43081. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43082. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43083. */
  43084. _this._useSpecularOverAlpha = true;
  43085. /**
  43086. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43087. */
  43088. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43089. /**
  43090. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43091. */
  43092. _this._useRoughnessFromMetallicTextureAlpha = true;
  43093. /**
  43094. * Specifies if the metallic texture contains the roughness information in its green channel.
  43095. */
  43096. _this._useRoughnessFromMetallicTextureGreen = false;
  43097. /**
  43098. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43099. */
  43100. _this._useMetallnessFromMetallicTextureBlue = false;
  43101. /**
  43102. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43103. */
  43104. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43105. /**
  43106. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43107. */
  43108. _this._useAmbientInGrayScale = false;
  43109. /**
  43110. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43111. * The material will try to infer what glossiness each pixel should be.
  43112. */
  43113. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43114. /**
  43115. * BJS is using an harcoded light falloff based on a manually sets up range.
  43116. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43117. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43118. */
  43119. _this._usePhysicalLightFalloff = true;
  43120. /**
  43121. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43122. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43123. */
  43124. _this._useRadianceOverAlpha = true;
  43125. /**
  43126. * Allows using an object space normal map (instead of tangent space).
  43127. */
  43128. _this._useObjectSpaceNormalMap = false;
  43129. /**
  43130. * Allows using the bump map in parallax mode.
  43131. */
  43132. _this._useParallax = false;
  43133. /**
  43134. * Allows using the bump map in parallax occlusion mode.
  43135. */
  43136. _this._useParallaxOcclusion = false;
  43137. /**
  43138. * Controls the scale bias of the parallax mode.
  43139. */
  43140. _this._parallaxScaleBias = 0.05;
  43141. /**
  43142. * If sets to true, disables all the lights affecting the material.
  43143. */
  43144. _this._disableLighting = false;
  43145. /**
  43146. * Number of Simultaneous lights allowed on the material.
  43147. */
  43148. _this._maxSimultaneousLights = 4;
  43149. /**
  43150. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43151. */
  43152. _this._invertNormalMapX = false;
  43153. /**
  43154. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43155. */
  43156. _this._invertNormalMapY = false;
  43157. /**
  43158. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43159. */
  43160. _this._twoSidedLighting = false;
  43161. /**
  43162. * Defines the alpha limits in alpha test mode.
  43163. */
  43164. _this._alphaCutOff = 0.4;
  43165. /**
  43166. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43167. */
  43168. _this._forceAlphaTest = false;
  43169. /**
  43170. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43171. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43172. */
  43173. _this._useAlphaFresnel = false;
  43174. /**
  43175. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43176. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43177. */
  43178. _this._useLinearAlphaFresnel = false;
  43179. /**
  43180. * The transparency mode of the material.
  43181. */
  43182. _this._transparencyMode = null;
  43183. /**
  43184. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43185. * from cos thetav and roughness:
  43186. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43187. */
  43188. _this._environmentBRDFTexture = null;
  43189. /**
  43190. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43191. */
  43192. _this._forceIrradianceInFragment = false;
  43193. /**
  43194. * Force normal to face away from face.
  43195. */
  43196. _this._forceNormalForward = false;
  43197. /**
  43198. * Enables specular anti aliasing in the PBR shader.
  43199. * It will both interacts on the Geometry for analytical and IBL lighting.
  43200. * It also prefilter the roughness map based on the bump values.
  43201. */
  43202. _this._enableSpecularAntiAliasing = false;
  43203. /**
  43204. * Stores the available render targets.
  43205. */
  43206. _this._renderTargets = new BABYLON.SmartArray(16);
  43207. /**
  43208. * Sets the global ambient color for the material used in lighting calculations.
  43209. */
  43210. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43211. /**
  43212. * If set to true, no lighting calculations will be applied.
  43213. */
  43214. _this._unlit = false;
  43215. // Setup the default processing configuration to the scene.
  43216. _this._attachImageProcessingConfiguration(null);
  43217. _this.getRenderTargetTextures = function () {
  43218. _this._renderTargets.reset();
  43219. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43220. _this._renderTargets.push(_this._reflectionTexture);
  43221. }
  43222. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43223. _this._renderTargets.push(_this._refractionTexture);
  43224. }
  43225. return _this._renderTargets;
  43226. };
  43227. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43228. return _this;
  43229. }
  43230. /**
  43231. * Attaches a new image processing configuration to the PBR Material.
  43232. * @param configuration
  43233. */
  43234. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43235. var _this = this;
  43236. if (configuration === this._imageProcessingConfiguration) {
  43237. return;
  43238. }
  43239. // Detaches observer.
  43240. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43241. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43242. }
  43243. // Pick the scene configuration if needed.
  43244. if (!configuration) {
  43245. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43246. }
  43247. else {
  43248. this._imageProcessingConfiguration = configuration;
  43249. }
  43250. // Attaches observer.
  43251. if (this._imageProcessingConfiguration) {
  43252. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43253. _this._markAllSubMeshesAsImageProcessingDirty();
  43254. });
  43255. }
  43256. };
  43257. /**
  43258. * Gets the name of the material class.
  43259. */
  43260. PBRBaseMaterial.prototype.getClassName = function () {
  43261. return "PBRBaseMaterial";
  43262. };
  43263. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43264. /**
  43265. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43266. */
  43267. get: function () {
  43268. return this._useLogarithmicDepth;
  43269. },
  43270. /**
  43271. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43272. */
  43273. set: function (value) {
  43274. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43275. },
  43276. enumerable: true,
  43277. configurable: true
  43278. });
  43279. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43280. /**
  43281. * Gets the current transparency mode.
  43282. */
  43283. get: function () {
  43284. return this._transparencyMode;
  43285. },
  43286. /**
  43287. * Sets the transparency mode of the material.
  43288. *
  43289. * | Value | Type | Description |
  43290. * | ----- | ----------------------------------- | ----------- |
  43291. * | 0 | OPAQUE | |
  43292. * | 1 | ALPHATEST | |
  43293. * | 2 | ALPHABLEND | |
  43294. * | 3 | ALPHATESTANDBLEND | |
  43295. *
  43296. */
  43297. set: function (value) {
  43298. if (this._transparencyMode === value) {
  43299. return;
  43300. }
  43301. this._transparencyMode = value;
  43302. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43303. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43304. },
  43305. enumerable: true,
  43306. configurable: true
  43307. });
  43308. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43309. /**
  43310. * Returns true if alpha blending should be disabled.
  43311. */
  43312. get: function () {
  43313. return (this._linkRefractionWithTransparency ||
  43314. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43315. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43316. },
  43317. enumerable: true,
  43318. configurable: true
  43319. });
  43320. /**
  43321. * Specifies whether or not this material should be rendered in alpha blend mode.
  43322. */
  43323. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43324. if (this._disableAlphaBlending) {
  43325. return false;
  43326. }
  43327. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43328. };
  43329. /**
  43330. * Specifies if the mesh will require alpha blending.
  43331. * @param mesh - BJS mesh.
  43332. */
  43333. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43334. if (this._disableAlphaBlending) {
  43335. return false;
  43336. }
  43337. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43338. };
  43339. /**
  43340. * Specifies whether or not this material should be rendered in alpha test mode.
  43341. */
  43342. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43343. if (this._forceAlphaTest) {
  43344. return true;
  43345. }
  43346. if (this._linkRefractionWithTransparency) {
  43347. return false;
  43348. }
  43349. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43350. };
  43351. /**
  43352. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43353. */
  43354. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43355. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43356. };
  43357. /**
  43358. * Gets the texture used for the alpha test.
  43359. */
  43360. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43361. return this._albedoTexture;
  43362. };
  43363. /**
  43364. * Specifies that the submesh is ready to be used.
  43365. * @param mesh - BJS mesh.
  43366. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43367. * @param useInstances - Specifies that instances should be used.
  43368. * @returns - boolean indicating that the submesh is ready or not.
  43369. */
  43370. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43371. if (subMesh.effect && this.isFrozen) {
  43372. if (this._wasPreviouslyReady) {
  43373. return true;
  43374. }
  43375. }
  43376. if (!subMesh._materialDefines) {
  43377. subMesh._materialDefines = new PBRMaterialDefines();
  43378. }
  43379. var defines = subMesh._materialDefines;
  43380. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43381. if (defines._renderId === this.getScene().getRenderId()) {
  43382. return true;
  43383. }
  43384. }
  43385. var scene = this.getScene();
  43386. var engine = scene.getEngine();
  43387. if (defines._areTexturesDirty) {
  43388. if (scene.texturesEnabled) {
  43389. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43390. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43391. return false;
  43392. }
  43393. }
  43394. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43395. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43396. return false;
  43397. }
  43398. }
  43399. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43400. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43401. return false;
  43402. }
  43403. }
  43404. var reflectionTexture = this._getReflectionTexture();
  43405. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43406. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43407. return false;
  43408. }
  43409. }
  43410. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43411. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43412. return false;
  43413. }
  43414. }
  43415. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43416. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43417. return false;
  43418. }
  43419. }
  43420. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43421. if (this._metallicTexture) {
  43422. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43423. return false;
  43424. }
  43425. }
  43426. else if (this._reflectivityTexture) {
  43427. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43428. return false;
  43429. }
  43430. }
  43431. if (this._microSurfaceTexture) {
  43432. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43433. return false;
  43434. }
  43435. }
  43436. }
  43437. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43438. // Bump texture cannot be not blocking.
  43439. if (!this._bumpTexture.isReady()) {
  43440. return false;
  43441. }
  43442. }
  43443. var refractionTexture = this._getRefractionTexture();
  43444. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43445. if (!refractionTexture.isReadyOrNotBlocking()) {
  43446. return false;
  43447. }
  43448. }
  43449. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43450. // This is blocking.
  43451. if (!this._environmentBRDFTexture.isReady()) {
  43452. return false;
  43453. }
  43454. }
  43455. }
  43456. }
  43457. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43458. if (!this._imageProcessingConfiguration.isReady()) {
  43459. return false;
  43460. }
  43461. }
  43462. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43463. mesh.createNormals(true);
  43464. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43465. }
  43466. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43467. if (effect) {
  43468. scene.resetCachedMaterial();
  43469. subMesh.setEffect(effect, defines);
  43470. this.buildUniformLayout();
  43471. }
  43472. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43473. return false;
  43474. }
  43475. defines._renderId = scene.getRenderId();
  43476. this._wasPreviouslyReady = true;
  43477. return true;
  43478. };
  43479. /**
  43480. * Specifies if the material uses metallic roughness workflow.
  43481. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43482. */
  43483. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43484. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43485. return true;
  43486. }
  43487. return false;
  43488. };
  43489. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43490. if (onCompiled === void 0) { onCompiled = null; }
  43491. if (onError === void 0) { onError = null; }
  43492. if (useInstances === void 0) { useInstances = null; }
  43493. if (useClipPlane === void 0) { useClipPlane = null; }
  43494. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43495. if (!defines.isDirty) {
  43496. return null;
  43497. }
  43498. defines.markAsProcessed();
  43499. var scene = this.getScene();
  43500. var engine = scene.getEngine();
  43501. // Fallbacks
  43502. var fallbacks = new BABYLON.EffectFallbacks();
  43503. var fallbackRank = 0;
  43504. if (defines.USESPHERICALINVERTEX) {
  43505. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43506. }
  43507. if (defines.FOG) {
  43508. fallbacks.addFallback(fallbackRank, "FOG");
  43509. }
  43510. if (defines.SPECULARAA) {
  43511. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43512. }
  43513. if (defines.POINTSIZE) {
  43514. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43515. }
  43516. if (defines.LOGARITHMICDEPTH) {
  43517. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43518. }
  43519. if (defines.PARALLAX) {
  43520. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43521. }
  43522. if (defines.PARALLAXOCCLUSION) {
  43523. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43524. }
  43525. if (defines.ENVIRONMENTBRDF) {
  43526. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43527. }
  43528. if (defines.TANGENT) {
  43529. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43530. }
  43531. if (defines.BUMP) {
  43532. fallbacks.addFallback(fallbackRank++, "BUMP");
  43533. }
  43534. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43535. if (defines.SPECULARTERM) {
  43536. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43537. }
  43538. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43539. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43540. }
  43541. if (defines.LIGHTMAP) {
  43542. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43543. }
  43544. if (defines.NORMAL) {
  43545. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43546. }
  43547. if (defines.AMBIENT) {
  43548. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43549. }
  43550. if (defines.EMISSIVE) {
  43551. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43552. }
  43553. if (defines.VERTEXCOLOR) {
  43554. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43555. }
  43556. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43557. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43558. }
  43559. if (defines.MORPHTARGETS) {
  43560. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43561. }
  43562. //Attributes
  43563. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43564. if (defines.NORMAL) {
  43565. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43566. }
  43567. if (defines.TANGENT) {
  43568. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43569. }
  43570. if (defines.UV1) {
  43571. attribs.push(BABYLON.VertexBuffer.UVKind);
  43572. }
  43573. if (defines.UV2) {
  43574. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43575. }
  43576. if (defines.VERTEXCOLOR) {
  43577. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43578. }
  43579. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43580. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43581. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43582. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43583. "vFogInfos", "vFogColor", "pointSize",
  43584. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43585. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43586. "mBones",
  43587. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43588. "vLightingIntensity",
  43589. "logarithmicDepthConstant",
  43590. "vSphericalX", "vSphericalY", "vSphericalZ",
  43591. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43592. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43593. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43594. "vTangentSpaceParams"
  43595. ];
  43596. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43597. "bumpSampler", "lightmapSampler", "opacitySampler",
  43598. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43599. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43600. "microSurfaceSampler", "environmentBrdfSampler"];
  43601. var uniformBuffers = ["Material", "Scene"];
  43602. if (BABYLON.ImageProcessingConfiguration) {
  43603. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43604. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43605. }
  43606. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43607. uniformsNames: uniforms,
  43608. uniformBuffersNames: uniformBuffers,
  43609. samplers: samplers,
  43610. defines: defines,
  43611. maxSimultaneousLights: this._maxSimultaneousLights
  43612. });
  43613. var join = defines.toString();
  43614. return engine.createEffect("pbr", {
  43615. attributes: attribs,
  43616. uniformsNames: uniforms,
  43617. uniformBuffersNames: uniformBuffers,
  43618. samplers: samplers,
  43619. defines: join,
  43620. fallbacks: fallbacks,
  43621. onCompiled: onCompiled,
  43622. onError: onError,
  43623. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43624. }, engine);
  43625. };
  43626. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43627. if (useInstances === void 0) { useInstances = null; }
  43628. if (useClipPlane === void 0) { useClipPlane = null; }
  43629. var scene = this.getScene();
  43630. var engine = scene.getEngine();
  43631. // Lights
  43632. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43633. defines._needNormals = true;
  43634. // Textures
  43635. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43636. if (defines._areTexturesDirty) {
  43637. defines._needUVs = false;
  43638. if (scene.texturesEnabled) {
  43639. if (scene.getEngine().getCaps().textureLOD) {
  43640. defines.LODBASEDMICROSFURACE = true;
  43641. }
  43642. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43643. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43644. }
  43645. else {
  43646. defines.ALBEDO = false;
  43647. }
  43648. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43649. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43650. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43651. }
  43652. else {
  43653. defines.AMBIENT = false;
  43654. }
  43655. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43657. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43658. }
  43659. else {
  43660. defines.OPACITY = false;
  43661. }
  43662. var reflectionTexture = this._getReflectionTexture();
  43663. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43664. defines.REFLECTION = true;
  43665. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43666. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43667. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43668. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43669. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43670. defines.INVERTCUBICMAP = true;
  43671. }
  43672. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43673. switch (reflectionTexture.coordinatesMode) {
  43674. case BABYLON.Texture.EXPLICIT_MODE:
  43675. defines.REFLECTIONMAP_EXPLICIT = true;
  43676. break;
  43677. case BABYLON.Texture.PLANAR_MODE:
  43678. defines.REFLECTIONMAP_PLANAR = true;
  43679. break;
  43680. case BABYLON.Texture.PROJECTION_MODE:
  43681. defines.REFLECTIONMAP_PROJECTION = true;
  43682. break;
  43683. case BABYLON.Texture.SKYBOX_MODE:
  43684. defines.REFLECTIONMAP_SKYBOX = true;
  43685. break;
  43686. case BABYLON.Texture.SPHERICAL_MODE:
  43687. defines.REFLECTIONMAP_SPHERICAL = true;
  43688. break;
  43689. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43690. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43691. break;
  43692. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43693. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43694. break;
  43695. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43696. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43697. break;
  43698. case BABYLON.Texture.CUBIC_MODE:
  43699. case BABYLON.Texture.INVCUBIC_MODE:
  43700. default:
  43701. defines.REFLECTIONMAP_CUBIC = true;
  43702. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43703. break;
  43704. }
  43705. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43706. if (reflectionTexture.sphericalPolynomial) {
  43707. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43708. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43709. defines.USESPHERICALINVERTEX = false;
  43710. }
  43711. else {
  43712. defines.USESPHERICALINVERTEX = true;
  43713. }
  43714. }
  43715. }
  43716. }
  43717. else {
  43718. defines.REFLECTION = false;
  43719. defines.REFLECTIONMAP_3D = false;
  43720. defines.REFLECTIONMAP_SPHERICAL = false;
  43721. defines.REFLECTIONMAP_PLANAR = false;
  43722. defines.REFLECTIONMAP_CUBIC = false;
  43723. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43724. defines.REFLECTIONMAP_PROJECTION = false;
  43725. defines.REFLECTIONMAP_SKYBOX = false;
  43726. defines.REFLECTIONMAP_EXPLICIT = false;
  43727. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43728. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43729. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43730. defines.INVERTCUBICMAP = false;
  43731. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43732. defines.USESPHERICALINVERTEX = false;
  43733. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43734. defines.LODINREFLECTIONALPHA = false;
  43735. defines.GAMMAREFLECTION = false;
  43736. defines.RGBDREFLECTION = false;
  43737. }
  43738. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43739. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43740. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43741. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43742. }
  43743. else {
  43744. defines.LIGHTMAP = false;
  43745. }
  43746. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43748. }
  43749. else {
  43750. defines.EMISSIVE = false;
  43751. }
  43752. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43753. if (this._metallicTexture) {
  43754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43755. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43756. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43757. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43758. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43759. }
  43760. else if (this._reflectivityTexture) {
  43761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43762. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43763. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43764. }
  43765. else {
  43766. defines.REFLECTIVITY = false;
  43767. }
  43768. if (this._microSurfaceTexture) {
  43769. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43770. }
  43771. else {
  43772. defines.MICROSURFACEMAP = false;
  43773. }
  43774. }
  43775. else {
  43776. defines.REFLECTIVITY = false;
  43777. defines.MICROSURFACEMAP = false;
  43778. }
  43779. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43780. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43781. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43782. defines.PARALLAX = true;
  43783. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43784. }
  43785. else {
  43786. defines.PARALLAX = false;
  43787. }
  43788. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43789. }
  43790. else {
  43791. defines.BUMP = false;
  43792. }
  43793. var refractionTexture = this._getRefractionTexture();
  43794. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43795. defines.REFRACTION = true;
  43796. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43797. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43798. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  43799. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43800. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43801. if (this._linkRefractionWithTransparency) {
  43802. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43803. }
  43804. }
  43805. else {
  43806. defines.REFRACTION = false;
  43807. }
  43808. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43809. defines.ENVIRONMENTBRDF = true;
  43810. }
  43811. else {
  43812. defines.ENVIRONMENTBRDF = false;
  43813. }
  43814. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43815. defines.ALPHAFROMALBEDO = true;
  43816. }
  43817. else {
  43818. defines.ALPHAFROMALBEDO = false;
  43819. }
  43820. }
  43821. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43822. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43823. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43824. if (!this.backFaceCulling && this._twoSidedLighting) {
  43825. defines.TWOSIDEDLIGHTING = true;
  43826. }
  43827. else {
  43828. defines.TWOSIDEDLIGHTING = false;
  43829. }
  43830. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43831. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43832. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43833. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43834. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43835. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43836. }
  43837. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43838. this._imageProcessingConfiguration.prepareDefines(defines);
  43839. }
  43840. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43841. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43842. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43843. // Misc.
  43844. if (defines._areMiscDirty) {
  43845. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43846. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43847. }
  43848. // Values that need to be evaluated on every frame
  43849. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43850. // Attribs
  43851. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43852. };
  43853. /**
  43854. * Force shader compilation
  43855. */
  43856. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43857. var _this = this;
  43858. var localOptions = __assign({ clipPlane: false }, options);
  43859. var defines = new PBRMaterialDefines();
  43860. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43861. if (effect.isReady()) {
  43862. if (onCompiled) {
  43863. onCompiled(this);
  43864. }
  43865. }
  43866. else {
  43867. effect.onCompileObservable.add(function () {
  43868. if (onCompiled) {
  43869. onCompiled(_this);
  43870. }
  43871. });
  43872. }
  43873. };
  43874. /**
  43875. * Initializes the uniform buffer layout for the shader.
  43876. */
  43877. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  43878. // Order is important !
  43879. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  43880. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  43881. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43882. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43883. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43884. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  43885. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  43886. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43887. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43888. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43889. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43890. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43891. this._uniformBuffer.addUniform("albedoMatrix", 16);
  43892. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43893. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43894. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43895. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43896. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  43897. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  43898. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43899. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43900. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43901. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43902. this._uniformBuffer.addUniform("vReflectionColor", 3);
  43903. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  43904. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  43905. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  43906. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  43907. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  43908. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43909. this._uniformBuffer.addUniform("pointSize", 1);
  43910. this._uniformBuffer.create();
  43911. };
  43912. /**
  43913. * Unbinds the textures.
  43914. */
  43915. PBRBaseMaterial.prototype.unbind = function () {
  43916. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43917. this._uniformBuffer.setTexture("reflectionSampler", null);
  43918. }
  43919. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43920. this._uniformBuffer.setTexture("refractionSampler", null);
  43921. }
  43922. _super.prototype.unbind.call(this);
  43923. };
  43924. /**
  43925. * Binds the submesh data.
  43926. * @param world - The world matrix.
  43927. * @param mesh - The BJS mesh.
  43928. * @param subMesh - A submesh of the BJS mesh.
  43929. */
  43930. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43931. var scene = this.getScene();
  43932. var defines = subMesh._materialDefines;
  43933. if (!defines) {
  43934. return;
  43935. }
  43936. var effect = subMesh.effect;
  43937. if (!effect) {
  43938. return;
  43939. }
  43940. this._activeEffect = effect;
  43941. // Matrices
  43942. this.bindOnlyWorldMatrix(world);
  43943. // Normal Matrix
  43944. if (defines.OBJECTSPACE_NORMALMAP) {
  43945. world.toNormalMatrix(this._normalMatrix);
  43946. this.bindOnlyNormalMatrix(this._normalMatrix);
  43947. }
  43948. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43949. // Bones
  43950. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  43951. var reflectionTexture = null;
  43952. if (mustRebind) {
  43953. this._uniformBuffer.bindToEffect(effect, "Material");
  43954. this.bindViewProjection(effect);
  43955. reflectionTexture = this._getReflectionTexture();
  43956. var refractionTexture = this._getRefractionTexture();
  43957. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43958. // Texture uniforms
  43959. if (scene.texturesEnabled) {
  43960. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43961. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  43962. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  43963. }
  43964. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43965. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  43966. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43967. }
  43968. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43969. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43970. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43971. }
  43972. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43973. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  43974. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  43975. if (reflectionTexture.boundingBoxSize) {
  43976. var cubeTexture = reflectionTexture;
  43977. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43978. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43979. }
  43980. var polynomials = reflectionTexture.sphericalPolynomial;
  43981. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  43982. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  43983. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  43984. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  43985. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  43986. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  43987. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  43988. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  43989. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  43990. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  43991. }
  43992. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  43993. }
  43994. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43995. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43996. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43997. }
  43998. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43999. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44000. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44001. }
  44002. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44003. if (this._metallicTexture) {
  44004. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44005. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44006. }
  44007. else if (this._reflectivityTexture) {
  44008. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44009. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44010. }
  44011. if (this._microSurfaceTexture) {
  44012. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44013. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44014. }
  44015. }
  44016. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44017. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44018. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44019. if (scene._mirroredCameraPosition) {
  44020. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44021. }
  44022. else {
  44023. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44024. }
  44025. }
  44026. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44027. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44028. var depth = 1.0;
  44029. if (!refractionTexture.isCube) {
  44030. if (refractionTexture.depth) {
  44031. depth = refractionTexture.depth;
  44032. }
  44033. }
  44034. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44035. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44036. }
  44037. }
  44038. // Point size
  44039. if (this.pointsCloud) {
  44040. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44041. }
  44042. // Colors
  44043. if (defines.METALLICWORKFLOW) {
  44044. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44045. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44046. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44047. }
  44048. else {
  44049. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44050. }
  44051. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44052. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44053. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44054. // Misc
  44055. this._lightingInfos.x = this._directIntensity;
  44056. this._lightingInfos.y = this._emissiveIntensity;
  44057. this._lightingInfos.z = this._environmentIntensity;
  44058. this._lightingInfos.w = this._specularIntensity;
  44059. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44060. }
  44061. // Textures
  44062. if (scene.texturesEnabled) {
  44063. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44064. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44065. }
  44066. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44067. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44068. }
  44069. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44070. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44071. }
  44072. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44073. if (defines.LODBASEDMICROSFURACE) {
  44074. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44075. }
  44076. else {
  44077. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44078. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44079. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44080. }
  44081. }
  44082. if (defines.ENVIRONMENTBRDF) {
  44083. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44084. }
  44085. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44086. if (defines.LODBASEDMICROSFURACE) {
  44087. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44088. }
  44089. else {
  44090. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44091. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44092. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44093. }
  44094. }
  44095. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44096. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44097. }
  44098. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44099. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44100. }
  44101. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44102. if (this._metallicTexture) {
  44103. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44104. }
  44105. else if (this._reflectivityTexture) {
  44106. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44107. }
  44108. if (this._microSurfaceTexture) {
  44109. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44110. }
  44111. }
  44112. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44113. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44114. }
  44115. }
  44116. // Clip plane
  44117. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44118. // Colors
  44119. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44120. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44121. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44122. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44123. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44124. }
  44125. if (mustRebind || !this.isFrozen) {
  44126. // Lights
  44127. if (scene.lightsEnabled && !this._disableLighting) {
  44128. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44129. }
  44130. // View
  44131. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44132. this.bindView(effect);
  44133. }
  44134. // Fog
  44135. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44136. // Morph targets
  44137. if (defines.NUM_MORPH_INFLUENCERS) {
  44138. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44139. }
  44140. // image processing
  44141. this._imageProcessingConfiguration.bind(this._activeEffect);
  44142. // Log. depth
  44143. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44144. }
  44145. this._uniformBuffer.update();
  44146. this._afterBind(mesh, this._activeEffect);
  44147. };
  44148. /**
  44149. * Returns the animatable textures.
  44150. * @returns - Array of animatable textures.
  44151. */
  44152. PBRBaseMaterial.prototype.getAnimatables = function () {
  44153. var results = [];
  44154. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44155. results.push(this._albedoTexture);
  44156. }
  44157. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44158. results.push(this._ambientTexture);
  44159. }
  44160. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44161. results.push(this._opacityTexture);
  44162. }
  44163. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44164. results.push(this._reflectionTexture);
  44165. }
  44166. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44167. results.push(this._emissiveTexture);
  44168. }
  44169. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44170. results.push(this._metallicTexture);
  44171. }
  44172. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44173. results.push(this._reflectivityTexture);
  44174. }
  44175. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44176. results.push(this._bumpTexture);
  44177. }
  44178. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44179. results.push(this._lightmapTexture);
  44180. }
  44181. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44182. results.push(this._refractionTexture);
  44183. }
  44184. return results;
  44185. };
  44186. /**
  44187. * Returns the texture used for reflections.
  44188. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44189. */
  44190. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44191. if (this._reflectionTexture) {
  44192. return this._reflectionTexture;
  44193. }
  44194. return this.getScene().environmentTexture;
  44195. };
  44196. /**
  44197. * Returns the texture used for refraction or null if none is used.
  44198. * @returns - Refection texture if present. If no refraction texture and refraction
  44199. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44200. */
  44201. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44202. if (this._refractionTexture) {
  44203. return this._refractionTexture;
  44204. }
  44205. if (this._linkRefractionWithTransparency) {
  44206. return this.getScene().environmentTexture;
  44207. }
  44208. return null;
  44209. };
  44210. /**
  44211. * Disposes the resources of the material.
  44212. * @param forceDisposeEffect - Forces the disposal of effects.
  44213. * @param forceDisposeTextures - Forces the disposal of all textures.
  44214. */
  44215. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44216. if (forceDisposeTextures) {
  44217. if (this._albedoTexture) {
  44218. this._albedoTexture.dispose();
  44219. }
  44220. if (this._ambientTexture) {
  44221. this._ambientTexture.dispose();
  44222. }
  44223. if (this._opacityTexture) {
  44224. this._opacityTexture.dispose();
  44225. }
  44226. if (this._reflectionTexture) {
  44227. this._reflectionTexture.dispose();
  44228. }
  44229. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44230. this._environmentBRDFTexture.dispose();
  44231. }
  44232. if (this._emissiveTexture) {
  44233. this._emissiveTexture.dispose();
  44234. }
  44235. if (this._metallicTexture) {
  44236. this._metallicTexture.dispose();
  44237. }
  44238. if (this._reflectivityTexture) {
  44239. this._reflectivityTexture.dispose();
  44240. }
  44241. if (this._bumpTexture) {
  44242. this._bumpTexture.dispose();
  44243. }
  44244. if (this._lightmapTexture) {
  44245. this._lightmapTexture.dispose();
  44246. }
  44247. if (this._refractionTexture) {
  44248. this._refractionTexture.dispose();
  44249. }
  44250. }
  44251. this._renderTargets.dispose();
  44252. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44253. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44254. }
  44255. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44256. };
  44257. /**
  44258. * Stores the reflectivity values based on metallic roughness workflow.
  44259. */
  44260. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44261. __decorate([
  44262. BABYLON.serializeAsImageProcessingConfiguration()
  44263. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44264. __decorate([
  44265. BABYLON.serialize()
  44266. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44267. __decorate([
  44268. BABYLON.serialize()
  44269. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44270. return PBRBaseMaterial;
  44271. }(BABYLON.PushMaterial));
  44272. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44273. })(BABYLON || (BABYLON = {}));
  44274. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44275. var BABYLON;
  44276. (function (BABYLON) {
  44277. /**
  44278. * The Physically based simple base material of BJS.
  44279. *
  44280. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44281. * It is used as the base class for both the specGloss and metalRough conventions.
  44282. */
  44283. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44284. __extends(PBRBaseSimpleMaterial, _super);
  44285. /**
  44286. * Instantiates a new PBRMaterial instance.
  44287. *
  44288. * @param name The material name
  44289. * @param scene The scene the material will be use in.
  44290. */
  44291. function PBRBaseSimpleMaterial(name, scene) {
  44292. var _this = _super.call(this, name, scene) || this;
  44293. /**
  44294. * Number of Simultaneous lights allowed on the material.
  44295. */
  44296. _this.maxSimultaneousLights = 4;
  44297. /**
  44298. * If sets to true, disables all the lights affecting the material.
  44299. */
  44300. _this.disableLighting = false;
  44301. /**
  44302. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44303. */
  44304. _this.invertNormalMapX = false;
  44305. /**
  44306. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44307. */
  44308. _this.invertNormalMapY = false;
  44309. /**
  44310. * Emissivie color used to self-illuminate the model.
  44311. */
  44312. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44313. /**
  44314. * Occlusion Channel Strenght.
  44315. */
  44316. _this.occlusionStrength = 1.0;
  44317. _this.useLightmapAsShadowmap = false;
  44318. _this._useAlphaFromAlbedoTexture = true;
  44319. _this._useAmbientInGrayScale = true;
  44320. return _this;
  44321. }
  44322. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44323. /**
  44324. * Gets the current double sided mode.
  44325. */
  44326. get: function () {
  44327. return this._twoSidedLighting;
  44328. },
  44329. /**
  44330. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44331. */
  44332. set: function (value) {
  44333. if (this._twoSidedLighting === value) {
  44334. return;
  44335. }
  44336. this._twoSidedLighting = value;
  44337. this.backFaceCulling = !value;
  44338. this._markAllSubMeshesAsTexturesDirty();
  44339. },
  44340. enumerable: true,
  44341. configurable: true
  44342. });
  44343. /**
  44344. * Return the active textures of the material.
  44345. */
  44346. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44347. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44348. if (this.environmentTexture) {
  44349. activeTextures.push(this.environmentTexture);
  44350. }
  44351. if (this.normalTexture) {
  44352. activeTextures.push(this.normalTexture);
  44353. }
  44354. if (this.emissiveTexture) {
  44355. activeTextures.push(this.emissiveTexture);
  44356. }
  44357. if (this.occlusionTexture) {
  44358. activeTextures.push(this.occlusionTexture);
  44359. }
  44360. if (this.lightmapTexture) {
  44361. activeTextures.push(this.lightmapTexture);
  44362. }
  44363. return activeTextures;
  44364. };
  44365. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44366. if (_super.prototype.hasTexture.call(this, texture)) {
  44367. return true;
  44368. }
  44369. if (this.lightmapTexture === texture) {
  44370. return true;
  44371. }
  44372. return false;
  44373. };
  44374. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44375. return "PBRBaseSimpleMaterial";
  44376. };
  44377. __decorate([
  44378. BABYLON.serialize(),
  44379. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44380. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44381. __decorate([
  44382. BABYLON.serialize(),
  44383. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44384. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44385. __decorate([
  44386. BABYLON.serializeAsTexture(),
  44387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44388. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44389. __decorate([
  44390. BABYLON.serialize(),
  44391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44392. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44393. __decorate([
  44394. BABYLON.serialize(),
  44395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44396. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44397. __decorate([
  44398. BABYLON.serializeAsTexture(),
  44399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44400. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44401. __decorate([
  44402. BABYLON.serializeAsColor3("emissive"),
  44403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44404. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44405. __decorate([
  44406. BABYLON.serializeAsTexture(),
  44407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44408. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44409. __decorate([
  44410. BABYLON.serialize(),
  44411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44412. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44413. __decorate([
  44414. BABYLON.serializeAsTexture(),
  44415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44416. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44417. __decorate([
  44418. BABYLON.serialize(),
  44419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44420. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44421. __decorate([
  44422. BABYLON.serialize()
  44423. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44424. __decorate([
  44425. BABYLON.serializeAsTexture(),
  44426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44427. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44428. __decorate([
  44429. BABYLON.serialize(),
  44430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44431. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44432. return PBRBaseSimpleMaterial;
  44433. }(BABYLON.PBRBaseMaterial));
  44434. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44435. })(BABYLON || (BABYLON = {}));
  44436. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44437. var BABYLON;
  44438. (function (BABYLON) {
  44439. /**
  44440. * The Physically based material of BJS.
  44441. *
  44442. * This offers the main features of a standard PBR material.
  44443. * For more information, please refer to the documentation :
  44444. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44445. */
  44446. var PBRMaterial = /** @class */ (function (_super) {
  44447. __extends(PBRMaterial, _super);
  44448. /**
  44449. * Instantiates a new PBRMaterial instance.
  44450. *
  44451. * @param name The material name
  44452. * @param scene The scene the material will be use in.
  44453. */
  44454. function PBRMaterial(name, scene) {
  44455. var _this = _super.call(this, name, scene) || this;
  44456. /**
  44457. * Intensity of the direct lights e.g. the four lights available in your scene.
  44458. * This impacts both the direct diffuse and specular highlights.
  44459. */
  44460. _this.directIntensity = 1.0;
  44461. /**
  44462. * Intensity of the emissive part of the material.
  44463. * This helps controlling the emissive effect without modifying the emissive color.
  44464. */
  44465. _this.emissiveIntensity = 1.0;
  44466. /**
  44467. * Intensity of the environment e.g. how much the environment will light the object
  44468. * either through harmonics for rough material or through the refelction for shiny ones.
  44469. */
  44470. _this.environmentIntensity = 1.0;
  44471. /**
  44472. * This is a special control allowing the reduction of the specular highlights coming from the
  44473. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44474. */
  44475. _this.specularIntensity = 1.0;
  44476. /**
  44477. * Debug Control allowing disabling the bump map on this material.
  44478. */
  44479. _this.disableBumpMap = false;
  44480. /**
  44481. * AKA Occlusion Texture Intensity in other nomenclature.
  44482. */
  44483. _this.ambientTextureStrength = 1.0;
  44484. /**
  44485. * The color of a material in ambient lighting.
  44486. */
  44487. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44488. /**
  44489. * AKA Diffuse Color in other nomenclature.
  44490. */
  44491. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44492. /**
  44493. * AKA Specular Color in other nomenclature.
  44494. */
  44495. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44496. /**
  44497. * The color reflected from the material.
  44498. */
  44499. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44500. /**
  44501. * The color emitted from the material.
  44502. */
  44503. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44504. /**
  44505. * AKA Glossiness in other nomenclature.
  44506. */
  44507. _this.microSurface = 1.0;
  44508. /**
  44509. * source material index of refraction (IOR)' / 'destination material IOR.
  44510. */
  44511. _this.indexOfRefraction = 0.66;
  44512. /**
  44513. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44514. */
  44515. _this.invertRefractionY = false;
  44516. /**
  44517. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44518. * Materials half opaque for instance using refraction could benefit from this control.
  44519. */
  44520. _this.linkRefractionWithTransparency = false;
  44521. _this.useLightmapAsShadowmap = false;
  44522. /**
  44523. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44524. */
  44525. _this.useAlphaFromAlbedoTexture = false;
  44526. /**
  44527. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44528. */
  44529. _this.forceAlphaTest = false;
  44530. /**
  44531. * Defines the alpha limits in alpha test mode.
  44532. */
  44533. _this.alphaCutOff = 0.4;
  44534. /**
  44535. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44536. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44537. */
  44538. _this.useSpecularOverAlpha = true;
  44539. /**
  44540. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44541. */
  44542. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44543. /**
  44544. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44545. */
  44546. _this.useRoughnessFromMetallicTextureAlpha = true;
  44547. /**
  44548. * Specifies if the metallic texture contains the roughness information in its green channel.
  44549. */
  44550. _this.useRoughnessFromMetallicTextureGreen = false;
  44551. /**
  44552. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44553. */
  44554. _this.useMetallnessFromMetallicTextureBlue = false;
  44555. /**
  44556. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44557. */
  44558. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44559. /**
  44560. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44561. */
  44562. _this.useAmbientInGrayScale = false;
  44563. /**
  44564. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44565. * The material will try to infer what glossiness each pixel should be.
  44566. */
  44567. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44568. /**
  44569. * BJS is using an harcoded light falloff based on a manually sets up range.
  44570. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44571. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44572. */
  44573. _this.usePhysicalLightFalloff = true;
  44574. /**
  44575. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44576. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44577. */
  44578. _this.useRadianceOverAlpha = true;
  44579. /**
  44580. * Allows using an object space normal map (instead of tangent space).
  44581. */
  44582. _this.useObjectSpaceNormalMap = false;
  44583. /**
  44584. * Allows using the bump map in parallax mode.
  44585. */
  44586. _this.useParallax = false;
  44587. /**
  44588. * Allows using the bump map in parallax occlusion mode.
  44589. */
  44590. _this.useParallaxOcclusion = false;
  44591. /**
  44592. * Controls the scale bias of the parallax mode.
  44593. */
  44594. _this.parallaxScaleBias = 0.05;
  44595. /**
  44596. * If sets to true, disables all the lights affecting the material.
  44597. */
  44598. _this.disableLighting = false;
  44599. /**
  44600. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44601. */
  44602. _this.forceIrradianceInFragment = false;
  44603. /**
  44604. * Number of Simultaneous lights allowed on the material.
  44605. */
  44606. _this.maxSimultaneousLights = 4;
  44607. /**
  44608. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44609. */
  44610. _this.invertNormalMapX = false;
  44611. /**
  44612. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44613. */
  44614. _this.invertNormalMapY = false;
  44615. /**
  44616. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44617. */
  44618. _this.twoSidedLighting = false;
  44619. /**
  44620. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44621. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44622. */
  44623. _this.useAlphaFresnel = false;
  44624. /**
  44625. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44626. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44627. */
  44628. _this.useLinearAlphaFresnel = false;
  44629. /**
  44630. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44631. * And/Or occlude the blended part.
  44632. */
  44633. _this.environmentBRDFTexture = null;
  44634. /**
  44635. * Force normal to face away from face.
  44636. */
  44637. _this.forceNormalForward = false;
  44638. /**
  44639. * Enables specular anti aliasing in the PBR shader.
  44640. * It will both interacts on the Geometry for analytical and IBL lighting.
  44641. * It also prefilter the roughness map based on the bump values.
  44642. */
  44643. _this.enableSpecularAntiAliasing = false;
  44644. /**
  44645. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44646. * makes the reflect vector face the model (under horizon).
  44647. */
  44648. _this.useHorizonOcclusion = true;
  44649. /**
  44650. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44651. * too much the area relying on ambient texture to define their ambient occlusion.
  44652. */
  44653. _this.useRadianceOcclusion = true;
  44654. /**
  44655. * If set to true, no lighting calculations will be applied.
  44656. */
  44657. _this.unlit = false;
  44658. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44659. return _this;
  44660. }
  44661. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44662. /**
  44663. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44664. */
  44665. get: function () {
  44666. return this._PBRMATERIAL_OPAQUE;
  44667. },
  44668. enumerable: true,
  44669. configurable: true
  44670. });
  44671. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44672. /**
  44673. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44674. */
  44675. get: function () {
  44676. return this._PBRMATERIAL_ALPHATEST;
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44682. /**
  44683. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44684. */
  44685. get: function () {
  44686. return this._PBRMATERIAL_ALPHABLEND;
  44687. },
  44688. enumerable: true,
  44689. configurable: true
  44690. });
  44691. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44692. /**
  44693. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44694. * They are also discarded below the alpha cutoff threshold to improve performances.
  44695. */
  44696. get: function () {
  44697. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44698. },
  44699. enumerable: true,
  44700. configurable: true
  44701. });
  44702. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44703. /**
  44704. * Gets the image processing configuration used either in this material.
  44705. */
  44706. get: function () {
  44707. return this._imageProcessingConfiguration;
  44708. },
  44709. /**
  44710. * Sets the Default image processing configuration used either in the this material.
  44711. *
  44712. * If sets to null, the scene one is in use.
  44713. */
  44714. set: function (value) {
  44715. this._attachImageProcessingConfiguration(value);
  44716. // Ensure the effect will be rebuilt.
  44717. this._markAllSubMeshesAsTexturesDirty();
  44718. },
  44719. enumerable: true,
  44720. configurable: true
  44721. });
  44722. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44723. /**
  44724. * Gets wether the color curves effect is enabled.
  44725. */
  44726. get: function () {
  44727. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44728. },
  44729. /**
  44730. * Sets wether the color curves effect is enabled.
  44731. */
  44732. set: function (value) {
  44733. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44734. },
  44735. enumerable: true,
  44736. configurable: true
  44737. });
  44738. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44739. /**
  44740. * Gets wether the color grading effect is enabled.
  44741. */
  44742. get: function () {
  44743. return this.imageProcessingConfiguration.colorGradingEnabled;
  44744. },
  44745. /**
  44746. * Gets wether the color grading effect is enabled.
  44747. */
  44748. set: function (value) {
  44749. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44750. },
  44751. enumerable: true,
  44752. configurable: true
  44753. });
  44754. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44755. /**
  44756. * Gets wether tonemapping is enabled or not.
  44757. */
  44758. get: function () {
  44759. return this._imageProcessingConfiguration.toneMappingEnabled;
  44760. },
  44761. /**
  44762. * Sets wether tonemapping is enabled or not
  44763. */
  44764. set: function (value) {
  44765. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44766. },
  44767. enumerable: true,
  44768. configurable: true
  44769. });
  44770. ;
  44771. ;
  44772. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44773. /**
  44774. * The camera exposure used on this material.
  44775. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44776. * This corresponds to a photographic exposure.
  44777. */
  44778. get: function () {
  44779. return this._imageProcessingConfiguration.exposure;
  44780. },
  44781. /**
  44782. * The camera exposure used on this material.
  44783. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44784. * This corresponds to a photographic exposure.
  44785. */
  44786. set: function (value) {
  44787. this._imageProcessingConfiguration.exposure = value;
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. ;
  44793. ;
  44794. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44795. /**
  44796. * Gets The camera contrast used on this material.
  44797. */
  44798. get: function () {
  44799. return this._imageProcessingConfiguration.contrast;
  44800. },
  44801. /**
  44802. * Sets The camera contrast used on this material.
  44803. */
  44804. set: function (value) {
  44805. this._imageProcessingConfiguration.contrast = value;
  44806. },
  44807. enumerable: true,
  44808. configurable: true
  44809. });
  44810. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44811. /**
  44812. * Gets the Color Grading 2D Lookup Texture.
  44813. */
  44814. get: function () {
  44815. return this._imageProcessingConfiguration.colorGradingTexture;
  44816. },
  44817. /**
  44818. * Sets the Color Grading 2D Lookup Texture.
  44819. */
  44820. set: function (value) {
  44821. this._imageProcessingConfiguration.colorGradingTexture = value;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44827. /**
  44828. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44829. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44830. * 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;
  44831. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44832. */
  44833. get: function () {
  44834. return this._imageProcessingConfiguration.colorCurves;
  44835. },
  44836. /**
  44837. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44838. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44839. * 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;
  44840. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44841. */
  44842. set: function (value) {
  44843. this._imageProcessingConfiguration.colorCurves = value;
  44844. },
  44845. enumerable: true,
  44846. configurable: true
  44847. });
  44848. /**
  44849. * Returns the name of this material class.
  44850. */
  44851. PBRMaterial.prototype.getClassName = function () {
  44852. return "PBRMaterial";
  44853. };
  44854. /**
  44855. * Returns an array of the actively used textures.
  44856. * @returns - Array of BaseTextures
  44857. */
  44858. PBRMaterial.prototype.getActiveTextures = function () {
  44859. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44860. if (this._albedoTexture) {
  44861. activeTextures.push(this._albedoTexture);
  44862. }
  44863. if (this._ambientTexture) {
  44864. activeTextures.push(this._ambientTexture);
  44865. }
  44866. if (this._opacityTexture) {
  44867. activeTextures.push(this._opacityTexture);
  44868. }
  44869. if (this._reflectionTexture) {
  44870. activeTextures.push(this._reflectionTexture);
  44871. }
  44872. if (this._emissiveTexture) {
  44873. activeTextures.push(this._emissiveTexture);
  44874. }
  44875. if (this._reflectivityTexture) {
  44876. activeTextures.push(this._reflectivityTexture);
  44877. }
  44878. if (this._metallicTexture) {
  44879. activeTextures.push(this._metallicTexture);
  44880. }
  44881. if (this._microSurfaceTexture) {
  44882. activeTextures.push(this._microSurfaceTexture);
  44883. }
  44884. if (this._bumpTexture) {
  44885. activeTextures.push(this._bumpTexture);
  44886. }
  44887. if (this._lightmapTexture) {
  44888. activeTextures.push(this._lightmapTexture);
  44889. }
  44890. if (this._refractionTexture) {
  44891. activeTextures.push(this._refractionTexture);
  44892. }
  44893. return activeTextures;
  44894. };
  44895. /**
  44896. * Checks to see if a texture is used in the material.
  44897. * @param texture - Base texture to use.
  44898. * @returns - Boolean specifying if a texture is used in the material.
  44899. */
  44900. PBRMaterial.prototype.hasTexture = function (texture) {
  44901. if (_super.prototype.hasTexture.call(this, texture)) {
  44902. return true;
  44903. }
  44904. if (this._albedoTexture === texture) {
  44905. return true;
  44906. }
  44907. if (this._ambientTexture === texture) {
  44908. return true;
  44909. }
  44910. if (this._opacityTexture === texture) {
  44911. return true;
  44912. }
  44913. if (this._reflectionTexture === texture) {
  44914. return true;
  44915. }
  44916. if (this._reflectivityTexture === texture) {
  44917. return true;
  44918. }
  44919. if (this._metallicTexture === texture) {
  44920. return true;
  44921. }
  44922. if (this._microSurfaceTexture === texture) {
  44923. return true;
  44924. }
  44925. if (this._bumpTexture === texture) {
  44926. return true;
  44927. }
  44928. if (this._lightmapTexture === texture) {
  44929. return true;
  44930. }
  44931. if (this._refractionTexture === texture) {
  44932. return true;
  44933. }
  44934. return false;
  44935. };
  44936. /**
  44937. * Makes a duplicate of the current material.
  44938. * @param name - name to use for the new material.
  44939. */
  44940. PBRMaterial.prototype.clone = function (name) {
  44941. var _this = this;
  44942. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  44943. clone.id = name;
  44944. clone.name = name;
  44945. return clone;
  44946. };
  44947. /**
  44948. * Serializes this PBR Material.
  44949. * @returns - An object with the serialized material.
  44950. */
  44951. PBRMaterial.prototype.serialize = function () {
  44952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44953. serializationObject.customType = "BABYLON.PBRMaterial";
  44954. return serializationObject;
  44955. };
  44956. // Statics
  44957. /**
  44958. * Parses a PBR Material from a serialized object.
  44959. * @param source - Serialized object.
  44960. * @param scene - BJS scene instance.
  44961. * @param rootUrl - url for the scene object
  44962. * @returns - PBRMaterial
  44963. */
  44964. PBRMaterial.Parse = function (source, scene, rootUrl) {
  44965. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  44966. };
  44967. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  44968. /**
  44969. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44970. */
  44971. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  44972. /**
  44973. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44974. */
  44975. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  44976. /**
  44977. * 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.
  44978. * They are also discarded below the alpha cutoff threshold to improve performances.
  44979. */
  44980. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  44981. __decorate([
  44982. BABYLON.serialize(),
  44983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44984. ], PBRMaterial.prototype, "directIntensity", void 0);
  44985. __decorate([
  44986. BABYLON.serialize(),
  44987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44988. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  44989. __decorate([
  44990. BABYLON.serialize(),
  44991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44992. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  44993. __decorate([
  44994. BABYLON.serialize(),
  44995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44996. ], PBRMaterial.prototype, "specularIntensity", void 0);
  44997. __decorate([
  44998. BABYLON.serialize(),
  44999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45000. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45001. __decorate([
  45002. BABYLON.serializeAsTexture(),
  45003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45004. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45005. __decorate([
  45006. BABYLON.serializeAsTexture(),
  45007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45008. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45009. __decorate([
  45010. BABYLON.serialize(),
  45011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45012. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45013. __decorate([
  45014. BABYLON.serializeAsTexture(),
  45015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45016. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45017. __decorate([
  45018. BABYLON.serializeAsTexture(),
  45019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45020. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45021. __decorate([
  45022. BABYLON.serializeAsTexture(),
  45023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45024. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45025. __decorate([
  45026. BABYLON.serializeAsTexture(),
  45027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45028. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45029. __decorate([
  45030. BABYLON.serializeAsTexture(),
  45031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45032. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45033. __decorate([
  45034. BABYLON.serialize(),
  45035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45036. ], PBRMaterial.prototype, "metallic", void 0);
  45037. __decorate([
  45038. BABYLON.serialize(),
  45039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45040. ], PBRMaterial.prototype, "roughness", void 0);
  45041. __decorate([
  45042. BABYLON.serializeAsTexture(),
  45043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45044. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45045. __decorate([
  45046. BABYLON.serializeAsTexture(),
  45047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45048. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45049. __decorate([
  45050. BABYLON.serializeAsTexture(),
  45051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45052. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45053. __decorate([
  45054. BABYLON.serializeAsTexture(),
  45055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45056. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45057. __decorate([
  45058. BABYLON.serializeAsColor3("ambient"),
  45059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45060. ], PBRMaterial.prototype, "ambientColor", void 0);
  45061. __decorate([
  45062. BABYLON.serializeAsColor3("albedo"),
  45063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45064. ], PBRMaterial.prototype, "albedoColor", void 0);
  45065. __decorate([
  45066. BABYLON.serializeAsColor3("reflectivity"),
  45067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45068. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45069. __decorate([
  45070. BABYLON.serializeAsColor3("reflection"),
  45071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45072. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45073. __decorate([
  45074. BABYLON.serializeAsColor3("emissive"),
  45075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45076. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45077. __decorate([
  45078. BABYLON.serialize(),
  45079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45080. ], PBRMaterial.prototype, "microSurface", void 0);
  45081. __decorate([
  45082. BABYLON.serialize(),
  45083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45084. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45085. __decorate([
  45086. BABYLON.serialize(),
  45087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45088. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45089. __decorate([
  45090. BABYLON.serialize(),
  45091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45092. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45093. __decorate([
  45094. BABYLON.serialize(),
  45095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45096. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45097. __decorate([
  45098. BABYLON.serialize(),
  45099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45100. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45101. __decorate([
  45102. BABYLON.serialize(),
  45103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45104. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45105. __decorate([
  45106. BABYLON.serialize(),
  45107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45108. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45109. __decorate([
  45110. BABYLON.serialize(),
  45111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45112. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45113. __decorate([
  45114. BABYLON.serialize(),
  45115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45116. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45117. __decorate([
  45118. BABYLON.serialize(),
  45119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45120. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45121. __decorate([
  45122. BABYLON.serialize(),
  45123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45124. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45125. __decorate([
  45126. BABYLON.serialize(),
  45127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45128. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45129. __decorate([
  45130. BABYLON.serialize(),
  45131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45132. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45133. __decorate([
  45134. BABYLON.serialize(),
  45135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45136. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45137. __decorate([
  45138. BABYLON.serialize(),
  45139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45140. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45141. __decorate([
  45142. BABYLON.serialize(),
  45143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45144. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45145. __decorate([
  45146. BABYLON.serialize(),
  45147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45148. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45149. __decorate([
  45150. BABYLON.serialize(),
  45151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45152. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45153. __decorate([
  45154. BABYLON.serialize(),
  45155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45156. ], PBRMaterial.prototype, "useParallax", void 0);
  45157. __decorate([
  45158. BABYLON.serialize(),
  45159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45160. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45161. __decorate([
  45162. BABYLON.serialize(),
  45163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45164. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45165. __decorate([
  45166. BABYLON.serialize(),
  45167. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45168. ], PBRMaterial.prototype, "disableLighting", void 0);
  45169. __decorate([
  45170. BABYLON.serialize(),
  45171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45172. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45173. __decorate([
  45174. BABYLON.serialize(),
  45175. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45176. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45177. __decorate([
  45178. BABYLON.serialize(),
  45179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45180. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45181. __decorate([
  45182. BABYLON.serialize(),
  45183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45184. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45185. __decorate([
  45186. BABYLON.serialize(),
  45187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45188. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45189. __decorate([
  45190. BABYLON.serialize(),
  45191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45192. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45193. __decorate([
  45194. BABYLON.serialize(),
  45195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45196. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45197. __decorate([
  45198. BABYLON.serializeAsTexture(),
  45199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45200. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45201. __decorate([
  45202. BABYLON.serialize(),
  45203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45204. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45205. __decorate([
  45206. BABYLON.serialize(),
  45207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45208. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45209. __decorate([
  45210. BABYLON.serialize(),
  45211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45212. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45213. __decorate([
  45214. BABYLON.serialize(),
  45215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45216. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45217. __decorate([
  45218. BABYLON.serialize(),
  45219. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45220. ], PBRMaterial.prototype, "unlit", void 0);
  45221. return PBRMaterial;
  45222. }(BABYLON.PBRBaseMaterial));
  45223. BABYLON.PBRMaterial = PBRMaterial;
  45224. })(BABYLON || (BABYLON = {}));
  45225. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45226. var BABYLON;
  45227. (function (BABYLON) {
  45228. /**
  45229. * The PBR material of BJS following the metal roughness convention.
  45230. *
  45231. * This fits to the PBR convention in the GLTF definition:
  45232. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45233. */
  45234. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45235. __extends(PBRMetallicRoughnessMaterial, _super);
  45236. /**
  45237. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45238. *
  45239. * @param name The material name
  45240. * @param scene The scene the material will be use in.
  45241. */
  45242. function PBRMetallicRoughnessMaterial(name, scene) {
  45243. var _this = _super.call(this, name, scene) || this;
  45244. _this._useRoughnessFromMetallicTextureAlpha = false;
  45245. _this._useRoughnessFromMetallicTextureGreen = true;
  45246. _this._useMetallnessFromMetallicTextureBlue = true;
  45247. _this.metallic = 1.0;
  45248. _this.roughness = 1.0;
  45249. return _this;
  45250. }
  45251. /**
  45252. * Return the currrent class name of the material.
  45253. */
  45254. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45255. return "PBRMetallicRoughnessMaterial";
  45256. };
  45257. /**
  45258. * Return the active textures of the material.
  45259. */
  45260. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45261. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45262. if (this.baseTexture) {
  45263. activeTextures.push(this.baseTexture);
  45264. }
  45265. if (this.metallicRoughnessTexture) {
  45266. activeTextures.push(this.metallicRoughnessTexture);
  45267. }
  45268. return activeTextures;
  45269. };
  45270. /**
  45271. * Checks to see if a texture is used in the material.
  45272. * @param texture - Base texture to use.
  45273. * @returns - Boolean specifying if a texture is used in the material.
  45274. */
  45275. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45276. if (_super.prototype.hasTexture.call(this, texture)) {
  45277. return true;
  45278. }
  45279. if (this.baseTexture === texture) {
  45280. return true;
  45281. }
  45282. if (this.metallicRoughnessTexture === texture) {
  45283. return true;
  45284. }
  45285. return false;
  45286. };
  45287. /**
  45288. * Makes a duplicate of the current material.
  45289. * @param name - name to use for the new material.
  45290. */
  45291. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45292. var _this = this;
  45293. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45294. clone.id = name;
  45295. clone.name = name;
  45296. return clone;
  45297. };
  45298. /**
  45299. * Serialize the material to a parsable JSON object.
  45300. */
  45301. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45303. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45304. return serializationObject;
  45305. };
  45306. /**
  45307. * Parses a JSON object correponding to the serialize function.
  45308. */
  45309. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45310. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45311. };
  45312. __decorate([
  45313. BABYLON.serializeAsColor3(),
  45314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45315. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45316. __decorate([
  45317. BABYLON.serializeAsTexture(),
  45318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45319. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45320. __decorate([
  45321. BABYLON.serialize(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45323. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45324. __decorate([
  45325. BABYLON.serialize(),
  45326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45327. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45328. __decorate([
  45329. BABYLON.serializeAsTexture(),
  45330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45331. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45332. return PBRMetallicRoughnessMaterial;
  45333. }(BABYLON.PBRBaseSimpleMaterial));
  45334. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45335. })(BABYLON || (BABYLON = {}));
  45336. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45337. var BABYLON;
  45338. (function (BABYLON) {
  45339. /**
  45340. * The PBR material of BJS following the specular glossiness convention.
  45341. *
  45342. * This fits to the PBR convention in the GLTF definition:
  45343. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45344. */
  45345. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45346. __extends(PBRSpecularGlossinessMaterial, _super);
  45347. /**
  45348. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45349. *
  45350. * @param name The material name
  45351. * @param scene The scene the material will be use in.
  45352. */
  45353. function PBRSpecularGlossinessMaterial(name, scene) {
  45354. var _this = _super.call(this, name, scene) || this;
  45355. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45356. return _this;
  45357. }
  45358. /**
  45359. * Return the currrent class name of the material.
  45360. */
  45361. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45362. return "PBRSpecularGlossinessMaterial";
  45363. };
  45364. /**
  45365. * Return the active textures of the material.
  45366. */
  45367. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45368. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45369. if (this.diffuseTexture) {
  45370. activeTextures.push(this.diffuseTexture);
  45371. }
  45372. if (this.specularGlossinessTexture) {
  45373. activeTextures.push(this.specularGlossinessTexture);
  45374. }
  45375. return activeTextures;
  45376. };
  45377. /**
  45378. * Checks to see if a texture is used in the material.
  45379. * @param texture - Base texture to use.
  45380. * @returns - Boolean specifying if a texture is used in the material.
  45381. */
  45382. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45383. if (_super.prototype.hasTexture.call(this, texture)) {
  45384. return true;
  45385. }
  45386. if (this.diffuseTexture === texture) {
  45387. return true;
  45388. }
  45389. if (this.specularGlossinessTexture === texture) {
  45390. return true;
  45391. }
  45392. return false;
  45393. };
  45394. /**
  45395. * Makes a duplicate of the current material.
  45396. * @param name - name to use for the new material.
  45397. */
  45398. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45399. var _this = this;
  45400. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45401. clone.id = name;
  45402. clone.name = name;
  45403. return clone;
  45404. };
  45405. /**
  45406. * Serialize the material to a parsable JSON object.
  45407. */
  45408. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45409. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45410. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45411. return serializationObject;
  45412. };
  45413. /**
  45414. * Parses a JSON object correponding to the serialize function.
  45415. */
  45416. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45417. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45418. };
  45419. __decorate([
  45420. BABYLON.serializeAsColor3("diffuse"),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45422. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsTexture(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45426. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45427. __decorate([
  45428. BABYLON.serializeAsColor3("specular"),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45430. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45434. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45435. __decorate([
  45436. BABYLON.serializeAsTexture(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45438. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45439. return PBRSpecularGlossinessMaterial;
  45440. }(BABYLON.PBRBaseSimpleMaterial));
  45441. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45442. })(BABYLON || (BABYLON = {}));
  45443. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45444. var BABYLON;
  45445. (function (BABYLON) {
  45446. BABYLON.CameraInputTypes = {};
  45447. var CameraInputsManager = /** @class */ (function () {
  45448. function CameraInputsManager(camera) {
  45449. this.attached = {};
  45450. this.camera = camera;
  45451. this.checkInputs = function () { };
  45452. }
  45453. /**
  45454. * Add an input method to a camera
  45455. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45456. * @param input camera input method
  45457. */
  45458. CameraInputsManager.prototype.add = function (input) {
  45459. var type = input.getSimpleName();
  45460. if (this.attached[type]) {
  45461. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45462. return;
  45463. }
  45464. this.attached[type] = input;
  45465. input.camera = this.camera;
  45466. //for checkInputs, we are dynamically creating a function
  45467. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45468. if (input.checkInputs) {
  45469. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45470. }
  45471. if (this.attachedElement) {
  45472. input.attachControl(this.attachedElement);
  45473. }
  45474. };
  45475. /**
  45476. * Remove a specific input method from a camera
  45477. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45478. * @param inputToRemove camera input method
  45479. */
  45480. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45481. for (var cam in this.attached) {
  45482. var input = this.attached[cam];
  45483. if (input === inputToRemove) {
  45484. input.detachControl(this.attachedElement);
  45485. input.camera = null;
  45486. delete this.attached[cam];
  45487. this.rebuildInputCheck();
  45488. }
  45489. }
  45490. };
  45491. CameraInputsManager.prototype.removeByType = function (inputType) {
  45492. for (var cam in this.attached) {
  45493. var input = this.attached[cam];
  45494. if (input.getClassName() === inputType) {
  45495. input.detachControl(this.attachedElement);
  45496. input.camera = null;
  45497. delete this.attached[cam];
  45498. this.rebuildInputCheck();
  45499. }
  45500. }
  45501. };
  45502. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45503. var current = this.checkInputs;
  45504. return function () {
  45505. current();
  45506. fn();
  45507. };
  45508. };
  45509. CameraInputsManager.prototype.attachInput = function (input) {
  45510. if (this.attachedElement) {
  45511. input.attachControl(this.attachedElement, this.noPreventDefault);
  45512. }
  45513. };
  45514. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45515. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45516. if (this.attachedElement) {
  45517. return;
  45518. }
  45519. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45520. this.attachedElement = element;
  45521. this.noPreventDefault = noPreventDefault;
  45522. for (var cam in this.attached) {
  45523. this.attached[cam].attachControl(element, noPreventDefault);
  45524. }
  45525. };
  45526. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45527. if (disconnect === void 0) { disconnect = false; }
  45528. if (this.attachedElement !== element) {
  45529. return;
  45530. }
  45531. for (var cam in this.attached) {
  45532. this.attached[cam].detachControl(element);
  45533. if (disconnect) {
  45534. this.attached[cam].camera = null;
  45535. }
  45536. }
  45537. this.attachedElement = null;
  45538. };
  45539. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45540. this.checkInputs = function () { };
  45541. for (var cam in this.attached) {
  45542. var input = this.attached[cam];
  45543. if (input.checkInputs) {
  45544. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45545. }
  45546. }
  45547. };
  45548. /**
  45549. * Remove all attached input methods from a camera
  45550. */
  45551. CameraInputsManager.prototype.clear = function () {
  45552. if (this.attachedElement) {
  45553. this.detachElement(this.attachedElement, true);
  45554. }
  45555. this.attached = {};
  45556. this.attachedElement = null;
  45557. this.checkInputs = function () { };
  45558. };
  45559. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45560. var inputs = {};
  45561. for (var cam in this.attached) {
  45562. var input = this.attached[cam];
  45563. var res = BABYLON.SerializationHelper.Serialize(input);
  45564. inputs[input.getClassName()] = res;
  45565. }
  45566. serializedCamera.inputsmgr = inputs;
  45567. };
  45568. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45569. var parsedInputs = parsedCamera.inputsmgr;
  45570. if (parsedInputs) {
  45571. this.clear();
  45572. for (var n in parsedInputs) {
  45573. var construct = BABYLON.CameraInputTypes[n];
  45574. if (construct) {
  45575. var parsedinput = parsedInputs[n];
  45576. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45577. this.add(input);
  45578. }
  45579. }
  45580. }
  45581. else {
  45582. //2016-03-08 this part is for managing backward compatibility
  45583. for (var n in this.attached) {
  45584. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45585. if (construct) {
  45586. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45587. this.remove(this.attached[n]);
  45588. this.add(input);
  45589. }
  45590. }
  45591. }
  45592. };
  45593. return CameraInputsManager;
  45594. }());
  45595. BABYLON.CameraInputsManager = CameraInputsManager;
  45596. })(BABYLON || (BABYLON = {}));
  45597. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45598. var BABYLON;
  45599. (function (BABYLON) {
  45600. var TargetCamera = /** @class */ (function (_super) {
  45601. __extends(TargetCamera, _super);
  45602. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45603. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45604. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45605. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45606. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45607. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45608. _this.speed = 2.0;
  45609. _this.noRotationConstraint = false;
  45610. _this.lockedTarget = null;
  45611. _this._currentTarget = BABYLON.Vector3.Zero();
  45612. _this._viewMatrix = BABYLON.Matrix.Zero();
  45613. _this._camMatrix = BABYLON.Matrix.Zero();
  45614. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45615. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45616. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45617. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45618. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45619. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45620. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45621. return _this;
  45622. }
  45623. TargetCamera.prototype.getFrontPosition = function (distance) {
  45624. this.getWorldMatrix();
  45625. var direction = this.getTarget().subtract(this.position);
  45626. direction.normalize();
  45627. direction.scaleInPlace(distance);
  45628. return this.globalPosition.add(direction);
  45629. };
  45630. TargetCamera.prototype._getLockedTargetPosition = function () {
  45631. if (!this.lockedTarget) {
  45632. return null;
  45633. }
  45634. if (this.lockedTarget.absolutePosition) {
  45635. this.lockedTarget.computeWorldMatrix();
  45636. }
  45637. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45638. };
  45639. TargetCamera.prototype.storeState = function () {
  45640. this._storedPosition = this.position.clone();
  45641. this._storedRotation = this.rotation.clone();
  45642. if (this.rotationQuaternion) {
  45643. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45644. }
  45645. return _super.prototype.storeState.call(this);
  45646. };
  45647. /**
  45648. * Restored camera state. You must call storeState() first
  45649. */
  45650. TargetCamera.prototype._restoreStateValues = function () {
  45651. if (!_super.prototype._restoreStateValues.call(this)) {
  45652. return false;
  45653. }
  45654. this.position = this._storedPosition.clone();
  45655. this.rotation = this._storedRotation.clone();
  45656. if (this.rotationQuaternion) {
  45657. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45658. }
  45659. this.cameraDirection.copyFromFloats(0, 0, 0);
  45660. this.cameraRotation.copyFromFloats(0, 0);
  45661. return true;
  45662. };
  45663. // Cache
  45664. TargetCamera.prototype._initCache = function () {
  45665. _super.prototype._initCache.call(this);
  45666. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45667. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45668. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45669. };
  45670. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45671. if (!ignoreParentClass) {
  45672. _super.prototype._updateCache.call(this);
  45673. }
  45674. var lockedTargetPosition = this._getLockedTargetPosition();
  45675. if (!lockedTargetPosition) {
  45676. this._cache.lockedTarget = null;
  45677. }
  45678. else {
  45679. if (!this._cache.lockedTarget) {
  45680. this._cache.lockedTarget = lockedTargetPosition.clone();
  45681. }
  45682. else {
  45683. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45684. }
  45685. }
  45686. this._cache.rotation.copyFrom(this.rotation);
  45687. if (this.rotationQuaternion)
  45688. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45689. };
  45690. // Synchronized
  45691. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45692. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45693. return false;
  45694. }
  45695. var lockedTargetPosition = this._getLockedTargetPosition();
  45696. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45697. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45698. };
  45699. // Methods
  45700. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45701. var engine = this.getEngine();
  45702. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45703. };
  45704. // Target
  45705. TargetCamera.prototype.setTarget = function (target) {
  45706. this.upVector.normalize();
  45707. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45708. this._camMatrix.invert();
  45709. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45710. var vDir = target.subtract(this.position);
  45711. if (vDir.x >= 0.0) {
  45712. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45713. }
  45714. else {
  45715. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45716. }
  45717. this.rotation.z = 0;
  45718. if (isNaN(this.rotation.x)) {
  45719. this.rotation.x = 0;
  45720. }
  45721. if (isNaN(this.rotation.y)) {
  45722. this.rotation.y = 0;
  45723. }
  45724. if (isNaN(this.rotation.z)) {
  45725. this.rotation.z = 0;
  45726. }
  45727. if (this.rotationQuaternion) {
  45728. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45729. }
  45730. };
  45731. /**
  45732. * Return the current target position of the camera. This value is expressed in local space.
  45733. */
  45734. TargetCamera.prototype.getTarget = function () {
  45735. return this._currentTarget;
  45736. };
  45737. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45738. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45739. };
  45740. TargetCamera.prototype._updatePosition = function () {
  45741. if (this.parent) {
  45742. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45743. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45744. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45745. return;
  45746. }
  45747. this.position.addInPlace(this.cameraDirection);
  45748. };
  45749. TargetCamera.prototype._checkInputs = function () {
  45750. var needToMove = this._decideIfNeedsToMove();
  45751. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45752. // Move
  45753. if (needToMove) {
  45754. this._updatePosition();
  45755. }
  45756. // Rotate
  45757. if (needToRotate) {
  45758. this.rotation.x += this.cameraRotation.x;
  45759. this.rotation.y += this.cameraRotation.y;
  45760. //rotate, if quaternion is set and rotation was used
  45761. if (this.rotationQuaternion) {
  45762. var len = this.rotation.lengthSquared();
  45763. if (len) {
  45764. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45765. }
  45766. }
  45767. if (!this.noRotationConstraint) {
  45768. var limit = (Math.PI / 2) * 0.95;
  45769. if (this.rotation.x > limit)
  45770. this.rotation.x = limit;
  45771. if (this.rotation.x < -limit)
  45772. this.rotation.x = -limit;
  45773. }
  45774. }
  45775. // Inertia
  45776. if (needToMove) {
  45777. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45778. this.cameraDirection.x = 0;
  45779. }
  45780. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45781. this.cameraDirection.y = 0;
  45782. }
  45783. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45784. this.cameraDirection.z = 0;
  45785. }
  45786. this.cameraDirection.scaleInPlace(this.inertia);
  45787. }
  45788. if (needToRotate) {
  45789. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45790. this.cameraRotation.x = 0;
  45791. }
  45792. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45793. this.cameraRotation.y = 0;
  45794. }
  45795. this.cameraRotation.scaleInPlace(this.inertia);
  45796. }
  45797. _super.prototype._checkInputs.call(this);
  45798. };
  45799. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45800. if (this.rotationQuaternion) {
  45801. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45802. }
  45803. else {
  45804. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45805. }
  45806. //update the up vector!
  45807. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45808. };
  45809. TargetCamera.prototype._getViewMatrix = function () {
  45810. if (this.lockedTarget) {
  45811. this.setTarget(this._getLockedTargetPosition());
  45812. }
  45813. // Compute
  45814. this._updateCameraRotationMatrix();
  45815. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45816. // Computing target and final matrix
  45817. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45818. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  45819. return this._viewMatrix;
  45820. };
  45821. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  45822. if (this.parent) {
  45823. var parentWorldMatrix = this.parent.getWorldMatrix();
  45824. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  45825. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  45826. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  45827. this._markSyncedWithParent();
  45828. }
  45829. else {
  45830. this._globalPosition.copyFrom(this.position);
  45831. this._globalCurrentTarget.copyFrom(target);
  45832. this._globalCurrentUpVector.copyFrom(up);
  45833. }
  45834. if (this.getScene().useRightHandedSystem) {
  45835. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45836. }
  45837. else {
  45838. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45839. }
  45840. };
  45841. /**
  45842. * @override
  45843. * Override Camera.createRigCamera
  45844. */
  45845. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45846. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45847. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45848. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45849. if (!this.rotationQuaternion) {
  45850. this.rotationQuaternion = new BABYLON.Quaternion();
  45851. }
  45852. rigCamera._cameraRigParams = {};
  45853. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45854. }
  45855. return rigCamera;
  45856. }
  45857. return null;
  45858. };
  45859. /**
  45860. * @override
  45861. * Override Camera._updateRigCameras
  45862. */
  45863. TargetCamera.prototype._updateRigCameras = function () {
  45864. var camLeft = this._rigCameras[0];
  45865. var camRight = this._rigCameras[1];
  45866. switch (this.cameraRigMode) {
  45867. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45868. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45869. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45871. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45872. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45873. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45874. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45875. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45876. camLeft.setTarget(this.getTarget());
  45877. camRight.setTarget(this.getTarget());
  45878. break;
  45879. case BABYLON.Camera.RIG_MODE_VR:
  45880. if (camLeft.rotationQuaternion) {
  45881. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45882. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45883. }
  45884. else {
  45885. camLeft.rotation.copyFrom(this.rotation);
  45886. camRight.rotation.copyFrom(this.rotation);
  45887. }
  45888. camLeft.position.copyFrom(this.position);
  45889. camRight.position.copyFrom(this.position);
  45890. break;
  45891. }
  45892. _super.prototype._updateRigCameras.call(this);
  45893. };
  45894. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  45895. if (!this._rigCamTransformMatrix) {
  45896. this._rigCamTransformMatrix = new BABYLON.Matrix();
  45897. }
  45898. var target = this.getTarget();
  45899. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  45900. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  45901. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  45902. };
  45903. TargetCamera.prototype.getClassName = function () {
  45904. return "TargetCamera";
  45905. };
  45906. __decorate([
  45907. BABYLON.serializeAsVector3()
  45908. ], TargetCamera.prototype, "rotation", void 0);
  45909. __decorate([
  45910. BABYLON.serialize()
  45911. ], TargetCamera.prototype, "speed", void 0);
  45912. __decorate([
  45913. BABYLON.serializeAsMeshReference("lockedTargetId")
  45914. ], TargetCamera.prototype, "lockedTarget", void 0);
  45915. return TargetCamera;
  45916. }(BABYLON.Camera));
  45917. BABYLON.TargetCamera = TargetCamera;
  45918. })(BABYLON || (BABYLON = {}));
  45919. //# sourceMappingURL=babylon.targetCamera.js.map
  45920. var BABYLON;
  45921. (function (BABYLON) {
  45922. var FreeCameraMouseInput = /** @class */ (function () {
  45923. function FreeCameraMouseInput(touchEnabled) {
  45924. if (touchEnabled === void 0) { touchEnabled = true; }
  45925. this.touchEnabled = touchEnabled;
  45926. this.buttons = [0, 1, 2];
  45927. this.angularSensibility = 2000.0;
  45928. this.previousPosition = null;
  45929. }
  45930. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  45931. var _this = this;
  45932. var engine = this.camera.getEngine();
  45933. if (!this._pointerInput) {
  45934. this._pointerInput = function (p, s) {
  45935. var evt = p.event;
  45936. if (engine.isInVRExclusivePointerMode) {
  45937. return;
  45938. }
  45939. if (!_this.touchEnabled && evt.pointerType === "touch") {
  45940. return;
  45941. }
  45942. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45943. return;
  45944. }
  45945. var srcElement = (evt.srcElement || evt.target);
  45946. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45947. try {
  45948. srcElement.setPointerCapture(evt.pointerId);
  45949. }
  45950. catch (e) {
  45951. //Nothing to do with the error. Execution will continue.
  45952. }
  45953. _this.previousPosition = {
  45954. x: evt.clientX,
  45955. y: evt.clientY
  45956. };
  45957. if (!noPreventDefault) {
  45958. evt.preventDefault();
  45959. element.focus();
  45960. }
  45961. }
  45962. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45963. try {
  45964. srcElement.releasePointerCapture(evt.pointerId);
  45965. }
  45966. catch (e) {
  45967. //Nothing to do with the error.
  45968. }
  45969. _this.previousPosition = null;
  45970. if (!noPreventDefault) {
  45971. evt.preventDefault();
  45972. }
  45973. }
  45974. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45975. if (!_this.previousPosition || engine.isPointerLock) {
  45976. return;
  45977. }
  45978. var offsetX = evt.clientX - _this.previousPosition.x;
  45979. if (_this.camera.getScene().useRightHandedSystem)
  45980. offsetX *= -1;
  45981. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45982. offsetX *= -1;
  45983. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45984. var offsetY = evt.clientY - _this.previousPosition.y;
  45985. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45986. _this.previousPosition = {
  45987. x: evt.clientX,
  45988. y: evt.clientY
  45989. };
  45990. if (!noPreventDefault) {
  45991. evt.preventDefault();
  45992. }
  45993. }
  45994. };
  45995. }
  45996. this._onMouseMove = function (evt) {
  45997. if (!engine.isPointerLock) {
  45998. return;
  45999. }
  46000. if (engine.isInVRExclusivePointerMode) {
  46001. return;
  46002. }
  46003. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46004. if (_this.camera.getScene().useRightHandedSystem)
  46005. offsetX *= -1;
  46006. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46007. offsetX *= -1;
  46008. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46009. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46010. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46011. _this.previousPosition = null;
  46012. if (!noPreventDefault) {
  46013. evt.preventDefault();
  46014. }
  46015. };
  46016. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46017. element.addEventListener("mousemove", this._onMouseMove, false);
  46018. };
  46019. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46020. if (this._observer && element) {
  46021. this.camera.getScene().onPointerObservable.remove(this._observer);
  46022. if (this._onMouseMove) {
  46023. element.removeEventListener("mousemove", this._onMouseMove);
  46024. }
  46025. this._observer = null;
  46026. this._onMouseMove = null;
  46027. this.previousPosition = null;
  46028. }
  46029. };
  46030. FreeCameraMouseInput.prototype.getClassName = function () {
  46031. return "FreeCameraMouseInput";
  46032. };
  46033. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46034. return "mouse";
  46035. };
  46036. __decorate([
  46037. BABYLON.serialize()
  46038. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46039. __decorate([
  46040. BABYLON.serialize()
  46041. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46042. return FreeCameraMouseInput;
  46043. }());
  46044. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46045. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46046. })(BABYLON || (BABYLON = {}));
  46047. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46048. var BABYLON;
  46049. (function (BABYLON) {
  46050. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46051. function FreeCameraKeyboardMoveInput() {
  46052. this._keys = new Array();
  46053. this.keysUp = [38];
  46054. this.keysDown = [40];
  46055. this.keysLeft = [37];
  46056. this.keysRight = [39];
  46057. }
  46058. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46059. var _this = this;
  46060. if (this._onCanvasBlurObserver) {
  46061. return;
  46062. }
  46063. this._scene = this.camera.getScene();
  46064. this._engine = this._scene.getEngine();
  46065. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46066. _this._keys = [];
  46067. });
  46068. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46069. var evt = info.event;
  46070. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46071. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46072. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46073. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46074. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46075. var index = _this._keys.indexOf(evt.keyCode);
  46076. if (index === -1) {
  46077. _this._keys.push(evt.keyCode);
  46078. }
  46079. if (!noPreventDefault) {
  46080. evt.preventDefault();
  46081. }
  46082. }
  46083. }
  46084. else {
  46085. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46086. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46087. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46088. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46089. var index = _this._keys.indexOf(evt.keyCode);
  46090. if (index >= 0) {
  46091. _this._keys.splice(index, 1);
  46092. }
  46093. if (!noPreventDefault) {
  46094. evt.preventDefault();
  46095. }
  46096. }
  46097. }
  46098. });
  46099. };
  46100. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46101. if (this._scene) {
  46102. if (this._onKeyboardObserver) {
  46103. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46104. }
  46105. if (this._onCanvasBlurObserver) {
  46106. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46107. }
  46108. this._onKeyboardObserver = null;
  46109. this._onCanvasBlurObserver = null;
  46110. }
  46111. this._keys = [];
  46112. };
  46113. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46114. if (this._onKeyboardObserver) {
  46115. var camera = this.camera;
  46116. // Keyboard
  46117. for (var index = 0; index < this._keys.length; index++) {
  46118. var keyCode = this._keys[index];
  46119. var speed = camera._computeLocalCameraSpeed();
  46120. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46121. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46122. }
  46123. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46124. camera._localDirection.copyFromFloats(0, 0, speed);
  46125. }
  46126. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46127. camera._localDirection.copyFromFloats(speed, 0, 0);
  46128. }
  46129. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46130. camera._localDirection.copyFromFloats(0, 0, -speed);
  46131. }
  46132. if (camera.getScene().useRightHandedSystem) {
  46133. camera._localDirection.z *= -1;
  46134. }
  46135. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46136. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46137. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46138. }
  46139. }
  46140. };
  46141. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46142. return "FreeCameraKeyboardMoveInput";
  46143. };
  46144. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46145. this._keys = [];
  46146. };
  46147. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46148. return "keyboard";
  46149. };
  46150. __decorate([
  46151. BABYLON.serialize()
  46152. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46153. __decorate([
  46154. BABYLON.serialize()
  46155. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46156. __decorate([
  46157. BABYLON.serialize()
  46158. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46159. __decorate([
  46160. BABYLON.serialize()
  46161. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46162. return FreeCameraKeyboardMoveInput;
  46163. }());
  46164. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46165. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46166. })(BABYLON || (BABYLON = {}));
  46167. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46168. var BABYLON;
  46169. (function (BABYLON) {
  46170. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46171. __extends(FreeCameraInputsManager, _super);
  46172. function FreeCameraInputsManager(camera) {
  46173. return _super.call(this, camera) || this;
  46174. }
  46175. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46176. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46177. return this;
  46178. };
  46179. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46180. if (touchEnabled === void 0) { touchEnabled = true; }
  46181. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46182. return this;
  46183. };
  46184. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46185. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46186. return this;
  46187. };
  46188. FreeCameraInputsManager.prototype.addTouch = function () {
  46189. this.add(new BABYLON.FreeCameraTouchInput());
  46190. return this;
  46191. };
  46192. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46193. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46194. return this;
  46195. };
  46196. return FreeCameraInputsManager;
  46197. }(BABYLON.CameraInputsManager));
  46198. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46199. })(BABYLON || (BABYLON = {}));
  46200. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46201. var BABYLON;
  46202. (function (BABYLON) {
  46203. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46204. // Forcing to use the Universal camera
  46205. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46206. });
  46207. var FreeCamera = /** @class */ (function (_super) {
  46208. __extends(FreeCamera, _super);
  46209. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46210. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46211. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46212. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46213. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46214. _this.checkCollisions = false;
  46215. _this.applyGravity = false;
  46216. _this._needMoveForGravity = false;
  46217. _this._oldPosition = BABYLON.Vector3.Zero();
  46218. _this._diffPosition = BABYLON.Vector3.Zero();
  46219. _this._newPosition = BABYLON.Vector3.Zero();
  46220. // Collisions
  46221. _this._collisionMask = -1;
  46222. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46223. if (collidedMesh === void 0) { collidedMesh = null; }
  46224. //TODO move this to the collision coordinator!
  46225. if (_this.getScene().workerCollisions)
  46226. newPosition.multiplyInPlace(_this._collider._radius);
  46227. var updatePosition = function (newPos) {
  46228. _this._newPosition.copyFrom(newPos);
  46229. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46230. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46231. _this.position.addInPlace(_this._diffPosition);
  46232. if (_this.onCollide && collidedMesh) {
  46233. _this.onCollide(collidedMesh);
  46234. }
  46235. }
  46236. };
  46237. updatePosition(newPosition);
  46238. };
  46239. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46240. _this.inputs.addKeyboard().addMouse();
  46241. return _this;
  46242. }
  46243. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46244. //-- begin properties for backward compatibility for inputs
  46245. /**
  46246. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46247. * Higher values reduce sensitivity.
  46248. */
  46249. get: function () {
  46250. var mouse = this.inputs.attached["mouse"];
  46251. if (mouse)
  46252. return mouse.angularSensibility;
  46253. return 0;
  46254. },
  46255. /**
  46256. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46257. * Higher values reduce sensitivity.
  46258. */
  46259. set: function (value) {
  46260. var mouse = this.inputs.attached["mouse"];
  46261. if (mouse)
  46262. mouse.angularSensibility = value;
  46263. },
  46264. enumerable: true,
  46265. configurable: true
  46266. });
  46267. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46268. get: function () {
  46269. var keyboard = this.inputs.attached["keyboard"];
  46270. if (keyboard)
  46271. return keyboard.keysUp;
  46272. return [];
  46273. },
  46274. set: function (value) {
  46275. var keyboard = this.inputs.attached["keyboard"];
  46276. if (keyboard)
  46277. keyboard.keysUp = value;
  46278. },
  46279. enumerable: true,
  46280. configurable: true
  46281. });
  46282. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46283. get: function () {
  46284. var keyboard = this.inputs.attached["keyboard"];
  46285. if (keyboard)
  46286. return keyboard.keysDown;
  46287. return [];
  46288. },
  46289. set: function (value) {
  46290. var keyboard = this.inputs.attached["keyboard"];
  46291. if (keyboard)
  46292. keyboard.keysDown = value;
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46298. get: function () {
  46299. var keyboard = this.inputs.attached["keyboard"];
  46300. if (keyboard)
  46301. return keyboard.keysLeft;
  46302. return [];
  46303. },
  46304. set: function (value) {
  46305. var keyboard = this.inputs.attached["keyboard"];
  46306. if (keyboard)
  46307. keyboard.keysLeft = value;
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46313. get: function () {
  46314. var keyboard = this.inputs.attached["keyboard"];
  46315. if (keyboard)
  46316. return keyboard.keysRight;
  46317. return [];
  46318. },
  46319. set: function (value) {
  46320. var keyboard = this.inputs.attached["keyboard"];
  46321. if (keyboard)
  46322. keyboard.keysRight = value;
  46323. },
  46324. enumerable: true,
  46325. configurable: true
  46326. });
  46327. // Controls
  46328. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46329. this.inputs.attachElement(element, noPreventDefault);
  46330. };
  46331. FreeCamera.prototype.detachControl = function (element) {
  46332. this.inputs.detachElement(element);
  46333. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46334. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46335. };
  46336. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46337. get: function () {
  46338. return this._collisionMask;
  46339. },
  46340. set: function (mask) {
  46341. this._collisionMask = !isNaN(mask) ? mask : -1;
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46347. var globalPosition;
  46348. if (this.parent) {
  46349. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46350. }
  46351. else {
  46352. globalPosition = this.position;
  46353. }
  46354. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46355. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46356. if (!this._collider) {
  46357. this._collider = new BABYLON.Collider();
  46358. }
  46359. this._collider._radius = this.ellipsoid;
  46360. this._collider.collisionMask = this._collisionMask;
  46361. //no need for clone, as long as gravity is not on.
  46362. var actualDisplacement = displacement;
  46363. //add gravity to the direction to prevent the dual-collision checking
  46364. if (this.applyGravity) {
  46365. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46366. actualDisplacement = displacement.add(this.getScene().gravity);
  46367. }
  46368. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46369. };
  46370. FreeCamera.prototype._checkInputs = function () {
  46371. if (!this._localDirection) {
  46372. this._localDirection = BABYLON.Vector3.Zero();
  46373. this._transformedDirection = BABYLON.Vector3.Zero();
  46374. }
  46375. this.inputs.checkInputs();
  46376. _super.prototype._checkInputs.call(this);
  46377. };
  46378. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46379. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46380. };
  46381. FreeCamera.prototype._updatePosition = function () {
  46382. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46383. this._collideWithWorld(this.cameraDirection);
  46384. }
  46385. else {
  46386. _super.prototype._updatePosition.call(this);
  46387. }
  46388. };
  46389. FreeCamera.prototype.dispose = function () {
  46390. this.inputs.clear();
  46391. _super.prototype.dispose.call(this);
  46392. };
  46393. FreeCamera.prototype.getClassName = function () {
  46394. return "FreeCamera";
  46395. };
  46396. __decorate([
  46397. BABYLON.serializeAsVector3()
  46398. ], FreeCamera.prototype, "ellipsoid", void 0);
  46399. __decorate([
  46400. BABYLON.serializeAsVector3()
  46401. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46402. __decorate([
  46403. BABYLON.serialize()
  46404. ], FreeCamera.prototype, "checkCollisions", void 0);
  46405. __decorate([
  46406. BABYLON.serialize()
  46407. ], FreeCamera.prototype, "applyGravity", void 0);
  46408. return FreeCamera;
  46409. }(BABYLON.TargetCamera));
  46410. BABYLON.FreeCamera = FreeCamera;
  46411. })(BABYLON || (BABYLON = {}));
  46412. //# sourceMappingURL=babylon.freeCamera.js.map
  46413. var BABYLON;
  46414. (function (BABYLON) {
  46415. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46416. function ArcRotateCameraKeyboardMoveInput() {
  46417. this._keys = new Array();
  46418. this.keysUp = [38];
  46419. this.keysDown = [40];
  46420. this.keysLeft = [37];
  46421. this.keysRight = [39];
  46422. this.keysReset = [220];
  46423. this.panningSensibility = 50.0;
  46424. this.zoomingSensibility = 25.0;
  46425. this.useAltToZoom = true;
  46426. }
  46427. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46428. var _this = this;
  46429. if (this._onCanvasBlurObserver) {
  46430. return;
  46431. }
  46432. this._scene = this.camera.getScene();
  46433. this._engine = this._scene.getEngine();
  46434. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46435. _this._keys = [];
  46436. });
  46437. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46438. var evt = info.event;
  46439. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46440. _this._ctrlPressed = evt.ctrlKey;
  46441. _this._altPressed = evt.altKey;
  46442. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46443. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46444. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46445. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46446. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46447. var index = _this._keys.indexOf(evt.keyCode);
  46448. if (index === -1) {
  46449. _this._keys.push(evt.keyCode);
  46450. }
  46451. if (evt.preventDefault) {
  46452. if (!noPreventDefault) {
  46453. evt.preventDefault();
  46454. }
  46455. }
  46456. }
  46457. }
  46458. else {
  46459. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46460. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46461. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46462. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46463. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46464. var index = _this._keys.indexOf(evt.keyCode);
  46465. if (index >= 0) {
  46466. _this._keys.splice(index, 1);
  46467. }
  46468. if (evt.preventDefault) {
  46469. if (!noPreventDefault) {
  46470. evt.preventDefault();
  46471. }
  46472. }
  46473. }
  46474. }
  46475. });
  46476. };
  46477. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46478. if (this._scene) {
  46479. if (this._onKeyboardObserver) {
  46480. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46481. }
  46482. if (this._onCanvasBlurObserver) {
  46483. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46484. }
  46485. this._onKeyboardObserver = null;
  46486. this._onCanvasBlurObserver = null;
  46487. }
  46488. this._keys = [];
  46489. };
  46490. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46491. if (this._onKeyboardObserver) {
  46492. var camera = this.camera;
  46493. for (var index = 0; index < this._keys.length; index++) {
  46494. var keyCode = this._keys[index];
  46495. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46496. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46497. camera.inertialPanningX -= 1 / this.panningSensibility;
  46498. }
  46499. else {
  46500. camera.inertialAlphaOffset -= 0.01;
  46501. }
  46502. }
  46503. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46504. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46505. camera.inertialPanningY += 1 / this.panningSensibility;
  46506. }
  46507. else if (this._altPressed && this.useAltToZoom) {
  46508. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46509. }
  46510. else {
  46511. camera.inertialBetaOffset -= 0.01;
  46512. }
  46513. }
  46514. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46515. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46516. camera.inertialPanningX += 1 / this.panningSensibility;
  46517. }
  46518. else {
  46519. camera.inertialAlphaOffset += 0.01;
  46520. }
  46521. }
  46522. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46523. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46524. camera.inertialPanningY -= 1 / this.panningSensibility;
  46525. }
  46526. else if (this._altPressed && this.useAltToZoom) {
  46527. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46528. }
  46529. else {
  46530. camera.inertialBetaOffset += 0.01;
  46531. }
  46532. }
  46533. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46534. camera.restoreState();
  46535. }
  46536. }
  46537. }
  46538. };
  46539. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46540. return "ArcRotateCameraKeyboardMoveInput";
  46541. };
  46542. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46543. return "keyboard";
  46544. };
  46545. __decorate([
  46546. BABYLON.serialize()
  46547. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46548. __decorate([
  46549. BABYLON.serialize()
  46550. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46551. __decorate([
  46552. BABYLON.serialize()
  46553. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46554. __decorate([
  46555. BABYLON.serialize()
  46556. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46557. __decorate([
  46558. BABYLON.serialize()
  46559. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46560. __decorate([
  46561. BABYLON.serialize()
  46562. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46563. __decorate([
  46564. BABYLON.serialize()
  46565. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46566. __decorate([
  46567. BABYLON.serialize()
  46568. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46569. return ArcRotateCameraKeyboardMoveInput;
  46570. }());
  46571. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46572. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46573. })(BABYLON || (BABYLON = {}));
  46574. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46575. var BABYLON;
  46576. (function (BABYLON) {
  46577. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46578. function ArcRotateCameraMouseWheelInput() {
  46579. this.wheelPrecision = 3.0;
  46580. /**
  46581. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46582. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46583. */
  46584. this.wheelDeltaPercentage = 0;
  46585. }
  46586. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46587. var _this = this;
  46588. this._wheel = function (p, s) {
  46589. //sanity check - this should be a PointerWheel event.
  46590. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46591. return;
  46592. var event = p.event;
  46593. var delta = 0;
  46594. if (event.wheelDelta) {
  46595. if (_this.wheelDeltaPercentage) {
  46596. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46597. if (event.wheelDelta > 0) {
  46598. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46599. }
  46600. else {
  46601. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46602. }
  46603. }
  46604. else {
  46605. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46606. }
  46607. }
  46608. else if (event.detail) {
  46609. delta = -event.detail / _this.wheelPrecision;
  46610. }
  46611. if (delta)
  46612. _this.camera.inertialRadiusOffset += delta;
  46613. if (event.preventDefault) {
  46614. if (!noPreventDefault) {
  46615. event.preventDefault();
  46616. }
  46617. }
  46618. };
  46619. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46620. };
  46621. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46622. if (this._observer && element) {
  46623. this.camera.getScene().onPointerObservable.remove(this._observer);
  46624. this._observer = null;
  46625. this._wheel = null;
  46626. }
  46627. };
  46628. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46629. return "ArcRotateCameraMouseWheelInput";
  46630. };
  46631. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46632. return "mousewheel";
  46633. };
  46634. __decorate([
  46635. BABYLON.serialize()
  46636. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46637. __decorate([
  46638. BABYLON.serialize()
  46639. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46640. return ArcRotateCameraMouseWheelInput;
  46641. }());
  46642. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46643. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46644. })(BABYLON || (BABYLON = {}));
  46645. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46646. var BABYLON;
  46647. (function (BABYLON) {
  46648. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46649. function ArcRotateCameraPointersInput() {
  46650. this.buttons = [0, 1, 2];
  46651. this.angularSensibilityX = 1000.0;
  46652. this.angularSensibilityY = 1000.0;
  46653. this.pinchPrecision = 12.0;
  46654. /**
  46655. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46656. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46657. */
  46658. this.pinchDeltaPercentage = 0;
  46659. this.panningSensibility = 1000.0;
  46660. this.multiTouchPanning = true;
  46661. this.multiTouchPanAndZoom = true;
  46662. this._isPanClick = false;
  46663. this.pinchInwards = true;
  46664. }
  46665. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46666. var _this = this;
  46667. var engine = this.camera.getEngine();
  46668. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46669. var pointA = null;
  46670. var pointB = null;
  46671. var previousPinchSquaredDistance = 0;
  46672. var initialDistance = 0;
  46673. var twoFingerActivityCount = 0;
  46674. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46675. this._pointerInput = function (p, s) {
  46676. var evt = p.event;
  46677. var isTouch = p.event.pointerType === "touch";
  46678. if (engine.isInVRExclusivePointerMode) {
  46679. return;
  46680. }
  46681. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46682. return;
  46683. }
  46684. var srcElement = (evt.srcElement || evt.target);
  46685. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46686. try {
  46687. srcElement.setPointerCapture(evt.pointerId);
  46688. }
  46689. catch (e) {
  46690. //Nothing to do with the error. Execution will continue.
  46691. }
  46692. // Manage panning with pan button click
  46693. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46694. // manage pointers
  46695. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46696. if (pointA === null) {
  46697. pointA = cacheSoloPointer;
  46698. }
  46699. else if (pointB === null) {
  46700. pointB = cacheSoloPointer;
  46701. }
  46702. if (!noPreventDefault) {
  46703. evt.preventDefault();
  46704. element.focus();
  46705. }
  46706. }
  46707. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46708. _this.camera.restoreState();
  46709. }
  46710. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46711. try {
  46712. srcElement.releasePointerCapture(evt.pointerId);
  46713. }
  46714. catch (e) {
  46715. //Nothing to do with the error.
  46716. }
  46717. cacheSoloPointer = null;
  46718. previousPinchSquaredDistance = 0;
  46719. previousMultiTouchPanPosition.isPaning = false;
  46720. previousMultiTouchPanPosition.isPinching = false;
  46721. twoFingerActivityCount = 0;
  46722. initialDistance = 0;
  46723. if (!isTouch) {
  46724. pointB = null; // Mouse and pen are mono pointer
  46725. }
  46726. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46727. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46728. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46729. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46730. if (engine._badOS) {
  46731. pointA = pointB = null;
  46732. }
  46733. else {
  46734. //only remove the impacted pointer in case of multitouch allowing on most
  46735. //platforms switching from rotate to zoom and pan seamlessly.
  46736. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46737. pointA = pointB;
  46738. pointB = null;
  46739. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46740. }
  46741. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46742. pointB = null;
  46743. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46744. }
  46745. else {
  46746. pointA = pointB = null;
  46747. }
  46748. }
  46749. if (!noPreventDefault) {
  46750. evt.preventDefault();
  46751. }
  46752. }
  46753. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46754. if (!noPreventDefault) {
  46755. evt.preventDefault();
  46756. }
  46757. // One button down
  46758. if (pointA && pointB === null && cacheSoloPointer) {
  46759. if (_this.panningSensibility !== 0 &&
  46760. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46761. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46762. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46763. }
  46764. else {
  46765. var offsetX = evt.clientX - cacheSoloPointer.x;
  46766. var offsetY = evt.clientY - cacheSoloPointer.y;
  46767. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46768. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46769. }
  46770. cacheSoloPointer.x = evt.clientX;
  46771. cacheSoloPointer.y = evt.clientY;
  46772. }
  46773. // Two buttons down: pinch/pan
  46774. else if (pointA && pointB) {
  46775. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46776. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46777. ed.x = evt.clientX;
  46778. ed.y = evt.clientY;
  46779. var direction = _this.pinchInwards ? 1 : -1;
  46780. var distX = pointA.x - pointB.x;
  46781. var distY = pointA.y - pointB.y;
  46782. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46783. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46784. if (previousPinchSquaredDistance === 0) {
  46785. initialDistance = pinchDistance;
  46786. previousPinchSquaredDistance = pinchSquaredDistance;
  46787. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46788. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46789. return;
  46790. }
  46791. if (_this.multiTouchPanAndZoom) {
  46792. if (_this.pinchDeltaPercentage) {
  46793. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46794. }
  46795. else {
  46796. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46797. (_this.pinchPrecision *
  46798. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46799. direction);
  46800. }
  46801. if (_this.panningSensibility !== 0) {
  46802. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46803. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46804. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46805. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46806. previousMultiTouchPanPosition.x = pointersCenterX;
  46807. previousMultiTouchPanPosition.y = pointersCenterY;
  46808. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46809. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46810. }
  46811. }
  46812. else {
  46813. twoFingerActivityCount++;
  46814. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46815. if (_this.pinchDeltaPercentage) {
  46816. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46817. }
  46818. else {
  46819. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46820. (_this.pinchPrecision *
  46821. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46822. direction);
  46823. }
  46824. previousMultiTouchPanPosition.isPaning = false;
  46825. previousMultiTouchPanPosition.isPinching = true;
  46826. }
  46827. else {
  46828. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46829. if (!previousMultiTouchPanPosition.isPaning) {
  46830. previousMultiTouchPanPosition.isPaning = true;
  46831. previousMultiTouchPanPosition.isPinching = false;
  46832. previousMultiTouchPanPosition.x = ed.x;
  46833. previousMultiTouchPanPosition.y = ed.y;
  46834. return;
  46835. }
  46836. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46837. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46838. }
  46839. }
  46840. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46841. previousMultiTouchPanPosition.x = ed.x;
  46842. previousMultiTouchPanPosition.y = ed.y;
  46843. }
  46844. }
  46845. previousPinchSquaredDistance = pinchSquaredDistance;
  46846. }
  46847. }
  46848. };
  46849. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46850. this._onContextMenu = function (evt) {
  46851. evt.preventDefault();
  46852. };
  46853. if (!this.camera._useCtrlForPanning) {
  46854. element.addEventListener("contextmenu", this._onContextMenu, false);
  46855. }
  46856. this._onLostFocus = function () {
  46857. //this._keys = [];
  46858. pointA = pointB = null;
  46859. previousPinchSquaredDistance = 0;
  46860. previousMultiTouchPanPosition.isPaning = false;
  46861. previousMultiTouchPanPosition.isPinching = false;
  46862. twoFingerActivityCount = 0;
  46863. cacheSoloPointer = null;
  46864. initialDistance = 0;
  46865. };
  46866. this._onMouseMove = function (evt) {
  46867. if (!engine.isPointerLock) {
  46868. return;
  46869. }
  46870. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46871. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46872. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46873. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46874. if (!noPreventDefault) {
  46875. evt.preventDefault();
  46876. }
  46877. };
  46878. this._onGestureStart = function (e) {
  46879. if (window.MSGesture === undefined) {
  46880. return;
  46881. }
  46882. if (!_this._MSGestureHandler) {
  46883. _this._MSGestureHandler = new MSGesture();
  46884. _this._MSGestureHandler.target = element;
  46885. }
  46886. _this._MSGestureHandler.addPointer(e.pointerId);
  46887. };
  46888. this._onGesture = function (e) {
  46889. _this.camera.radius *= e.scale;
  46890. if (e.preventDefault) {
  46891. if (!noPreventDefault) {
  46892. e.stopPropagation();
  46893. e.preventDefault();
  46894. }
  46895. }
  46896. };
  46897. element.addEventListener("mousemove", this._onMouseMove, false);
  46898. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  46899. element.addEventListener("MSGestureChange", this._onGesture, false);
  46900. BABYLON.Tools.RegisterTopRootEvents([
  46901. { name: "blur", handler: this._onLostFocus }
  46902. ]);
  46903. };
  46904. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  46905. if (this._onLostFocus) {
  46906. BABYLON.Tools.UnregisterTopRootEvents([
  46907. { name: "blur", handler: this._onLostFocus }
  46908. ]);
  46909. }
  46910. if (element && this._observer) {
  46911. this.camera.getScene().onPointerObservable.remove(this._observer);
  46912. this._observer = null;
  46913. if (this._onContextMenu) {
  46914. element.removeEventListener("contextmenu", this._onContextMenu);
  46915. }
  46916. if (this._onMouseMove) {
  46917. element.removeEventListener("mousemove", this._onMouseMove);
  46918. }
  46919. if (this._onGestureStart) {
  46920. element.removeEventListener("MSPointerDown", this._onGestureStart);
  46921. }
  46922. if (this._onGesture) {
  46923. element.removeEventListener("MSGestureChange", this._onGesture);
  46924. }
  46925. this._isPanClick = false;
  46926. this.pinchInwards = true;
  46927. this._onMouseMove = null;
  46928. this._onGestureStart = null;
  46929. this._onGesture = null;
  46930. this._MSGestureHandler = null;
  46931. this._onLostFocus = null;
  46932. this._onContextMenu = null;
  46933. }
  46934. };
  46935. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  46936. return "ArcRotateCameraPointersInput";
  46937. };
  46938. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  46939. return "pointers";
  46940. };
  46941. __decorate([
  46942. BABYLON.serialize()
  46943. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  46944. __decorate([
  46945. BABYLON.serialize()
  46946. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  46947. __decorate([
  46948. BABYLON.serialize()
  46949. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  46950. __decorate([
  46951. BABYLON.serialize()
  46952. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  46953. __decorate([
  46954. BABYLON.serialize()
  46955. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  46956. __decorate([
  46957. BABYLON.serialize()
  46958. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  46962. __decorate([
  46963. BABYLON.serialize()
  46964. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  46965. return ArcRotateCameraPointersInput;
  46966. }());
  46967. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  46968. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  46969. })(BABYLON || (BABYLON = {}));
  46970. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  46971. var BABYLON;
  46972. (function (BABYLON) {
  46973. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  46974. __extends(ArcRotateCameraInputsManager, _super);
  46975. function ArcRotateCameraInputsManager(camera) {
  46976. return _super.call(this, camera) || this;
  46977. }
  46978. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  46979. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  46980. return this;
  46981. };
  46982. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  46983. this.add(new BABYLON.ArcRotateCameraPointersInput());
  46984. return this;
  46985. };
  46986. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  46987. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  46988. return this;
  46989. };
  46990. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  46991. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  46992. return this;
  46993. };
  46994. return ArcRotateCameraInputsManager;
  46995. }(BABYLON.CameraInputsManager));
  46996. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  46997. })(BABYLON || (BABYLON = {}));
  46998. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  46999. var BABYLON;
  47000. (function (BABYLON) {
  47001. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47002. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47003. });
  47004. var ArcRotateCamera = /** @class */ (function (_super) {
  47005. __extends(ArcRotateCamera, _super);
  47006. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47007. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47008. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47009. _this.inertialAlphaOffset = 0;
  47010. _this.inertialBetaOffset = 0;
  47011. _this.inertialRadiusOffset = 0;
  47012. _this.lowerAlphaLimit = null;
  47013. _this.upperAlphaLimit = null;
  47014. _this.lowerBetaLimit = 0.01;
  47015. _this.upperBetaLimit = Math.PI;
  47016. _this.lowerRadiusLimit = null;
  47017. _this.upperRadiusLimit = null;
  47018. _this.inertialPanningX = 0;
  47019. _this.inertialPanningY = 0;
  47020. _this.pinchToPanMaxDistance = 20;
  47021. _this.panningDistanceLimit = null;
  47022. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47023. _this.panningInertia = 0.9;
  47024. //-- end properties for backward compatibility for inputs
  47025. _this.zoomOnFactor = 1;
  47026. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47027. _this.allowUpsideDown = true;
  47028. _this._viewMatrix = new BABYLON.Matrix();
  47029. // Panning
  47030. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47031. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47032. _this.checkCollisions = false;
  47033. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47034. _this._previousPosition = BABYLON.Vector3.Zero();
  47035. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47036. _this._newPosition = BABYLON.Vector3.Zero();
  47037. _this._computationVector = BABYLON.Vector3.Zero();
  47038. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47039. if (collidedMesh === void 0) { collidedMesh = null; }
  47040. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47041. newPosition.multiplyInPlace(_this._collider._radius);
  47042. }
  47043. if (!collidedMesh) {
  47044. _this._previousPosition.copyFrom(_this.position);
  47045. }
  47046. else {
  47047. _this.setPosition(newPosition);
  47048. if (_this.onCollide) {
  47049. _this.onCollide(collidedMesh);
  47050. }
  47051. }
  47052. // Recompute because of constraints
  47053. var cosa = Math.cos(_this.alpha);
  47054. var sina = Math.sin(_this.alpha);
  47055. var cosb = Math.cos(_this.beta);
  47056. var sinb = Math.sin(_this.beta);
  47057. if (sinb === 0) {
  47058. sinb = 0.0001;
  47059. }
  47060. var target = _this._getTargetPosition();
  47061. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47062. target.addToRef(_this._computationVector, _this._newPosition);
  47063. _this.position.copyFrom(_this._newPosition);
  47064. var up = _this.upVector;
  47065. if (_this.allowUpsideDown && _this.beta < 0) {
  47066. up = up.clone();
  47067. up = up.negate();
  47068. }
  47069. _this._computeViewMatrix(_this.position, target, up);
  47070. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47071. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47072. _this._collisionTriggered = false;
  47073. };
  47074. _this._target = BABYLON.Vector3.Zero();
  47075. if (target) {
  47076. _this.setTarget(target);
  47077. }
  47078. _this.alpha = alpha;
  47079. _this.beta = beta;
  47080. _this.radius = radius;
  47081. _this.getViewMatrix();
  47082. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47083. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47084. return _this;
  47085. }
  47086. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47087. get: function () {
  47088. return this._target;
  47089. },
  47090. set: function (value) {
  47091. this.setTarget(value);
  47092. },
  47093. enumerable: true,
  47094. configurable: true
  47095. });
  47096. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47097. //-- begin properties for backward compatibility for inputs
  47098. get: function () {
  47099. var pointers = this.inputs.attached["pointers"];
  47100. if (pointers)
  47101. return pointers.angularSensibilityX;
  47102. return 0;
  47103. },
  47104. set: function (value) {
  47105. var pointers = this.inputs.attached["pointers"];
  47106. if (pointers) {
  47107. pointers.angularSensibilityX = value;
  47108. }
  47109. },
  47110. enumerable: true,
  47111. configurable: true
  47112. });
  47113. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47114. get: function () {
  47115. var pointers = this.inputs.attached["pointers"];
  47116. if (pointers)
  47117. return pointers.angularSensibilityY;
  47118. return 0;
  47119. },
  47120. set: function (value) {
  47121. var pointers = this.inputs.attached["pointers"];
  47122. if (pointers) {
  47123. pointers.angularSensibilityY = value;
  47124. }
  47125. },
  47126. enumerable: true,
  47127. configurable: true
  47128. });
  47129. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47130. get: function () {
  47131. var pointers = this.inputs.attached["pointers"];
  47132. if (pointers)
  47133. return pointers.pinchPrecision;
  47134. return 0;
  47135. },
  47136. set: function (value) {
  47137. var pointers = this.inputs.attached["pointers"];
  47138. if (pointers) {
  47139. pointers.pinchPrecision = value;
  47140. }
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47146. get: function () {
  47147. var pointers = this.inputs.attached["pointers"];
  47148. if (pointers)
  47149. return pointers.pinchDeltaPercentage;
  47150. return 0;
  47151. },
  47152. set: function (value) {
  47153. var pointers = this.inputs.attached["pointers"];
  47154. if (pointers) {
  47155. pointers.pinchDeltaPercentage = value;
  47156. }
  47157. },
  47158. enumerable: true,
  47159. configurable: true
  47160. });
  47161. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47162. get: function () {
  47163. var pointers = this.inputs.attached["pointers"];
  47164. if (pointers)
  47165. return pointers.panningSensibility;
  47166. return 0;
  47167. },
  47168. set: function (value) {
  47169. var pointers = this.inputs.attached["pointers"];
  47170. if (pointers) {
  47171. pointers.panningSensibility = value;
  47172. }
  47173. },
  47174. enumerable: true,
  47175. configurable: true
  47176. });
  47177. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47178. get: function () {
  47179. var keyboard = this.inputs.attached["keyboard"];
  47180. if (keyboard)
  47181. return keyboard.keysUp;
  47182. return [];
  47183. },
  47184. set: function (value) {
  47185. var keyboard = this.inputs.attached["keyboard"];
  47186. if (keyboard)
  47187. keyboard.keysUp = value;
  47188. },
  47189. enumerable: true,
  47190. configurable: true
  47191. });
  47192. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47193. get: function () {
  47194. var keyboard = this.inputs.attached["keyboard"];
  47195. if (keyboard)
  47196. return keyboard.keysDown;
  47197. return [];
  47198. },
  47199. set: function (value) {
  47200. var keyboard = this.inputs.attached["keyboard"];
  47201. if (keyboard)
  47202. keyboard.keysDown = value;
  47203. },
  47204. enumerable: true,
  47205. configurable: true
  47206. });
  47207. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47208. get: function () {
  47209. var keyboard = this.inputs.attached["keyboard"];
  47210. if (keyboard)
  47211. return keyboard.keysLeft;
  47212. return [];
  47213. },
  47214. set: function (value) {
  47215. var keyboard = this.inputs.attached["keyboard"];
  47216. if (keyboard)
  47217. keyboard.keysLeft = value;
  47218. },
  47219. enumerable: true,
  47220. configurable: true
  47221. });
  47222. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47223. get: function () {
  47224. var keyboard = this.inputs.attached["keyboard"];
  47225. if (keyboard)
  47226. return keyboard.keysRight;
  47227. return [];
  47228. },
  47229. set: function (value) {
  47230. var keyboard = this.inputs.attached["keyboard"];
  47231. if (keyboard)
  47232. keyboard.keysRight = value;
  47233. },
  47234. enumerable: true,
  47235. configurable: true
  47236. });
  47237. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47238. get: function () {
  47239. var mousewheel = this.inputs.attached["mousewheel"];
  47240. if (mousewheel)
  47241. return mousewheel.wheelPrecision;
  47242. return 0;
  47243. },
  47244. set: function (value) {
  47245. var mousewheel = this.inputs.attached["mousewheel"];
  47246. if (mousewheel)
  47247. mousewheel.wheelPrecision = value;
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47253. get: function () {
  47254. var mousewheel = this.inputs.attached["mousewheel"];
  47255. if (mousewheel)
  47256. return mousewheel.wheelDeltaPercentage;
  47257. return 0;
  47258. },
  47259. set: function (value) {
  47260. var mousewheel = this.inputs.attached["mousewheel"];
  47261. if (mousewheel)
  47262. mousewheel.wheelDeltaPercentage = value;
  47263. },
  47264. enumerable: true,
  47265. configurable: true
  47266. });
  47267. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47268. get: function () {
  47269. return this._bouncingBehavior;
  47270. },
  47271. enumerable: true,
  47272. configurable: true
  47273. });
  47274. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47275. get: function () {
  47276. return this._bouncingBehavior != null;
  47277. },
  47278. set: function (value) {
  47279. if (value === this.useBouncingBehavior) {
  47280. return;
  47281. }
  47282. if (value) {
  47283. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47284. this.addBehavior(this._bouncingBehavior);
  47285. }
  47286. else if (this._bouncingBehavior) {
  47287. this.removeBehavior(this._bouncingBehavior);
  47288. this._bouncingBehavior = null;
  47289. }
  47290. },
  47291. enumerable: true,
  47292. configurable: true
  47293. });
  47294. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47295. get: function () {
  47296. return this._framingBehavior;
  47297. },
  47298. enumerable: true,
  47299. configurable: true
  47300. });
  47301. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47302. get: function () {
  47303. return this._framingBehavior != null;
  47304. },
  47305. set: function (value) {
  47306. if (value === this.useFramingBehavior) {
  47307. return;
  47308. }
  47309. if (value) {
  47310. this._framingBehavior = new BABYLON.FramingBehavior();
  47311. this.addBehavior(this._framingBehavior);
  47312. }
  47313. else if (this._framingBehavior) {
  47314. this.removeBehavior(this._framingBehavior);
  47315. this._framingBehavior = null;
  47316. }
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47322. get: function () {
  47323. return this._autoRotationBehavior;
  47324. },
  47325. enumerable: true,
  47326. configurable: true
  47327. });
  47328. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47329. get: function () {
  47330. return this._autoRotationBehavior != null;
  47331. },
  47332. set: function (value) {
  47333. if (value === this.useAutoRotationBehavior) {
  47334. return;
  47335. }
  47336. if (value) {
  47337. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47338. this.addBehavior(this._autoRotationBehavior);
  47339. }
  47340. else if (this._autoRotationBehavior) {
  47341. this.removeBehavior(this._autoRotationBehavior);
  47342. this._autoRotationBehavior = null;
  47343. }
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. // Cache
  47349. ArcRotateCamera.prototype._initCache = function () {
  47350. _super.prototype._initCache.call(this);
  47351. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47352. this._cache.alpha = undefined;
  47353. this._cache.beta = undefined;
  47354. this._cache.radius = undefined;
  47355. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47356. };
  47357. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47358. if (!ignoreParentClass) {
  47359. _super.prototype._updateCache.call(this);
  47360. }
  47361. this._cache._target.copyFrom(this._getTargetPosition());
  47362. this._cache.alpha = this.alpha;
  47363. this._cache.beta = this.beta;
  47364. this._cache.radius = this.radius;
  47365. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47366. };
  47367. ArcRotateCamera.prototype._getTargetPosition = function () {
  47368. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47369. var pos = this._targetHost.getAbsolutePosition();
  47370. if (this._targetBoundingCenter) {
  47371. pos.addToRef(this._targetBoundingCenter, this._target);
  47372. }
  47373. else {
  47374. this._target.copyFrom(pos);
  47375. }
  47376. }
  47377. var lockedTargetPosition = this._getLockedTargetPosition();
  47378. if (lockedTargetPosition) {
  47379. return lockedTargetPosition;
  47380. }
  47381. return this._target;
  47382. };
  47383. ArcRotateCamera.prototype.storeState = function () {
  47384. this._storedAlpha = this.alpha;
  47385. this._storedBeta = this.beta;
  47386. this._storedRadius = this.radius;
  47387. this._storedTarget = this._getTargetPosition().clone();
  47388. return _super.prototype.storeState.call(this);
  47389. };
  47390. /**
  47391. * Restored camera state. You must call storeState() first
  47392. */
  47393. ArcRotateCamera.prototype._restoreStateValues = function () {
  47394. if (!_super.prototype._restoreStateValues.call(this)) {
  47395. return false;
  47396. }
  47397. this.alpha = this._storedAlpha;
  47398. this.beta = this._storedBeta;
  47399. this.radius = this._storedRadius;
  47400. this.setTarget(this._storedTarget.clone());
  47401. this.inertialAlphaOffset = 0;
  47402. this.inertialBetaOffset = 0;
  47403. this.inertialRadiusOffset = 0;
  47404. this.inertialPanningX = 0;
  47405. this.inertialPanningY = 0;
  47406. return true;
  47407. };
  47408. // Synchronized
  47409. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47410. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47411. return false;
  47412. return this._cache._target.equals(this._getTargetPosition())
  47413. && this._cache.alpha === this.alpha
  47414. && this._cache.beta === this.beta
  47415. && this._cache.radius === this.radius
  47416. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47417. };
  47418. // Methods
  47419. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47420. var _this = this;
  47421. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47422. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47423. this._useCtrlForPanning = useCtrlForPanning;
  47424. this._panningMouseButton = panningMouseButton;
  47425. this.inputs.attachElement(element, noPreventDefault);
  47426. this._reset = function () {
  47427. _this.inertialAlphaOffset = 0;
  47428. _this.inertialBetaOffset = 0;
  47429. _this.inertialRadiusOffset = 0;
  47430. _this.inertialPanningX = 0;
  47431. _this.inertialPanningY = 0;
  47432. };
  47433. };
  47434. ArcRotateCamera.prototype.detachControl = function (element) {
  47435. this.inputs.detachElement(element);
  47436. if (this._reset) {
  47437. this._reset();
  47438. }
  47439. };
  47440. ArcRotateCamera.prototype._checkInputs = function () {
  47441. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47442. if (this._collisionTriggered) {
  47443. return;
  47444. }
  47445. this.inputs.checkInputs();
  47446. // Inertia
  47447. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47448. var inertialAlphaOffset = this.inertialAlphaOffset;
  47449. if (this.beta <= 0)
  47450. inertialAlphaOffset *= -1;
  47451. if (this.getScene().useRightHandedSystem)
  47452. inertialAlphaOffset *= -1;
  47453. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47454. inertialAlphaOffset *= -1;
  47455. this.alpha += inertialAlphaOffset;
  47456. this.beta += this.inertialBetaOffset;
  47457. this.radius -= this.inertialRadiusOffset;
  47458. this.inertialAlphaOffset *= this.inertia;
  47459. this.inertialBetaOffset *= this.inertia;
  47460. this.inertialRadiusOffset *= this.inertia;
  47461. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47462. this.inertialAlphaOffset = 0;
  47463. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47464. this.inertialBetaOffset = 0;
  47465. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47466. this.inertialRadiusOffset = 0;
  47467. }
  47468. // Panning inertia
  47469. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47470. if (!this._localDirection) {
  47471. this._localDirection = BABYLON.Vector3.Zero();
  47472. this._transformedDirection = BABYLON.Vector3.Zero();
  47473. }
  47474. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47475. this._localDirection.multiplyInPlace(this.panningAxis);
  47476. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47477. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47478. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47479. if (!this.panningAxis.y) {
  47480. this._transformedDirection.y = 0;
  47481. }
  47482. if (!this._targetHost) {
  47483. if (this.panningDistanceLimit) {
  47484. this._transformedDirection.addInPlace(this._target);
  47485. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47486. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47487. this._target.copyFrom(this._transformedDirection);
  47488. }
  47489. }
  47490. else {
  47491. this._target.addInPlace(this._transformedDirection);
  47492. }
  47493. }
  47494. this.inertialPanningX *= this.panningInertia;
  47495. this.inertialPanningY *= this.panningInertia;
  47496. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47497. this.inertialPanningX = 0;
  47498. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47499. this.inertialPanningY = 0;
  47500. }
  47501. // Limits
  47502. this._checkLimits();
  47503. _super.prototype._checkInputs.call(this);
  47504. };
  47505. ArcRotateCamera.prototype._checkLimits = function () {
  47506. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47507. if (this.allowUpsideDown && this.beta > Math.PI) {
  47508. this.beta = this.beta - (2 * Math.PI);
  47509. }
  47510. }
  47511. else {
  47512. if (this.beta < this.lowerBetaLimit) {
  47513. this.beta = this.lowerBetaLimit;
  47514. }
  47515. }
  47516. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47517. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47518. this.beta = this.beta + (2 * Math.PI);
  47519. }
  47520. }
  47521. else {
  47522. if (this.beta > this.upperBetaLimit) {
  47523. this.beta = this.upperBetaLimit;
  47524. }
  47525. }
  47526. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47527. this.alpha = this.lowerAlphaLimit;
  47528. }
  47529. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47530. this.alpha = this.upperAlphaLimit;
  47531. }
  47532. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47533. this.radius = this.lowerRadiusLimit;
  47534. }
  47535. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47536. this.radius = this.upperRadiusLimit;
  47537. }
  47538. };
  47539. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47540. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47541. this.radius = this._computationVector.length();
  47542. if (this.radius === 0) {
  47543. this.radius = 0.0001; // Just to avoid division by zero
  47544. }
  47545. // Alpha
  47546. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47547. if (this._computationVector.z < 0) {
  47548. this.alpha = 2 * Math.PI - this.alpha;
  47549. }
  47550. // Beta
  47551. this.beta = Math.acos(this._computationVector.y / this.radius);
  47552. this._checkLimits();
  47553. };
  47554. ArcRotateCamera.prototype.setPosition = function (position) {
  47555. if (this.position.equals(position)) {
  47556. return;
  47557. }
  47558. this.position.copyFrom(position);
  47559. this.rebuildAnglesAndRadius();
  47560. };
  47561. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47562. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47563. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47564. if (target.getBoundingInfo) {
  47565. if (toBoundingCenter) {
  47566. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47567. }
  47568. else {
  47569. this._targetBoundingCenter = null;
  47570. }
  47571. this._targetHost = target;
  47572. this._target = this._getTargetPosition();
  47573. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47574. }
  47575. else {
  47576. var newTarget = target;
  47577. var currentTarget = this._getTargetPosition();
  47578. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47579. return;
  47580. }
  47581. this._targetHost = null;
  47582. this._target = newTarget;
  47583. this._targetBoundingCenter = null;
  47584. this.onMeshTargetChangedObservable.notifyObservers(null);
  47585. }
  47586. this.rebuildAnglesAndRadius();
  47587. };
  47588. ArcRotateCamera.prototype._getViewMatrix = function () {
  47589. // Compute
  47590. var cosa = Math.cos(this.alpha);
  47591. var sina = Math.sin(this.alpha);
  47592. var cosb = Math.cos(this.beta);
  47593. var sinb = Math.sin(this.beta);
  47594. if (sinb === 0) {
  47595. sinb = 0.0001;
  47596. }
  47597. var target = this._getTargetPosition();
  47598. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47599. target.addToRef(this._computationVector, this._newPosition);
  47600. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47601. if (!this._collider) {
  47602. this._collider = new BABYLON.Collider();
  47603. }
  47604. this._collider._radius = this.collisionRadius;
  47605. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47606. this._collisionTriggered = true;
  47607. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47608. }
  47609. else {
  47610. this.position.copyFrom(this._newPosition);
  47611. var up = this.upVector;
  47612. if (this.allowUpsideDown && sinb < 0) {
  47613. up = up.clone();
  47614. up = up.negate();
  47615. }
  47616. this._computeViewMatrix(this.position, target, up);
  47617. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47618. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47619. }
  47620. this._currentTarget = target;
  47621. return this._viewMatrix;
  47622. };
  47623. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47624. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47625. meshes = meshes || this.getScene().meshes;
  47626. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47627. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47628. this.radius = distance * this.zoomOnFactor;
  47629. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47630. };
  47631. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47632. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47633. var meshesOrMinMaxVector;
  47634. var distance;
  47635. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47636. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47637. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47638. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47639. }
  47640. else { //minMaxVector and distance
  47641. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47642. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47643. distance = minMaxVectorAndDistance.distance;
  47644. }
  47645. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47646. if (!doNotUpdateMaxZ) {
  47647. this.maxZ = distance * 2;
  47648. }
  47649. };
  47650. /**
  47651. * @override
  47652. * Override Camera.createRigCamera
  47653. */
  47654. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47655. var alphaShift = 0;
  47656. switch (this.cameraRigMode) {
  47657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47660. case BABYLON.Camera.RIG_MODE_VR:
  47661. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47662. break;
  47663. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47664. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47665. break;
  47666. }
  47667. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47668. rigCam._cameraRigParams = {};
  47669. return rigCam;
  47670. };
  47671. /**
  47672. * @override
  47673. * Override Camera._updateRigCameras
  47674. */
  47675. ArcRotateCamera.prototype._updateRigCameras = function () {
  47676. var camLeft = this._rigCameras[0];
  47677. var camRight = this._rigCameras[1];
  47678. camLeft.beta = camRight.beta = this.beta;
  47679. camLeft.radius = camRight.radius = this.radius;
  47680. switch (this.cameraRigMode) {
  47681. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47684. case BABYLON.Camera.RIG_MODE_VR:
  47685. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47686. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47687. break;
  47688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47689. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47690. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47691. break;
  47692. }
  47693. _super.prototype._updateRigCameras.call(this);
  47694. };
  47695. ArcRotateCamera.prototype.dispose = function () {
  47696. this.inputs.clear();
  47697. _super.prototype.dispose.call(this);
  47698. };
  47699. ArcRotateCamera.prototype.getClassName = function () {
  47700. return "ArcRotateCamera";
  47701. };
  47702. __decorate([
  47703. BABYLON.serialize()
  47704. ], ArcRotateCamera.prototype, "alpha", void 0);
  47705. __decorate([
  47706. BABYLON.serialize()
  47707. ], ArcRotateCamera.prototype, "beta", void 0);
  47708. __decorate([
  47709. BABYLON.serialize()
  47710. ], ArcRotateCamera.prototype, "radius", void 0);
  47711. __decorate([
  47712. BABYLON.serializeAsVector3("target")
  47713. ], ArcRotateCamera.prototype, "_target", void 0);
  47714. __decorate([
  47715. BABYLON.serialize()
  47716. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47717. __decorate([
  47718. BABYLON.serialize()
  47719. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47720. __decorate([
  47721. BABYLON.serialize()
  47722. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47723. __decorate([
  47724. BABYLON.serialize()
  47725. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47726. __decorate([
  47727. BABYLON.serialize()
  47728. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47729. __decorate([
  47730. BABYLON.serialize()
  47731. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47732. __decorate([
  47733. BABYLON.serialize()
  47734. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47735. __decorate([
  47736. BABYLON.serialize()
  47737. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47738. __decorate([
  47739. BABYLON.serialize()
  47740. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47741. __decorate([
  47742. BABYLON.serialize()
  47743. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47744. __decorate([
  47745. BABYLON.serialize()
  47746. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47747. __decorate([
  47748. BABYLON.serialize()
  47749. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47750. __decorate([
  47751. BABYLON.serialize()
  47752. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47753. __decorate([
  47754. BABYLON.serializeAsVector3()
  47755. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47756. __decorate([
  47757. BABYLON.serialize()
  47758. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47759. __decorate([
  47760. BABYLON.serialize()
  47761. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47762. __decorate([
  47763. BABYLON.serialize()
  47764. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47765. return ArcRotateCamera;
  47766. }(BABYLON.TargetCamera));
  47767. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47768. })(BABYLON || (BABYLON = {}));
  47769. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47770. var BABYLON;
  47771. (function (BABYLON) {
  47772. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  47773. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  47774. });
  47775. /**
  47776. * The HemisphericLight simulates the ambient environment light,
  47777. * so the passed direction is the light reflection direction, not the incoming direction.
  47778. */
  47779. var HemisphericLight = /** @class */ (function (_super) {
  47780. __extends(HemisphericLight, _super);
  47781. /**
  47782. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47783. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47784. * The HemisphericLight can't cast shadows.
  47785. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47786. * @param name The friendly name of the light
  47787. * @param direction The direction of the light reflection
  47788. * @param scene The scene the light belongs to
  47789. */
  47790. function HemisphericLight(name, direction, scene) {
  47791. var _this = _super.call(this, name, scene) || this;
  47792. /**
  47793. * The groundColor is the light in the opposite direction to the one specified during creation.
  47794. * 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.
  47795. */
  47796. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47797. _this.direction = direction || BABYLON.Vector3.Up();
  47798. return _this;
  47799. }
  47800. HemisphericLight.prototype._buildUniformLayout = function () {
  47801. this._uniformBuffer.addUniform("vLightData", 4);
  47802. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47803. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47804. this._uniformBuffer.addUniform("vLightGround", 3);
  47805. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47806. this._uniformBuffer.addUniform("depthValues", 2);
  47807. this._uniformBuffer.create();
  47808. };
  47809. /**
  47810. * Returns the string "HemisphericLight".
  47811. * @return The class name
  47812. */
  47813. HemisphericLight.prototype.getClassName = function () {
  47814. return "HemisphericLight";
  47815. };
  47816. /**
  47817. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47818. * Returns the updated direction.
  47819. * @param target The target the direction should point to
  47820. * @return The computed direction
  47821. */
  47822. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47823. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47824. return this.direction;
  47825. };
  47826. /**
  47827. * Returns the shadow generator associated to the light.
  47828. * @returns Always null for hemispheric lights because it does not support shadows.
  47829. */
  47830. HemisphericLight.prototype.getShadowGenerator = function () {
  47831. return null;
  47832. };
  47833. /**
  47834. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47835. * @param effect The effect to update
  47836. * @param lightIndex The index of the light in the effect to update
  47837. * @returns The hemispheric light
  47838. */
  47839. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47840. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47841. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47842. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47843. return this;
  47844. };
  47845. /**
  47846. * @hidden internal use only.
  47847. */
  47848. HemisphericLight.prototype._getWorldMatrix = function () {
  47849. if (!this._worldMatrix) {
  47850. this._worldMatrix = BABYLON.Matrix.Identity();
  47851. }
  47852. return this._worldMatrix;
  47853. };
  47854. /**
  47855. * Returns the integer 3.
  47856. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47857. */
  47858. HemisphericLight.prototype.getTypeID = function () {
  47859. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47860. };
  47861. /**
  47862. * Prepares the list of defines specific to the light type.
  47863. * @param defines the list of defines
  47864. * @param lightIndex defines the index of the light for the effect
  47865. */
  47866. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  47867. defines["HEMILIGHT" + lightIndex] = true;
  47868. };
  47869. __decorate([
  47870. BABYLON.serializeAsColor3()
  47871. ], HemisphericLight.prototype, "groundColor", void 0);
  47872. __decorate([
  47873. BABYLON.serializeAsVector3()
  47874. ], HemisphericLight.prototype, "direction", void 0);
  47875. return HemisphericLight;
  47876. }(BABYLON.Light));
  47877. BABYLON.HemisphericLight = HemisphericLight;
  47878. })(BABYLON || (BABYLON = {}));
  47879. //# sourceMappingURL=babylon.hemisphericLight.js.map
  47880. var BABYLON;
  47881. (function (BABYLON) {
  47882. /**
  47883. * Base implementation IShadowLight
  47884. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  47885. */
  47886. var ShadowLight = /** @class */ (function (_super) {
  47887. __extends(ShadowLight, _super);
  47888. function ShadowLight() {
  47889. var _this = _super !== null && _super.apply(this, arguments) || this;
  47890. _this._needProjectionMatrixCompute = true;
  47891. return _this;
  47892. }
  47893. ShadowLight.prototype._setPosition = function (value) {
  47894. this._position = value;
  47895. };
  47896. Object.defineProperty(ShadowLight.prototype, "position", {
  47897. /**
  47898. * Sets the position the shadow will be casted from. Also use as the light position for both
  47899. * point and spot lights.
  47900. */
  47901. get: function () {
  47902. return this._position;
  47903. },
  47904. /**
  47905. * Sets the position the shadow will be casted from. Also use as the light position for both
  47906. * point and spot lights.
  47907. */
  47908. set: function (value) {
  47909. this._setPosition(value);
  47910. },
  47911. enumerable: true,
  47912. configurable: true
  47913. });
  47914. ShadowLight.prototype._setDirection = function (value) {
  47915. this._direction = value;
  47916. };
  47917. Object.defineProperty(ShadowLight.prototype, "direction", {
  47918. /**
  47919. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  47920. * Also use as the light direction on spot and directional lights.
  47921. */
  47922. get: function () {
  47923. return this._direction;
  47924. },
  47925. /**
  47926. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  47927. * Also use as the light direction on spot and directional lights.
  47928. */
  47929. set: function (value) {
  47930. this._setDirection(value);
  47931. },
  47932. enumerable: true,
  47933. configurable: true
  47934. });
  47935. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  47936. /**
  47937. * Gets the shadow projection clipping minimum z value.
  47938. */
  47939. get: function () {
  47940. return this._shadowMinZ;
  47941. },
  47942. /**
  47943. * Sets the shadow projection clipping minimum z value.
  47944. */
  47945. set: function (value) {
  47946. this._shadowMinZ = value;
  47947. this.forceProjectionMatrixCompute();
  47948. },
  47949. enumerable: true,
  47950. configurable: true
  47951. });
  47952. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  47953. /**
  47954. * Sets the shadow projection clipping maximum z value.
  47955. */
  47956. get: function () {
  47957. return this._shadowMaxZ;
  47958. },
  47959. /**
  47960. * Gets the shadow projection clipping maximum z value.
  47961. */
  47962. set: function (value) {
  47963. this._shadowMaxZ = value;
  47964. this.forceProjectionMatrixCompute();
  47965. },
  47966. enumerable: true,
  47967. configurable: true
  47968. });
  47969. /**
  47970. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  47971. * @returns true if the information has been computed, false if it does not need to (no parenting)
  47972. */
  47973. ShadowLight.prototype.computeTransformedInformation = function () {
  47974. if (this.parent && this.parent.getWorldMatrix) {
  47975. if (!this.transformedPosition) {
  47976. this.transformedPosition = BABYLON.Vector3.Zero();
  47977. }
  47978. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  47979. // In case the direction is present.
  47980. if (this.direction) {
  47981. if (!this.transformedDirection) {
  47982. this.transformedDirection = BABYLON.Vector3.Zero();
  47983. }
  47984. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  47985. }
  47986. return true;
  47987. }
  47988. return false;
  47989. };
  47990. /**
  47991. * Return the depth scale used for the shadow map.
  47992. * @returns the depth scale.
  47993. */
  47994. ShadowLight.prototype.getDepthScale = function () {
  47995. return 50.0;
  47996. };
  47997. /**
  47998. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  47999. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48000. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48001. */
  48002. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48003. return this.transformedDirection ? this.transformedDirection : this.direction;
  48004. };
  48005. /**
  48006. * Returns the ShadowLight absolute position in the World.
  48007. * @returns the position vector in world space
  48008. */
  48009. ShadowLight.prototype.getAbsolutePosition = function () {
  48010. return this.transformedPosition ? this.transformedPosition : this.position;
  48011. };
  48012. /**
  48013. * Sets the ShadowLight direction toward the passed target.
  48014. * @param target The point tot target in local space
  48015. * @returns the updated ShadowLight direction
  48016. */
  48017. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48018. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48019. return this.direction;
  48020. };
  48021. /**
  48022. * Returns the light rotation in euler definition.
  48023. * @returns the x y z rotation in local space.
  48024. */
  48025. ShadowLight.prototype.getRotation = function () {
  48026. this.direction.normalize();
  48027. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48028. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48029. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48030. };
  48031. /**
  48032. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48033. * @returns true if a cube texture needs to be use
  48034. */
  48035. ShadowLight.prototype.needCube = function () {
  48036. return false;
  48037. };
  48038. /**
  48039. * Detects if the projection matrix requires to be recomputed this frame.
  48040. * @returns true if it requires to be recomputed otherwise, false.
  48041. */
  48042. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48043. return this._needProjectionMatrixCompute;
  48044. };
  48045. /**
  48046. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48047. */
  48048. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48049. this._needProjectionMatrixCompute = true;
  48050. };
  48051. /**
  48052. * Get the world matrix of the sahdow lights.
  48053. * @hidden Internal Use Only
  48054. */
  48055. ShadowLight.prototype._getWorldMatrix = function () {
  48056. if (!this._worldMatrix) {
  48057. this._worldMatrix = BABYLON.Matrix.Identity();
  48058. }
  48059. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48060. return this._worldMatrix;
  48061. };
  48062. /**
  48063. * Gets the minZ used for shadow according to both the scene and the light.
  48064. * @param activeCamera The camera we are returning the min for
  48065. * @returns the depth min z
  48066. */
  48067. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48068. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48069. };
  48070. /**
  48071. * Gets the maxZ used for shadow according to both the scene and the light.
  48072. * @param activeCamera The camera we are returning the max for
  48073. * @returns the depth max z
  48074. */
  48075. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48076. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48077. };
  48078. /**
  48079. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48080. * @param matrix The materix to updated with the projection information
  48081. * @param viewMatrix The transform matrix of the light
  48082. * @param renderList The list of mesh to render in the map
  48083. * @returns The current light
  48084. */
  48085. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48086. if (this.customProjectionMatrixBuilder) {
  48087. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48088. }
  48089. else {
  48090. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48091. }
  48092. return this;
  48093. };
  48094. __decorate([
  48095. BABYLON.serializeAsVector3()
  48096. ], ShadowLight.prototype, "position", null);
  48097. __decorate([
  48098. BABYLON.serializeAsVector3()
  48099. ], ShadowLight.prototype, "direction", null);
  48100. __decorate([
  48101. BABYLON.serialize()
  48102. ], ShadowLight.prototype, "shadowMinZ", null);
  48103. __decorate([
  48104. BABYLON.serialize()
  48105. ], ShadowLight.prototype, "shadowMaxZ", null);
  48106. return ShadowLight;
  48107. }(BABYLON.Light));
  48108. BABYLON.ShadowLight = ShadowLight;
  48109. })(BABYLON || (BABYLON = {}));
  48110. //# sourceMappingURL=babylon.shadowLight.js.map
  48111. var BABYLON;
  48112. (function (BABYLON) {
  48113. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48114. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48115. });
  48116. /**
  48117. * A point light is a light defined by an unique point in world space.
  48118. * The light is emitted in every direction from this point.
  48119. * A good example of a point light is a standard light bulb.
  48120. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48121. */
  48122. var PointLight = /** @class */ (function (_super) {
  48123. __extends(PointLight, _super);
  48124. /**
  48125. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48126. * A PointLight emits the light in every direction.
  48127. * It can cast shadows.
  48128. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48129. * ```javascript
  48130. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48131. * ```
  48132. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48133. * @param name The light friendly name
  48134. * @param position The position of the point light in the scene
  48135. * @param scene The scene the lights belongs to
  48136. */
  48137. function PointLight(name, position, scene) {
  48138. var _this = _super.call(this, name, scene) || this;
  48139. _this._shadowAngle = Math.PI / 2;
  48140. _this.position = position;
  48141. return _this;
  48142. }
  48143. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48144. /**
  48145. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48146. * This specifies what angle the shadow will use to be created.
  48147. *
  48148. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48149. */
  48150. get: function () {
  48151. return this._shadowAngle;
  48152. },
  48153. /**
  48154. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48155. * This specifies what angle the shadow will use to be created.
  48156. *
  48157. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48158. */
  48159. set: function (value) {
  48160. this._shadowAngle = value;
  48161. this.forceProjectionMatrixCompute();
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. Object.defineProperty(PointLight.prototype, "direction", {
  48167. /**
  48168. * Gets the direction if it has been set.
  48169. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48170. */
  48171. get: function () {
  48172. return this._direction;
  48173. },
  48174. /**
  48175. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48176. */
  48177. set: function (value) {
  48178. var previousNeedCube = this.needCube();
  48179. this._direction = value;
  48180. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48181. this._shadowGenerator.recreateShadowMap();
  48182. }
  48183. },
  48184. enumerable: true,
  48185. configurable: true
  48186. });
  48187. /**
  48188. * Returns the string "PointLight"
  48189. * @returns the class name
  48190. */
  48191. PointLight.prototype.getClassName = function () {
  48192. return "PointLight";
  48193. };
  48194. /**
  48195. * Returns the integer 0.
  48196. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48197. */
  48198. PointLight.prototype.getTypeID = function () {
  48199. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48200. };
  48201. /**
  48202. * Specifies wether or not the shadowmap should be a cube texture.
  48203. * @returns true if the shadowmap needs to be a cube texture.
  48204. */
  48205. PointLight.prototype.needCube = function () {
  48206. return !this.direction;
  48207. };
  48208. /**
  48209. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48210. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48211. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48212. */
  48213. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48214. if (this.direction) {
  48215. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48216. }
  48217. else {
  48218. switch (faceIndex) {
  48219. case 0:
  48220. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48221. case 1:
  48222. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48223. case 2:
  48224. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48225. case 3:
  48226. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48227. case 4:
  48228. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48229. case 5:
  48230. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48231. }
  48232. }
  48233. return BABYLON.Vector3.Zero();
  48234. };
  48235. /**
  48236. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48237. * - fov = PI / 2
  48238. * - aspect ratio : 1.0
  48239. * - z-near and far equal to the active camera minZ and maxZ.
  48240. * Returns the PointLight.
  48241. */
  48242. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48243. var activeCamera = this.getScene().activeCamera;
  48244. if (!activeCamera) {
  48245. return;
  48246. }
  48247. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48248. };
  48249. PointLight.prototype._buildUniformLayout = function () {
  48250. this._uniformBuffer.addUniform("vLightData", 4);
  48251. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48252. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48253. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48254. this._uniformBuffer.addUniform("depthValues", 2);
  48255. this._uniformBuffer.create();
  48256. };
  48257. /**
  48258. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48259. * @param effect The effect to update
  48260. * @param lightIndex The index of the light in the effect to update
  48261. * @returns The point light
  48262. */
  48263. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48264. if (this.computeTransformedInformation()) {
  48265. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48266. return this;
  48267. }
  48268. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48269. return this;
  48270. };
  48271. /**
  48272. * Prepares the list of defines specific to the light type.
  48273. * @param defines the list of defines
  48274. * @param lightIndex defines the index of the light for the effect
  48275. */
  48276. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48277. defines["POINTLIGHT" + lightIndex] = true;
  48278. };
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], PointLight.prototype, "shadowAngle", null);
  48282. return PointLight;
  48283. }(BABYLON.ShadowLight));
  48284. BABYLON.PointLight = PointLight;
  48285. })(BABYLON || (BABYLON = {}));
  48286. //# sourceMappingURL=babylon.pointLight.js.map
  48287. var BABYLON;
  48288. (function (BABYLON) {
  48289. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48290. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48291. });
  48292. /**
  48293. * A directional light is defined by a direction (what a surprise!).
  48294. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48295. * 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.
  48296. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48297. */
  48298. var DirectionalLight = /** @class */ (function (_super) {
  48299. __extends(DirectionalLight, _super);
  48300. /**
  48301. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48302. * The directional light is emitted from everywhere in the given direction.
  48303. * It can cast shawdows.
  48304. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48305. * @param name The friendly name of the light
  48306. * @param direction The direction of the light
  48307. * @param scene The scene the light belongs to
  48308. */
  48309. function DirectionalLight(name, direction, scene) {
  48310. var _this = _super.call(this, name, scene) || this;
  48311. _this._shadowFrustumSize = 0;
  48312. _this._shadowOrthoScale = 0.1;
  48313. /**
  48314. * Automatically compute the projection matrix to best fit (including all the casters)
  48315. * on each frame.
  48316. */
  48317. _this.autoUpdateExtends = true;
  48318. // Cache
  48319. _this._orthoLeft = Number.MAX_VALUE;
  48320. _this._orthoRight = Number.MIN_VALUE;
  48321. _this._orthoTop = Number.MIN_VALUE;
  48322. _this._orthoBottom = Number.MAX_VALUE;
  48323. _this.position = direction.scale(-1.0);
  48324. _this.direction = direction;
  48325. return _this;
  48326. }
  48327. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48328. /**
  48329. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48330. */
  48331. get: function () {
  48332. return this._shadowFrustumSize;
  48333. },
  48334. /**
  48335. * Specifies a fix frustum size for the shadow generation.
  48336. */
  48337. set: function (value) {
  48338. this._shadowFrustumSize = value;
  48339. this.forceProjectionMatrixCompute();
  48340. },
  48341. enumerable: true,
  48342. configurable: true
  48343. });
  48344. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48345. /**
  48346. * Gets the shadow projection scale against the optimal computed one.
  48347. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48348. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48349. */
  48350. get: function () {
  48351. return this._shadowOrthoScale;
  48352. },
  48353. /**
  48354. * Sets the shadow projection scale against the optimal computed one.
  48355. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48356. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48357. */
  48358. set: function (value) {
  48359. this._shadowOrthoScale = value;
  48360. this.forceProjectionMatrixCompute();
  48361. },
  48362. enumerable: true,
  48363. configurable: true
  48364. });
  48365. /**
  48366. * Returns the string "DirectionalLight".
  48367. * @return The class name
  48368. */
  48369. DirectionalLight.prototype.getClassName = function () {
  48370. return "DirectionalLight";
  48371. };
  48372. /**
  48373. * Returns the integer 1.
  48374. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48375. */
  48376. DirectionalLight.prototype.getTypeID = function () {
  48377. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48378. };
  48379. /**
  48380. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48381. * Returns the DirectionalLight Shadow projection matrix.
  48382. */
  48383. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48384. if (this.shadowFrustumSize > 0) {
  48385. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48386. }
  48387. else {
  48388. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48389. }
  48390. };
  48391. /**
  48392. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48393. * Returns the DirectionalLight Shadow projection matrix.
  48394. */
  48395. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48396. var activeCamera = this.getScene().activeCamera;
  48397. if (!activeCamera) {
  48398. return;
  48399. }
  48400. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48401. };
  48402. /**
  48403. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48404. * Returns the DirectionalLight Shadow projection matrix.
  48405. */
  48406. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48407. var activeCamera = this.getScene().activeCamera;
  48408. if (!activeCamera) {
  48409. return;
  48410. }
  48411. // Check extends
  48412. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48413. var tempVector3 = BABYLON.Vector3.Zero();
  48414. this._orthoLeft = Number.MAX_VALUE;
  48415. this._orthoRight = Number.MIN_VALUE;
  48416. this._orthoTop = Number.MIN_VALUE;
  48417. this._orthoBottom = Number.MAX_VALUE;
  48418. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48419. var mesh = renderList[meshIndex];
  48420. if (!mesh) {
  48421. continue;
  48422. }
  48423. var boundingInfo = mesh.getBoundingInfo();
  48424. var boundingBox = boundingInfo.boundingBox;
  48425. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48426. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48427. if (tempVector3.x < this._orthoLeft)
  48428. this._orthoLeft = tempVector3.x;
  48429. if (tempVector3.y < this._orthoBottom)
  48430. this._orthoBottom = tempVector3.y;
  48431. if (tempVector3.x > this._orthoRight)
  48432. this._orthoRight = tempVector3.x;
  48433. if (tempVector3.y > this._orthoTop)
  48434. this._orthoTop = tempVector3.y;
  48435. }
  48436. }
  48437. }
  48438. var xOffset = this._orthoRight - this._orthoLeft;
  48439. var yOffset = this._orthoTop - this._orthoBottom;
  48440. 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);
  48441. };
  48442. DirectionalLight.prototype._buildUniformLayout = function () {
  48443. this._uniformBuffer.addUniform("vLightData", 4);
  48444. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48445. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48446. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48447. this._uniformBuffer.addUniform("depthValues", 2);
  48448. this._uniformBuffer.create();
  48449. };
  48450. /**
  48451. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48452. * @param effect The effect to update
  48453. * @param lightIndex The index of the light in the effect to update
  48454. * @returns The directional light
  48455. */
  48456. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48457. if (this.computeTransformedInformation()) {
  48458. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48459. return this;
  48460. }
  48461. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48462. return this;
  48463. };
  48464. /**
  48465. * Gets the minZ used for shadow according to both the scene and the light.
  48466. *
  48467. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48468. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48469. * @param activeCamera The camera we are returning the min for
  48470. * @returns the depth min z
  48471. */
  48472. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48473. return 1;
  48474. };
  48475. /**
  48476. * Gets the maxZ used for shadow according to both the scene and the light.
  48477. *
  48478. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48479. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48480. * @param activeCamera The camera we are returning the max for
  48481. * @returns the depth max z
  48482. */
  48483. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48484. return 1;
  48485. };
  48486. /**
  48487. * Prepares the list of defines specific to the light type.
  48488. * @param defines the list of defines
  48489. * @param lightIndex defines the index of the light for the effect
  48490. */
  48491. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48492. defines["DIRLIGHT" + lightIndex] = true;
  48493. };
  48494. __decorate([
  48495. BABYLON.serialize()
  48496. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48497. __decorate([
  48498. BABYLON.serialize()
  48499. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48500. __decorate([
  48501. BABYLON.serialize()
  48502. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48503. return DirectionalLight;
  48504. }(BABYLON.ShadowLight));
  48505. BABYLON.DirectionalLight = DirectionalLight;
  48506. })(BABYLON || (BABYLON = {}));
  48507. //# sourceMappingURL=babylon.directionalLight.js.map
  48508. var BABYLON;
  48509. (function (BABYLON) {
  48510. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48511. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48512. });
  48513. /**
  48514. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48515. * These values define a cone of light starting from the position, emitting toward the direction.
  48516. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48517. * and the exponent defines the speed of the decay of the light with distance (reach).
  48518. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48519. */
  48520. var SpotLight = /** @class */ (function (_super) {
  48521. __extends(SpotLight, _super);
  48522. /**
  48523. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48524. * It can cast shadows.
  48525. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48526. * @param name The light friendly name
  48527. * @param position The position of the spot light in the scene
  48528. * @param direction The direction of the light in the scene
  48529. * @param angle The cone angle of the light in Radians
  48530. * @param exponent The light decay speed with the distance from the emission spot
  48531. * @param scene The scene the lights belongs to
  48532. */
  48533. function SpotLight(name, position, direction, angle, exponent, scene) {
  48534. var _this = _super.call(this, name, scene) || this;
  48535. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48536. _this._projectionTextureLightNear = 1e-6;
  48537. _this._projectionTextureLightFar = 1000.0;
  48538. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48539. _this._projectionTextureViewLightDirty = true;
  48540. _this._projectionTextureProjectionLightDirty = true;
  48541. _this._projectionTextureDirty = true;
  48542. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48543. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48544. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48545. _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);
  48546. _this.position = position;
  48547. _this.direction = direction;
  48548. _this.angle = angle;
  48549. _this.exponent = exponent;
  48550. return _this;
  48551. }
  48552. Object.defineProperty(SpotLight.prototype, "angle", {
  48553. /**
  48554. * Gets the cone angle of the spot light in Radians.
  48555. */
  48556. get: function () {
  48557. return this._angle;
  48558. },
  48559. /**
  48560. * Sets the cone angle of the spot light in Radians.
  48561. */
  48562. set: function (value) {
  48563. this._angle = value;
  48564. this._projectionTextureProjectionLightDirty = true;
  48565. this.forceProjectionMatrixCompute();
  48566. },
  48567. enumerable: true,
  48568. configurable: true
  48569. });
  48570. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48571. /**
  48572. * Allows scaling the angle of the light for shadow generation only.
  48573. */
  48574. get: function () {
  48575. return this._shadowAngleScale;
  48576. },
  48577. /**
  48578. * Allows scaling the angle of the light for shadow generation only.
  48579. */
  48580. set: function (value) {
  48581. this._shadowAngleScale = value;
  48582. this.forceProjectionMatrixCompute();
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48588. /**
  48589. * Allows reading the projecton texture
  48590. */
  48591. get: function () {
  48592. return this._projectionTextureMatrix;
  48593. },
  48594. enumerable: true,
  48595. configurable: true
  48596. });
  48597. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48598. /**
  48599. * Gets the near clip of the Spotlight for texture projection.
  48600. */
  48601. get: function () {
  48602. return this._projectionTextureLightNear;
  48603. },
  48604. /**
  48605. * Sets the near clip of the Spotlight for texture projection.
  48606. */
  48607. set: function (value) {
  48608. this._projectionTextureLightNear = value;
  48609. this._projectionTextureProjectionLightDirty = true;
  48610. },
  48611. enumerable: true,
  48612. configurable: true
  48613. });
  48614. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48615. /**
  48616. * Gets the far clip of the Spotlight for texture projection.
  48617. */
  48618. get: function () {
  48619. return this._projectionTextureLightFar;
  48620. },
  48621. /**
  48622. * Sets the far clip of the Spotlight for texture projection.
  48623. */
  48624. set: function (value) {
  48625. this._projectionTextureLightFar = value;
  48626. this._projectionTextureProjectionLightDirty = true;
  48627. },
  48628. enumerable: true,
  48629. configurable: true
  48630. });
  48631. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48632. /**
  48633. * Gets the Up vector of the Spotlight for texture projection.
  48634. */
  48635. get: function () {
  48636. return this._projectionTextureUpDirection;
  48637. },
  48638. /**
  48639. * Sets the Up vector of the Spotlight for texture projection.
  48640. */
  48641. set: function (value) {
  48642. this._projectionTextureUpDirection = value;
  48643. this._projectionTextureProjectionLightDirty = true;
  48644. },
  48645. enumerable: true,
  48646. configurable: true
  48647. });
  48648. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48649. /**
  48650. * Gets the projection texture of the light.
  48651. */
  48652. get: function () {
  48653. return this._projectionTexture;
  48654. },
  48655. /**
  48656. * Sets the projection texture of the light.
  48657. */
  48658. set: function (value) {
  48659. this._projectionTexture = value;
  48660. this._projectionTextureDirty = true;
  48661. },
  48662. enumerable: true,
  48663. configurable: true
  48664. });
  48665. /**
  48666. * Returns the string "SpotLight".
  48667. * @returns the class name
  48668. */
  48669. SpotLight.prototype.getClassName = function () {
  48670. return "SpotLight";
  48671. };
  48672. /**
  48673. * Returns the integer 2.
  48674. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48675. */
  48676. SpotLight.prototype.getTypeID = function () {
  48677. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48678. };
  48679. /**
  48680. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48681. */
  48682. SpotLight.prototype._setDirection = function (value) {
  48683. _super.prototype._setDirection.call(this, value);
  48684. this._projectionTextureViewLightDirty = true;
  48685. };
  48686. /**
  48687. * Overrides the position setter to recompute the projection texture view light Matrix.
  48688. */
  48689. SpotLight.prototype._setPosition = function (value) {
  48690. _super.prototype._setPosition.call(this, value);
  48691. this._projectionTextureViewLightDirty = true;
  48692. };
  48693. /**
  48694. * 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.
  48695. * Returns the SpotLight.
  48696. */
  48697. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48698. var activeCamera = this.getScene().activeCamera;
  48699. if (!activeCamera) {
  48700. return;
  48701. }
  48702. this._shadowAngleScale = this._shadowAngleScale || 1;
  48703. var angle = this._shadowAngleScale * this._angle;
  48704. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48705. };
  48706. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48707. this._projectionTextureViewLightDirty = false;
  48708. this._projectionTextureDirty = true;
  48709. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48710. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48711. };
  48712. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48713. this._projectionTextureProjectionLightDirty = false;
  48714. this._projectionTextureDirty = true;
  48715. var light_far = this.projectionTextureLightFar;
  48716. var light_near = this.projectionTextureLightNear;
  48717. var P = light_far / (light_far - light_near);
  48718. var Q = -P * light_near;
  48719. var S = 1.0 / Math.tan(this._angle / 2.0);
  48720. var A = 1.0;
  48721. 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);
  48722. };
  48723. /**
  48724. * Main function for light texture projection matrix computing.
  48725. */
  48726. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48727. this._projectionTextureDirty = false;
  48728. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48729. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48730. };
  48731. SpotLight.prototype._buildUniformLayout = function () {
  48732. this._uniformBuffer.addUniform("vLightData", 4);
  48733. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48734. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48735. this._uniformBuffer.addUniform("vLightDirection", 3);
  48736. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48737. this._uniformBuffer.addUniform("depthValues", 2);
  48738. this._uniformBuffer.create();
  48739. };
  48740. /**
  48741. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48742. * @param effect The effect to update
  48743. * @param lightIndex The index of the light in the effect to update
  48744. * @returns The spot light
  48745. */
  48746. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48747. var normalizeDirection;
  48748. if (this.computeTransformedInformation()) {
  48749. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48750. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48751. }
  48752. else {
  48753. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48754. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48755. }
  48756. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48757. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48758. if (this._projectionTextureViewLightDirty) {
  48759. this._computeProjectionTextureViewLightMatrix();
  48760. }
  48761. if (this._projectionTextureProjectionLightDirty) {
  48762. this._computeProjectionTextureProjectionLightMatrix();
  48763. }
  48764. if (this._projectionTextureDirty) {
  48765. this._computeProjectionTextureMatrix();
  48766. }
  48767. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48768. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48769. }
  48770. return this;
  48771. };
  48772. /**
  48773. * Disposes the light and the associated resources.
  48774. */
  48775. SpotLight.prototype.dispose = function () {
  48776. _super.prototype.dispose.call(this);
  48777. if (this._projectionTexture) {
  48778. this._projectionTexture.dispose();
  48779. }
  48780. };
  48781. /**
  48782. * Prepares the list of defines specific to the light type.
  48783. * @param defines the list of defines
  48784. * @param lightIndex defines the index of the light for the effect
  48785. */
  48786. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48787. defines["SPOTLIGHT" + lightIndex] = true;
  48788. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  48789. };
  48790. __decorate([
  48791. BABYLON.serialize()
  48792. ], SpotLight.prototype, "angle", null);
  48793. __decorate([
  48794. BABYLON.serialize()
  48795. ], SpotLight.prototype, "shadowAngleScale", null);
  48796. __decorate([
  48797. BABYLON.serialize()
  48798. ], SpotLight.prototype, "exponent", void 0);
  48799. __decorate([
  48800. BABYLON.serialize()
  48801. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48802. __decorate([
  48803. BABYLON.serialize()
  48804. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48805. __decorate([
  48806. BABYLON.serialize()
  48807. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48808. __decorate([
  48809. BABYLON.serializeAsTexture("projectedLightTexture")
  48810. ], SpotLight.prototype, "_projectionTexture", void 0);
  48811. return SpotLight;
  48812. }(BABYLON.ShadowLight));
  48813. BABYLON.SpotLight = SpotLight;
  48814. })(BABYLON || (BABYLON = {}));
  48815. //# sourceMappingURL=babylon.spotLight.js.map
  48816. var BABYLON;
  48817. (function (BABYLON) {
  48818. /**
  48819. * Class used to override all child animations of a given target
  48820. */
  48821. var AnimationPropertiesOverride = /** @class */ (function () {
  48822. function AnimationPropertiesOverride() {
  48823. /**
  48824. * Gets or sets a value indicating if animation blending must be used
  48825. */
  48826. this.enableBlending = false;
  48827. /**
  48828. * Gets or sets the blending speed to use when enableBlending is true
  48829. */
  48830. this.blendingSpeed = 0.01;
  48831. /**
  48832. * Gets or sets the default loop mode to use
  48833. */
  48834. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48835. }
  48836. return AnimationPropertiesOverride;
  48837. }());
  48838. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48839. })(BABYLON || (BABYLON = {}));
  48840. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48841. var BABYLON;
  48842. (function (BABYLON) {
  48843. /**
  48844. * Represents the range of an animation
  48845. */
  48846. var AnimationRange = /** @class */ (function () {
  48847. /**
  48848. * Initializes the range of an animation
  48849. * @param name The name of the animation range
  48850. * @param from The starting frame of the animation
  48851. * @param to The ending frame of the animation
  48852. */
  48853. function AnimationRange(
  48854. /**The name of the animation range**/
  48855. name,
  48856. /**The starting frame of the animation */
  48857. from,
  48858. /**The ending frame of the animation*/
  48859. to) {
  48860. this.name = name;
  48861. this.from = from;
  48862. this.to = to;
  48863. }
  48864. /**
  48865. * Makes a copy of the animation range
  48866. * @returns A copy of the animation range
  48867. */
  48868. AnimationRange.prototype.clone = function () {
  48869. return new AnimationRange(this.name, this.from, this.to);
  48870. };
  48871. return AnimationRange;
  48872. }());
  48873. BABYLON.AnimationRange = AnimationRange;
  48874. /**
  48875. * Composed of a frame, and an action function
  48876. */
  48877. var AnimationEvent = /** @class */ (function () {
  48878. /**
  48879. * Initializes the animation event
  48880. * @param frame The frame for which the event is triggered
  48881. * @param action The event to perform when triggered
  48882. * @param onlyOnce Specifies if the event should be triggered only once
  48883. */
  48884. function AnimationEvent(
  48885. /** The frame for which the event is triggered **/
  48886. frame,
  48887. /** The event to perform when triggered **/
  48888. action,
  48889. /** Specifies if the event should be triggered only once**/
  48890. onlyOnce) {
  48891. this.frame = frame;
  48892. this.action = action;
  48893. this.onlyOnce = onlyOnce;
  48894. /**
  48895. * Specifies if the animation event is done
  48896. */
  48897. this.isDone = false;
  48898. }
  48899. /** @hidden */
  48900. AnimationEvent.prototype._clone = function () {
  48901. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  48902. };
  48903. return AnimationEvent;
  48904. }());
  48905. BABYLON.AnimationEvent = AnimationEvent;
  48906. /**
  48907. * A cursor which tracks a point on a path
  48908. */
  48909. var PathCursor = /** @class */ (function () {
  48910. /**
  48911. * Initializes the path cursor
  48912. * @param path The path to track
  48913. */
  48914. function PathCursor(path) {
  48915. this.path = path;
  48916. /**
  48917. * Stores path cursor callbacks for when an onchange event is triggered
  48918. */
  48919. this._onchange = new Array();
  48920. /**
  48921. * The value of the path cursor
  48922. */
  48923. this.value = 0;
  48924. /**
  48925. * The animation array of the path cursor
  48926. */
  48927. this.animations = new Array();
  48928. }
  48929. /**
  48930. * Gets the cursor point on the path
  48931. * @returns A point on the path cursor at the cursor location
  48932. */
  48933. PathCursor.prototype.getPoint = function () {
  48934. var point = this.path.getPointAtLengthPosition(this.value);
  48935. return new BABYLON.Vector3(point.x, 0, point.y);
  48936. };
  48937. /**
  48938. * Moves the cursor ahead by the step amount
  48939. * @param step The amount to move the cursor forward
  48940. * @returns This path cursor
  48941. */
  48942. PathCursor.prototype.moveAhead = function (step) {
  48943. if (step === void 0) { step = 0.002; }
  48944. this.move(step);
  48945. return this;
  48946. };
  48947. /**
  48948. * Moves the cursor behind by the step amount
  48949. * @param step The amount to move the cursor back
  48950. * @returns This path cursor
  48951. */
  48952. PathCursor.prototype.moveBack = function (step) {
  48953. if (step === void 0) { step = 0.002; }
  48954. this.move(-step);
  48955. return this;
  48956. };
  48957. /**
  48958. * Moves the cursor by the step amount
  48959. * If the step amount is greater than one, an exception is thrown
  48960. * @param step The amount to move the cursor
  48961. * @returns This path cursor
  48962. */
  48963. PathCursor.prototype.move = function (step) {
  48964. if (Math.abs(step) > 1) {
  48965. throw "step size should be less than 1.";
  48966. }
  48967. this.value += step;
  48968. this.ensureLimits();
  48969. this.raiseOnChange();
  48970. return this;
  48971. };
  48972. /**
  48973. * Ensures that the value is limited between zero and one
  48974. * @returns This path cursor
  48975. */
  48976. PathCursor.prototype.ensureLimits = function () {
  48977. while (this.value > 1) {
  48978. this.value -= 1;
  48979. }
  48980. while (this.value < 0) {
  48981. this.value += 1;
  48982. }
  48983. return this;
  48984. };
  48985. /**
  48986. * Runs onchange callbacks on change (used by the animation engine)
  48987. * @returns This path cursor
  48988. */
  48989. PathCursor.prototype.raiseOnChange = function () {
  48990. var _this = this;
  48991. this._onchange.forEach(function (f) { return f(_this); });
  48992. return this;
  48993. };
  48994. /**
  48995. * Executes a function on change
  48996. * @param f A path cursor onchange callback
  48997. * @returns This path cursor
  48998. */
  48999. PathCursor.prototype.onchange = function (f) {
  49000. this._onchange.push(f);
  49001. return this;
  49002. };
  49003. return PathCursor;
  49004. }());
  49005. BABYLON.PathCursor = PathCursor;
  49006. /**
  49007. * Enum for the animation key frame interpolation type
  49008. */
  49009. var AnimationKeyInterpolation;
  49010. (function (AnimationKeyInterpolation) {
  49011. /**
  49012. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49013. */
  49014. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49015. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49016. /**
  49017. * Class used to store any kind of animation
  49018. */
  49019. var Animation = /** @class */ (function () {
  49020. /**
  49021. * Initializes the animation
  49022. * @param name Name of the animation
  49023. * @param targetProperty Property to animate
  49024. * @param framePerSecond The frames per second of the animation
  49025. * @param dataType The data type of the animation
  49026. * @param loopMode The loop mode of the animation
  49027. * @param enableBlendings Specifies if blending should be enabled
  49028. */
  49029. function Animation(
  49030. /**Name of the animation */
  49031. name,
  49032. /**Property to animate */
  49033. targetProperty,
  49034. /**The frames per second of the animation */
  49035. framePerSecond,
  49036. /**The data type of the animation */
  49037. dataType,
  49038. /**The loop mode of the animation */
  49039. loopMode,
  49040. /**Specifies if blending should be enabled */
  49041. enableBlending) {
  49042. this.name = name;
  49043. this.targetProperty = targetProperty;
  49044. this.framePerSecond = framePerSecond;
  49045. this.dataType = dataType;
  49046. this.loopMode = loopMode;
  49047. this.enableBlending = enableBlending;
  49048. /**
  49049. * @hidden Internal use only
  49050. */
  49051. this._runtimeAnimations = new Array();
  49052. /**
  49053. * The set of event that will be linked to this animation
  49054. */
  49055. this._events = new Array();
  49056. /**
  49057. * Stores the blending speed of the animation
  49058. */
  49059. this.blendingSpeed = 0.01;
  49060. /**
  49061. * Stores the animation ranges for the animation
  49062. */
  49063. this._ranges = {};
  49064. this.targetPropertyPath = targetProperty.split(".");
  49065. this.dataType = dataType;
  49066. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49067. }
  49068. /**
  49069. * @hidden Internal use
  49070. */
  49071. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49072. var dataType = undefined;
  49073. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49074. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49075. }
  49076. else if (from instanceof BABYLON.Quaternion) {
  49077. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49078. }
  49079. else if (from instanceof BABYLON.Vector3) {
  49080. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49081. }
  49082. else if (from instanceof BABYLON.Vector2) {
  49083. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49084. }
  49085. else if (from instanceof BABYLON.Color3) {
  49086. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49087. }
  49088. else if (from instanceof BABYLON.Size) {
  49089. dataType = Animation.ANIMATIONTYPE_SIZE;
  49090. }
  49091. if (dataType == undefined) {
  49092. return null;
  49093. }
  49094. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49095. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49096. animation.setKeys(keys);
  49097. if (easingFunction !== undefined) {
  49098. animation.setEasingFunction(easingFunction);
  49099. }
  49100. return animation;
  49101. };
  49102. /**
  49103. * Sets up an animation
  49104. * @param property The property to animate
  49105. * @param animationType The animation type to apply
  49106. * @param framePerSecond The frames per second of the animation
  49107. * @param easingFunction The easing function used in the animation
  49108. * @returns The created animation
  49109. */
  49110. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49111. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49112. animation.setEasingFunction(easingFunction);
  49113. return animation;
  49114. };
  49115. /**
  49116. * Create and start an animation on a node
  49117. * @param name defines the name of the global animation that will be run on all nodes
  49118. * @param node defines the root node where the animation will take place
  49119. * @param targetProperty defines property to animate
  49120. * @param framePerSecond defines the number of frame per second yo use
  49121. * @param totalFrame defines the number of frames in total
  49122. * @param from defines the initial value
  49123. * @param to defines the final value
  49124. * @param loopMode defines which loop mode you want to use (off by default)
  49125. * @param easingFunction defines the easing function to use (linear by default)
  49126. * @param onAnimationEnd defines the callback to call when animation end
  49127. * @returns the animatable created for this animation
  49128. */
  49129. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49130. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49131. if (!animation) {
  49132. return null;
  49133. }
  49134. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49135. };
  49136. /**
  49137. * Create and start an animation on a node and its descendants
  49138. * @param name defines the name of the global animation that will be run on all nodes
  49139. * @param node defines the root node where the animation will take place
  49140. * @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
  49141. * @param targetProperty defines property to animate
  49142. * @param framePerSecond defines the number of frame per second to use
  49143. * @param totalFrame defines the number of frames in total
  49144. * @param from defines the initial value
  49145. * @param to defines the final value
  49146. * @param loopMode defines which loop mode you want to use (off by default)
  49147. * @param easingFunction defines the easing function to use (linear by default)
  49148. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49149. * @returns the list of animatables created for all nodes
  49150. * @example https://www.babylonjs-playground.com/#MH0VLI
  49151. */
  49152. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49153. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49154. if (!animation) {
  49155. return null;
  49156. }
  49157. var scene = node.getScene();
  49158. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49159. };
  49160. /**
  49161. * Creates a new animation, merges it with the existing animations and starts it
  49162. * @param name Name of the animation
  49163. * @param node Node which contains the scene that begins the animations
  49164. * @param targetProperty Specifies which property to animate
  49165. * @param framePerSecond The frames per second of the animation
  49166. * @param totalFrame The total number of frames
  49167. * @param from The frame at the beginning of the animation
  49168. * @param to The frame at the end of the animation
  49169. * @param loopMode Specifies the loop mode of the animation
  49170. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49171. * @param onAnimationEnd Callback to run once the animation is complete
  49172. * @returns Nullable animation
  49173. */
  49174. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49175. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49176. if (!animation) {
  49177. return null;
  49178. }
  49179. node.animations.push(animation);
  49180. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49181. };
  49182. /**
  49183. * Transition property of an host to the target Value
  49184. * @param property The property to transition
  49185. * @param targetValue The target Value of the property
  49186. * @param host The object where the property to animate belongs
  49187. * @param scene Scene used to run the animation
  49188. * @param frameRate Framerate (in frame/s) to use
  49189. * @param transition The transition type we want to use
  49190. * @param duration The duration of the animation, in milliseconds
  49191. * @param onAnimationEnd Callback trigger at the end of the animation
  49192. * @returns Nullable animation
  49193. */
  49194. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49195. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49196. if (duration <= 0) {
  49197. host[property] = targetValue;
  49198. if (onAnimationEnd) {
  49199. onAnimationEnd();
  49200. }
  49201. return null;
  49202. }
  49203. var endFrame = frameRate * (duration / 1000);
  49204. transition.setKeys([{
  49205. frame: 0,
  49206. value: host[property].clone ? host[property].clone() : host[property]
  49207. },
  49208. {
  49209. frame: endFrame,
  49210. value: targetValue
  49211. }]);
  49212. if (!host.animations) {
  49213. host.animations = [];
  49214. }
  49215. host.animations.push(transition);
  49216. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49217. animation.onAnimationEnd = onAnimationEnd;
  49218. return animation;
  49219. };
  49220. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49221. /**
  49222. * Return the array of runtime animations currently using this animation
  49223. */
  49224. get: function () {
  49225. return this._runtimeAnimations;
  49226. },
  49227. enumerable: true,
  49228. configurable: true
  49229. });
  49230. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49231. /**
  49232. * Specifies if any of the runtime animations are currently running
  49233. */
  49234. get: function () {
  49235. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49236. var runtimeAnimation = _a[_i];
  49237. if (!runtimeAnimation.isStopped) {
  49238. return true;
  49239. }
  49240. }
  49241. return false;
  49242. },
  49243. enumerable: true,
  49244. configurable: true
  49245. });
  49246. // Methods
  49247. /**
  49248. * Converts the animation to a string
  49249. * @param fullDetails support for multiple levels of logging within scene loading
  49250. * @returns String form of the animation
  49251. */
  49252. Animation.prototype.toString = function (fullDetails) {
  49253. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49254. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49255. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49256. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49257. if (fullDetails) {
  49258. ret += ", Ranges: {";
  49259. var first = true;
  49260. for (var name in this._ranges) {
  49261. if (first) {
  49262. ret += ", ";
  49263. first = false;
  49264. }
  49265. ret += name;
  49266. }
  49267. ret += "}";
  49268. }
  49269. return ret;
  49270. };
  49271. /**
  49272. * Add an event to this animation
  49273. * @param event Event to add
  49274. */
  49275. Animation.prototype.addEvent = function (event) {
  49276. this._events.push(event);
  49277. };
  49278. /**
  49279. * Remove all events found at the given frame
  49280. * @param frame The frame to remove events from
  49281. */
  49282. Animation.prototype.removeEvents = function (frame) {
  49283. for (var index = 0; index < this._events.length; index++) {
  49284. if (this._events[index].frame === frame) {
  49285. this._events.splice(index, 1);
  49286. index--;
  49287. }
  49288. }
  49289. };
  49290. /**
  49291. * Retrieves all the events from the animation
  49292. * @returns Events from the animation
  49293. */
  49294. Animation.prototype.getEvents = function () {
  49295. return this._events;
  49296. };
  49297. /**
  49298. * Creates an animation range
  49299. * @param name Name of the animation range
  49300. * @param from Starting frame of the animation range
  49301. * @param to Ending frame of the animation
  49302. */
  49303. Animation.prototype.createRange = function (name, from, to) {
  49304. // check name not already in use; could happen for bones after serialized
  49305. if (!this._ranges[name]) {
  49306. this._ranges[name] = new AnimationRange(name, from, to);
  49307. }
  49308. };
  49309. /**
  49310. * Deletes an animation range by name
  49311. * @param name Name of the animation range to delete
  49312. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49313. */
  49314. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49315. if (deleteFrames === void 0) { deleteFrames = true; }
  49316. var range = this._ranges[name];
  49317. if (!range) {
  49318. return;
  49319. }
  49320. if (deleteFrames) {
  49321. var from = range.from;
  49322. var to = range.to;
  49323. // this loop MUST go high to low for multiple splices to work
  49324. for (var key = this._keys.length - 1; key >= 0; key--) {
  49325. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49326. this._keys.splice(key, 1);
  49327. }
  49328. }
  49329. }
  49330. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49331. };
  49332. /**
  49333. * Gets the animation range by name, or null if not defined
  49334. * @param name Name of the animation range
  49335. * @returns Nullable animation range
  49336. */
  49337. Animation.prototype.getRange = function (name) {
  49338. return this._ranges[name];
  49339. };
  49340. /**
  49341. * Gets the key frames from the animation
  49342. * @returns The key frames of the animation
  49343. */
  49344. Animation.prototype.getKeys = function () {
  49345. return this._keys;
  49346. };
  49347. /**
  49348. * Gets the highest frame rate of the animation
  49349. * @returns Highest frame rate of the animation
  49350. */
  49351. Animation.prototype.getHighestFrame = function () {
  49352. var ret = 0;
  49353. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49354. if (ret < this._keys[key].frame) {
  49355. ret = this._keys[key].frame;
  49356. }
  49357. }
  49358. return ret;
  49359. };
  49360. /**
  49361. * Gets the easing function of the animation
  49362. * @returns Easing function of the animation
  49363. */
  49364. Animation.prototype.getEasingFunction = function () {
  49365. return this._easingFunction;
  49366. };
  49367. /**
  49368. * Sets the easing function of the animation
  49369. * @param easingFunction A custom mathematical formula for animation
  49370. */
  49371. Animation.prototype.setEasingFunction = function (easingFunction) {
  49372. this._easingFunction = easingFunction;
  49373. };
  49374. /**
  49375. * Interpolates a scalar linearly
  49376. * @param startValue Start value of the animation curve
  49377. * @param endValue End value of the animation curve
  49378. * @param gradient Scalar amount to interpolate
  49379. * @returns Interpolated scalar value
  49380. */
  49381. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49382. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49383. };
  49384. /**
  49385. * Interpolates a scalar cubically
  49386. * @param startValue Start value of the animation curve
  49387. * @param outTangent End tangent of the animation
  49388. * @param endValue End value of the animation curve
  49389. * @param inTangent Start tangent of the animation curve
  49390. * @param gradient Scalar amount to interpolate
  49391. * @returns Interpolated scalar value
  49392. */
  49393. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49394. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49395. };
  49396. /**
  49397. * Interpolates a quaternion using a spherical linear interpolation
  49398. * @param startValue Start value of the animation curve
  49399. * @param endValue End value of the animation curve
  49400. * @param gradient Scalar amount to interpolate
  49401. * @returns Interpolated quaternion value
  49402. */
  49403. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49404. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49405. };
  49406. /**
  49407. * Interpolates a quaternion cubically
  49408. * @param startValue Start value of the animation curve
  49409. * @param outTangent End tangent of the animation curve
  49410. * @param endValue End value of the animation curve
  49411. * @param inTangent Start tangent of the animation curve
  49412. * @param gradient Scalar amount to interpolate
  49413. * @returns Interpolated quaternion value
  49414. */
  49415. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49416. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49417. };
  49418. /**
  49419. * Interpolates a Vector3 linearl
  49420. * @param startValue Start value of the animation curve
  49421. * @param endValue End value of the animation curve
  49422. * @param gradient Scalar amount to interpolate
  49423. * @returns Interpolated scalar value
  49424. */
  49425. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49426. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49427. };
  49428. /**
  49429. * Interpolates a Vector3 cubically
  49430. * @param startValue Start value of the animation curve
  49431. * @param outTangent End tangent of the animation
  49432. * @param endValue End value of the animation curve
  49433. * @param inTangent Start tangent of the animation curve
  49434. * @param gradient Scalar amount to interpolate
  49435. * @returns InterpolatedVector3 value
  49436. */
  49437. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49438. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49439. };
  49440. /**
  49441. * Interpolates a Vector2 linearly
  49442. * @param startValue Start value of the animation curve
  49443. * @param endValue End value of the animation curve
  49444. * @param gradient Scalar amount to interpolate
  49445. * @returns Interpolated Vector2 value
  49446. */
  49447. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49448. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49449. };
  49450. /**
  49451. * Interpolates a Vector2 cubically
  49452. * @param startValue Start value of the animation curve
  49453. * @param outTangent End tangent of the animation
  49454. * @param endValue End value of the animation curve
  49455. * @param inTangent Start tangent of the animation curve
  49456. * @param gradient Scalar amount to interpolate
  49457. * @returns Interpolated Vector2 value
  49458. */
  49459. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49460. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49461. };
  49462. /**
  49463. * Interpolates a size linearly
  49464. * @param startValue Start value of the animation curve
  49465. * @param endValue End value of the animation curve
  49466. * @param gradient Scalar amount to interpolate
  49467. * @returns Interpolated Size value
  49468. */
  49469. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49470. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49471. };
  49472. /**
  49473. * Interpolates a Color3 linearly
  49474. * @param startValue Start value of the animation curve
  49475. * @param endValue End value of the animation curve
  49476. * @param gradient Scalar amount to interpolate
  49477. * @returns Interpolated Color3 value
  49478. */
  49479. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49480. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49481. };
  49482. /**
  49483. * @hidden Internal use only
  49484. */
  49485. Animation.prototype._getKeyValue = function (value) {
  49486. if (typeof value === "function") {
  49487. return value();
  49488. }
  49489. return value;
  49490. };
  49491. /**
  49492. * @hidden Internal use only
  49493. */
  49494. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49495. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49496. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49497. }
  49498. var keys = this.getKeys();
  49499. // Try to get a hash to find the right key
  49500. 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));
  49501. if (keys[startKeyIndex].frame >= currentFrame) {
  49502. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49503. startKeyIndex--;
  49504. }
  49505. }
  49506. for (var key = startKeyIndex; key < keys.length; key++) {
  49507. var endKey = keys[key + 1];
  49508. if (endKey.frame >= currentFrame) {
  49509. var startKey = keys[key];
  49510. var startValue = this._getKeyValue(startKey.value);
  49511. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49512. return startValue;
  49513. }
  49514. var endValue = this._getKeyValue(endKey.value);
  49515. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49516. var frameDelta = endKey.frame - startKey.frame;
  49517. // gradient : percent of currentFrame between the frame inf and the frame sup
  49518. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49519. // check for easingFunction and correction of gradient
  49520. var easingFunction = this.getEasingFunction();
  49521. if (easingFunction != null) {
  49522. gradient = easingFunction.ease(gradient);
  49523. }
  49524. switch (this.dataType) {
  49525. // Float
  49526. case Animation.ANIMATIONTYPE_FLOAT:
  49527. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49528. switch (loopMode) {
  49529. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49530. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49531. return floatValue;
  49532. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49533. return offsetValue * repeatCount + floatValue;
  49534. }
  49535. break;
  49536. // Quaternion
  49537. case Animation.ANIMATIONTYPE_QUATERNION:
  49538. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49539. switch (loopMode) {
  49540. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49541. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49542. return quatValue;
  49543. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49544. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49545. }
  49546. return quatValue;
  49547. // Vector3
  49548. case Animation.ANIMATIONTYPE_VECTOR3:
  49549. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49550. switch (loopMode) {
  49551. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49552. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49553. return vec3Value;
  49554. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49555. return vec3Value.add(offsetValue.scale(repeatCount));
  49556. }
  49557. // Vector2
  49558. case Animation.ANIMATIONTYPE_VECTOR2:
  49559. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49560. switch (loopMode) {
  49561. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49562. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49563. return vec2Value;
  49564. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49565. return vec2Value.add(offsetValue.scale(repeatCount));
  49566. }
  49567. // Size
  49568. case Animation.ANIMATIONTYPE_SIZE:
  49569. switch (loopMode) {
  49570. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49571. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49572. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49573. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49574. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49575. }
  49576. // Color3
  49577. case Animation.ANIMATIONTYPE_COLOR3:
  49578. switch (loopMode) {
  49579. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49580. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49581. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49582. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49583. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49584. }
  49585. // Matrix
  49586. case Animation.ANIMATIONTYPE_MATRIX:
  49587. switch (loopMode) {
  49588. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49589. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49590. if (Animation.AllowMatricesInterpolation) {
  49591. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49592. }
  49593. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49594. return startValue;
  49595. }
  49596. default:
  49597. break;
  49598. }
  49599. break;
  49600. }
  49601. }
  49602. return this._getKeyValue(keys[keys.length - 1].value);
  49603. };
  49604. /**
  49605. * Defines the function to use to interpolate matrices
  49606. * @param startValue defines the start matrix
  49607. * @param endValue defines the end matrix
  49608. * @param gradient defines the gradient between both matrices
  49609. * @param result defines an optional target matrix where to store the interpolation
  49610. * @returns the interpolated matrix
  49611. */
  49612. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49613. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49614. if (result) {
  49615. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49616. return result;
  49617. }
  49618. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49619. }
  49620. if (result) {
  49621. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49622. return result;
  49623. }
  49624. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49625. };
  49626. /**
  49627. * Makes a copy of the animation
  49628. * @returns Cloned animation
  49629. */
  49630. Animation.prototype.clone = function () {
  49631. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49632. clone.enableBlending = this.enableBlending;
  49633. clone.blendingSpeed = this.blendingSpeed;
  49634. if (this._keys) {
  49635. clone.setKeys(this._keys);
  49636. }
  49637. if (this._ranges) {
  49638. clone._ranges = {};
  49639. for (var name in this._ranges) {
  49640. var range = this._ranges[name];
  49641. if (!range) {
  49642. continue;
  49643. }
  49644. clone._ranges[name] = range.clone();
  49645. }
  49646. }
  49647. return clone;
  49648. };
  49649. /**
  49650. * Sets the key frames of the animation
  49651. * @param values The animation key frames to set
  49652. */
  49653. Animation.prototype.setKeys = function (values) {
  49654. this._keys = values.slice(0);
  49655. };
  49656. /**
  49657. * Serializes the animation to an object
  49658. * @returns Serialized object
  49659. */
  49660. Animation.prototype.serialize = function () {
  49661. var serializationObject = {};
  49662. serializationObject.name = this.name;
  49663. serializationObject.property = this.targetProperty;
  49664. serializationObject.framePerSecond = this.framePerSecond;
  49665. serializationObject.dataType = this.dataType;
  49666. serializationObject.loopBehavior = this.loopMode;
  49667. serializationObject.enableBlending = this.enableBlending;
  49668. serializationObject.blendingSpeed = this.blendingSpeed;
  49669. var dataType = this.dataType;
  49670. serializationObject.keys = [];
  49671. var keys = this.getKeys();
  49672. for (var index = 0; index < keys.length; index++) {
  49673. var animationKey = keys[index];
  49674. var key = {};
  49675. key.frame = animationKey.frame;
  49676. switch (dataType) {
  49677. case Animation.ANIMATIONTYPE_FLOAT:
  49678. key.values = [animationKey.value];
  49679. break;
  49680. case Animation.ANIMATIONTYPE_QUATERNION:
  49681. case Animation.ANIMATIONTYPE_MATRIX:
  49682. case Animation.ANIMATIONTYPE_VECTOR3:
  49683. case Animation.ANIMATIONTYPE_COLOR3:
  49684. key.values = animationKey.value.asArray();
  49685. break;
  49686. }
  49687. serializationObject.keys.push(key);
  49688. }
  49689. serializationObject.ranges = [];
  49690. for (var name in this._ranges) {
  49691. var source = this._ranges[name];
  49692. if (!source) {
  49693. continue;
  49694. }
  49695. var range = {};
  49696. range.name = name;
  49697. range.from = source.from;
  49698. range.to = source.to;
  49699. serializationObject.ranges.push(range);
  49700. }
  49701. return serializationObject;
  49702. };
  49703. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49704. /**
  49705. * Get the float animation type
  49706. */
  49707. get: function () {
  49708. return Animation._ANIMATIONTYPE_FLOAT;
  49709. },
  49710. enumerable: true,
  49711. configurable: true
  49712. });
  49713. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49714. /**
  49715. * Get the Vector3 animation type
  49716. */
  49717. get: function () {
  49718. return Animation._ANIMATIONTYPE_VECTOR3;
  49719. },
  49720. enumerable: true,
  49721. configurable: true
  49722. });
  49723. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49724. /**
  49725. * Get the Vectpr2 animation type
  49726. */
  49727. get: function () {
  49728. return Animation._ANIMATIONTYPE_VECTOR2;
  49729. },
  49730. enumerable: true,
  49731. configurable: true
  49732. });
  49733. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49734. /**
  49735. * Get the Size animation type
  49736. */
  49737. get: function () {
  49738. return Animation._ANIMATIONTYPE_SIZE;
  49739. },
  49740. enumerable: true,
  49741. configurable: true
  49742. });
  49743. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49744. /**
  49745. * Get the Quaternion animation type
  49746. */
  49747. get: function () {
  49748. return Animation._ANIMATIONTYPE_QUATERNION;
  49749. },
  49750. enumerable: true,
  49751. configurable: true
  49752. });
  49753. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49754. /**
  49755. * Get the Matrix animation type
  49756. */
  49757. get: function () {
  49758. return Animation._ANIMATIONTYPE_MATRIX;
  49759. },
  49760. enumerable: true,
  49761. configurable: true
  49762. });
  49763. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49764. /**
  49765. * Get the Color3 animation type
  49766. */
  49767. get: function () {
  49768. return Animation._ANIMATIONTYPE_COLOR3;
  49769. },
  49770. enumerable: true,
  49771. configurable: true
  49772. });
  49773. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49774. /**
  49775. * Get the Relative Loop Mode
  49776. */
  49777. get: function () {
  49778. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49779. },
  49780. enumerable: true,
  49781. configurable: true
  49782. });
  49783. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49784. /**
  49785. * Get the Cycle Loop Mode
  49786. */
  49787. get: function () {
  49788. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49789. },
  49790. enumerable: true,
  49791. configurable: true
  49792. });
  49793. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49794. /**
  49795. * Get the Constant Loop Mode
  49796. */
  49797. get: function () {
  49798. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49799. },
  49800. enumerable: true,
  49801. configurable: true
  49802. });
  49803. /** @hidden */
  49804. Animation._UniversalLerp = function (left, right, amount) {
  49805. var constructor = left.constructor;
  49806. if (constructor.Lerp) { // Lerp supported
  49807. return constructor.Lerp(left, right, amount);
  49808. }
  49809. else if (constructor.Slerp) { // Slerp supported
  49810. return constructor.Slerp(left, right, amount);
  49811. }
  49812. else if (left.toFixed) { // Number
  49813. return left * (1.0 - amount) + amount * right;
  49814. }
  49815. else { // Blending not supported
  49816. return right;
  49817. }
  49818. };
  49819. /**
  49820. * Parses an animation object and creates an animation
  49821. * @param parsedAnimation Parsed animation object
  49822. * @returns Animation object
  49823. */
  49824. Animation.Parse = function (parsedAnimation) {
  49825. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49826. var dataType = parsedAnimation.dataType;
  49827. var keys = [];
  49828. var data;
  49829. var index;
  49830. if (parsedAnimation.enableBlending) {
  49831. animation.enableBlending = parsedAnimation.enableBlending;
  49832. }
  49833. if (parsedAnimation.blendingSpeed) {
  49834. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49835. }
  49836. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49837. var key = parsedAnimation.keys[index];
  49838. var inTangent;
  49839. var outTangent;
  49840. switch (dataType) {
  49841. case Animation.ANIMATIONTYPE_FLOAT:
  49842. data = key.values[0];
  49843. if (key.values.length >= 1) {
  49844. inTangent = key.values[1];
  49845. }
  49846. if (key.values.length >= 2) {
  49847. outTangent = key.values[2];
  49848. }
  49849. break;
  49850. case Animation.ANIMATIONTYPE_QUATERNION:
  49851. data = BABYLON.Quaternion.FromArray(key.values);
  49852. if (key.values.length >= 8) {
  49853. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49854. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49855. inTangent = _inTangent;
  49856. }
  49857. }
  49858. if (key.values.length >= 12) {
  49859. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49860. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49861. outTangent = _outTangent;
  49862. }
  49863. }
  49864. break;
  49865. case Animation.ANIMATIONTYPE_MATRIX:
  49866. data = BABYLON.Matrix.FromArray(key.values);
  49867. break;
  49868. case Animation.ANIMATIONTYPE_COLOR3:
  49869. data = BABYLON.Color3.FromArray(key.values);
  49870. break;
  49871. case Animation.ANIMATIONTYPE_VECTOR3:
  49872. default:
  49873. data = BABYLON.Vector3.FromArray(key.values);
  49874. break;
  49875. }
  49876. var keyData = {};
  49877. keyData.frame = key.frame;
  49878. keyData.value = data;
  49879. if (inTangent != undefined) {
  49880. keyData.inTangent = inTangent;
  49881. }
  49882. if (outTangent != undefined) {
  49883. keyData.outTangent = outTangent;
  49884. }
  49885. keys.push(keyData);
  49886. }
  49887. animation.setKeys(keys);
  49888. if (parsedAnimation.ranges) {
  49889. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49890. data = parsedAnimation.ranges[index];
  49891. animation.createRange(data.name, data.from, data.to);
  49892. }
  49893. }
  49894. return animation;
  49895. };
  49896. /**
  49897. * Appends the serialized animations from the source animations
  49898. * @param source Source containing the animations
  49899. * @param destination Target to store the animations
  49900. */
  49901. Animation.AppendSerializedAnimations = function (source, destination) {
  49902. if (source.animations) {
  49903. destination.animations = [];
  49904. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49905. var animation = source.animations[animationIndex];
  49906. destination.animations.push(animation.serialize());
  49907. }
  49908. }
  49909. };
  49910. /**
  49911. * Use matrix interpolation instead of using direct key value when animating matrices
  49912. */
  49913. Animation.AllowMatricesInterpolation = false;
  49914. /**
  49915. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49916. */
  49917. Animation.AllowMatrixDecomposeForInterpolation = true;
  49918. // Statics
  49919. /**
  49920. * Float animation type
  49921. */
  49922. Animation._ANIMATIONTYPE_FLOAT = 0;
  49923. /**
  49924. * Vector3 animation type
  49925. */
  49926. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49927. /**
  49928. * Quaternion animation type
  49929. */
  49930. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49931. /**
  49932. * Matrix animation type
  49933. */
  49934. Animation._ANIMATIONTYPE_MATRIX = 3;
  49935. /**
  49936. * Color3 animation type
  49937. */
  49938. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49939. /**
  49940. * Vector2 animation type
  49941. */
  49942. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49943. /**
  49944. * Size animation type
  49945. */
  49946. Animation._ANIMATIONTYPE_SIZE = 6;
  49947. /**
  49948. * Relative Loop Mode
  49949. */
  49950. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49951. /**
  49952. * Cycle Loop Mode
  49953. */
  49954. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49955. /**
  49956. * Constant Loop Mode
  49957. */
  49958. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49959. return Animation;
  49960. }());
  49961. BABYLON.Animation = Animation;
  49962. })(BABYLON || (BABYLON = {}));
  49963. //# sourceMappingURL=babylon.animation.js.map
  49964. var BABYLON;
  49965. (function (BABYLON) {
  49966. /**
  49967. * This class defines the direct association between an animation and a target
  49968. */
  49969. var TargetedAnimation = /** @class */ (function () {
  49970. function TargetedAnimation() {
  49971. }
  49972. return TargetedAnimation;
  49973. }());
  49974. BABYLON.TargetedAnimation = TargetedAnimation;
  49975. /**
  49976. * Use this class to create coordinated animations on multiple targets
  49977. */
  49978. var AnimationGroup = /** @class */ (function () {
  49979. function AnimationGroup(name, scene) {
  49980. if (scene === void 0) { scene = null; }
  49981. this.name = name;
  49982. this._targetedAnimations = new Array();
  49983. this._animatables = new Array();
  49984. this._from = Number.MAX_VALUE;
  49985. this._to = -Number.MAX_VALUE;
  49986. this._speedRatio = 1;
  49987. this.onAnimationEndObservable = new BABYLON.Observable();
  49988. /**
  49989. * This observable will notify when all animations have ended.
  49990. */
  49991. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  49992. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49993. this._scene.animationGroups.push(this);
  49994. }
  49995. Object.defineProperty(AnimationGroup.prototype, "from", {
  49996. /**
  49997. * Gets the first frame
  49998. */
  49999. get: function () {
  50000. return this._from;
  50001. },
  50002. enumerable: true,
  50003. configurable: true
  50004. });
  50005. Object.defineProperty(AnimationGroup.prototype, "to", {
  50006. /**
  50007. * Gets the last frame
  50008. */
  50009. get: function () {
  50010. return this._to;
  50011. },
  50012. enumerable: true,
  50013. configurable: true
  50014. });
  50015. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50016. /**
  50017. * Define if the animations are started
  50018. */
  50019. get: function () {
  50020. return this._isStarted;
  50021. },
  50022. enumerable: true,
  50023. configurable: true
  50024. });
  50025. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50026. /**
  50027. * Gets or sets the speed ratio to use for all animations
  50028. */
  50029. get: function () {
  50030. return this._speedRatio;
  50031. },
  50032. /**
  50033. * Gets or sets the speed ratio to use for all animations
  50034. */
  50035. set: function (value) {
  50036. if (this._speedRatio === value) {
  50037. return;
  50038. }
  50039. this._speedRatio = value;
  50040. for (var index = 0; index < this._animatables.length; index++) {
  50041. var animatable = this._animatables[index];
  50042. animatable.speedRatio = this._speedRatio;
  50043. }
  50044. },
  50045. enumerable: true,
  50046. configurable: true
  50047. });
  50048. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50049. /**
  50050. * Gets the targeted animations for this animation group
  50051. */
  50052. get: function () {
  50053. return this._targetedAnimations;
  50054. },
  50055. enumerable: true,
  50056. configurable: true
  50057. });
  50058. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50059. /**
  50060. * returning the list of animatables controlled by this animation group.
  50061. */
  50062. get: function () {
  50063. return this._animatables;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. /**
  50069. * Add an animation (with its target) in the group
  50070. * @param animation defines the animation we want to add
  50071. * @param target defines the target of the animation
  50072. * @returns the {BABYLON.TargetedAnimation} object
  50073. */
  50074. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50075. var targetedAnimation = {
  50076. animation: animation,
  50077. target: target
  50078. };
  50079. var keys = animation.getKeys();
  50080. if (this._from > keys[0].frame) {
  50081. this._from = keys[0].frame;
  50082. }
  50083. if (this._to < keys[keys.length - 1].frame) {
  50084. this._to = keys[keys.length - 1].frame;
  50085. }
  50086. this._targetedAnimations.push(targetedAnimation);
  50087. return targetedAnimation;
  50088. };
  50089. /**
  50090. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50091. * It can add constant keys at begin or end
  50092. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50093. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50094. */
  50095. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50096. if (beginFrame === void 0) { beginFrame = null; }
  50097. if (endFrame === void 0) { endFrame = null; }
  50098. if (beginFrame == null)
  50099. beginFrame = this._from;
  50100. if (endFrame == null)
  50101. endFrame = this._to;
  50102. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50103. var targetedAnimation = this._targetedAnimations[index];
  50104. var keys = targetedAnimation.animation.getKeys();
  50105. var startKey = keys[0];
  50106. var endKey = keys[keys.length - 1];
  50107. if (startKey.frame > beginFrame) {
  50108. var newKey = {
  50109. frame: beginFrame,
  50110. value: startKey.value,
  50111. inTangent: startKey.inTangent,
  50112. outTangent: startKey.outTangent,
  50113. interpolation: startKey.interpolation
  50114. };
  50115. keys.splice(0, 0, newKey);
  50116. }
  50117. if (endKey.frame < endFrame) {
  50118. var newKey = {
  50119. frame: endFrame,
  50120. value: endKey.value,
  50121. inTangent: endKey.outTangent,
  50122. outTangent: endKey.outTangent,
  50123. interpolation: endKey.interpolation
  50124. };
  50125. keys.push(newKey);
  50126. }
  50127. }
  50128. this._from = beginFrame;
  50129. this._to = endFrame;
  50130. return this;
  50131. };
  50132. /**
  50133. * Start all animations on given targets
  50134. * @param loop defines if animations must loop
  50135. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50136. * @param from defines the from key (optional)
  50137. * @param to defines the to key (optional)
  50138. * @returns the current animation group
  50139. */
  50140. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50141. var _this = this;
  50142. if (loop === void 0) { loop = false; }
  50143. if (speedRatio === void 0) { speedRatio = 1; }
  50144. if (this._isStarted || this._targetedAnimations.length === 0) {
  50145. return this;
  50146. }
  50147. var _loop_1 = function (targetedAnimation) {
  50148. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50149. animatable.onAnimationEnd = function () {
  50150. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50151. _this._checkAnimationGroupEnded(animatable);
  50152. };
  50153. this_1._animatables.push(animatable);
  50154. };
  50155. var this_1 = this;
  50156. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50157. var targetedAnimation = _a[_i];
  50158. _loop_1(targetedAnimation);
  50159. }
  50160. this._speedRatio = speedRatio;
  50161. this._isStarted = true;
  50162. return this;
  50163. };
  50164. /**
  50165. * Pause all animations
  50166. */
  50167. AnimationGroup.prototype.pause = function () {
  50168. if (!this._isStarted) {
  50169. return this;
  50170. }
  50171. for (var index = 0; index < this._animatables.length; index++) {
  50172. var animatable = this._animatables[index];
  50173. animatable.pause();
  50174. }
  50175. return this;
  50176. };
  50177. /**
  50178. * Play all animations to initial state
  50179. * This function will start() the animations if they were not started or will restart() them if they were paused
  50180. * @param loop defines if animations must loop
  50181. */
  50182. AnimationGroup.prototype.play = function (loop) {
  50183. // only if all animatables are ready and exist
  50184. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50185. if (loop !== undefined) {
  50186. for (var index = 0; index < this._animatables.length; index++) {
  50187. var animatable = this._animatables[index];
  50188. animatable.loopAnimation = loop;
  50189. }
  50190. }
  50191. this.restart();
  50192. }
  50193. else {
  50194. this.stop();
  50195. this.start(loop, this._speedRatio);
  50196. }
  50197. return this;
  50198. };
  50199. /**
  50200. * Reset all animations to initial state
  50201. */
  50202. AnimationGroup.prototype.reset = function () {
  50203. if (!this._isStarted) {
  50204. return this;
  50205. }
  50206. for (var index = 0; index < this._animatables.length; index++) {
  50207. var animatable = this._animatables[index];
  50208. animatable.reset();
  50209. }
  50210. return this;
  50211. };
  50212. /**
  50213. * Restart animations from key 0
  50214. */
  50215. AnimationGroup.prototype.restart = function () {
  50216. if (!this._isStarted) {
  50217. return this;
  50218. }
  50219. for (var index = 0; index < this._animatables.length; index++) {
  50220. var animatable = this._animatables[index];
  50221. animatable.restart();
  50222. }
  50223. return this;
  50224. };
  50225. /**
  50226. * Stop all animations
  50227. */
  50228. AnimationGroup.prototype.stop = function () {
  50229. if (!this._isStarted) {
  50230. return this;
  50231. }
  50232. var list = this._animatables.slice();
  50233. for (var index = 0; index < list.length; index++) {
  50234. list[index].stop();
  50235. }
  50236. this._isStarted = false;
  50237. return this;
  50238. };
  50239. /**
  50240. * Set animation weight for all animatables
  50241. * @param weight defines the weight to use
  50242. * @return the animationGroup
  50243. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50244. */
  50245. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50246. for (var index = 0; index < this._animatables.length; index++) {
  50247. var animatable = this._animatables[index];
  50248. animatable.weight = weight;
  50249. }
  50250. return this;
  50251. };
  50252. /**
  50253. * Synchronize and normalize all animatables with a source animatable
  50254. * @param root defines the root animatable to synchronize with
  50255. * @return the animationGroup
  50256. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50257. */
  50258. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50259. for (var index = 0; index < this._animatables.length; index++) {
  50260. var animatable = this._animatables[index];
  50261. animatable.syncWith(root);
  50262. }
  50263. return this;
  50264. };
  50265. /**
  50266. * Goes to a specific frame in this animation group
  50267. * @param frame the frame number to go to
  50268. * @return the animationGroup
  50269. */
  50270. AnimationGroup.prototype.goToFrame = function (frame) {
  50271. if (!this._isStarted) {
  50272. return this;
  50273. }
  50274. for (var index = 0; index < this._animatables.length; index++) {
  50275. var animatable = this._animatables[index];
  50276. animatable.goToFrame(frame);
  50277. }
  50278. return this;
  50279. };
  50280. /**
  50281. * Dispose all associated resources
  50282. */
  50283. AnimationGroup.prototype.dispose = function () {
  50284. this._targetedAnimations = [];
  50285. this._animatables = [];
  50286. var index = this._scene.animationGroups.indexOf(this);
  50287. if (index > -1) {
  50288. this._scene.animationGroups.splice(index, 1);
  50289. }
  50290. };
  50291. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50292. // animatable should be taken out of the array
  50293. var idx = this._animatables.indexOf(animatable);
  50294. if (idx > -1) {
  50295. this._animatables.splice(idx, 1);
  50296. }
  50297. // all animatables were removed? animation group ended!
  50298. if (this._animatables.length === 0) {
  50299. this._isStarted = false;
  50300. this.onAnimationGroupEndObservable.notifyObservers(this);
  50301. }
  50302. };
  50303. return AnimationGroup;
  50304. }());
  50305. BABYLON.AnimationGroup = AnimationGroup;
  50306. })(BABYLON || (BABYLON = {}));
  50307. //# sourceMappingURL=babylon.animationGroup.js.map
  50308. var BABYLON;
  50309. (function (BABYLON) {
  50310. /**
  50311. * Defines a runtime animation
  50312. */
  50313. var RuntimeAnimation = /** @class */ (function () {
  50314. /**
  50315. * Create a new RuntimeAnimation object
  50316. * @param target defines the target of the animation
  50317. * @param animation defines the source animation object
  50318. * @param scene defines the hosting scene
  50319. * @param host defines the initiating Animatable
  50320. */
  50321. function RuntimeAnimation(target, animation, scene, host) {
  50322. var _this = this;
  50323. this._events = new Array();
  50324. /**
  50325. * The current frame of the runtime animation
  50326. */
  50327. this._currentFrame = 0;
  50328. /**
  50329. * The original value of the runtime animation
  50330. */
  50331. this._originalValue = new Array();
  50332. /**
  50333. * The offsets cache of the runtime animation
  50334. */
  50335. this._offsetsCache = {};
  50336. /**
  50337. * The high limits cache of the runtime animation
  50338. */
  50339. this._highLimitsCache = {};
  50340. /**
  50341. * Specifies if the runtime animation has been stopped
  50342. */
  50343. this._stopped = false;
  50344. /**
  50345. * The blending factor of the runtime animation
  50346. */
  50347. this._blendingFactor = 0;
  50348. /**
  50349. * The target path of the runtime animation
  50350. */
  50351. this._targetPath = "";
  50352. /**
  50353. * The weight of the runtime animation
  50354. */
  50355. this._weight = 1.0;
  50356. /**
  50357. * The ratio offset of the runtime animation
  50358. */
  50359. this._ratioOffset = 0;
  50360. /**
  50361. * The previous delay of the runtime animation
  50362. */
  50363. this._previousDelay = 0;
  50364. /**
  50365. * The previous ratio of the runtime animation
  50366. */
  50367. this._previousRatio = 0;
  50368. this._animation = animation;
  50369. this._target = target;
  50370. this._scene = scene;
  50371. this._host = host;
  50372. animation._runtimeAnimations.push(this);
  50373. // Cloning events locally
  50374. var events = animation.getEvents();
  50375. if (events && events.length > 0) {
  50376. events.forEach(function (e) {
  50377. _this._events.push(e._clone());
  50378. });
  50379. }
  50380. }
  50381. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50382. /**
  50383. * Gets the current frame of the runtime animation
  50384. */
  50385. get: function () {
  50386. return this._currentFrame;
  50387. },
  50388. enumerable: true,
  50389. configurable: true
  50390. });
  50391. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50392. /**
  50393. * Gets the weight of the runtime animation
  50394. */
  50395. get: function () {
  50396. return this._weight;
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50402. /**
  50403. * Gets the current value of the runtime animation
  50404. */
  50405. get: function () {
  50406. return this._currentValue;
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50412. /**
  50413. * Gets the target path of the runtime animation
  50414. */
  50415. get: function () {
  50416. return this._targetPath;
  50417. },
  50418. enumerable: true,
  50419. configurable: true
  50420. });
  50421. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50422. /**
  50423. * Gets the actual target of the runtime animation
  50424. */
  50425. get: function () {
  50426. return this._activeTarget;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50432. /**
  50433. * Gets the animation from the runtime animation
  50434. */
  50435. get: function () {
  50436. return this._animation;
  50437. },
  50438. enumerable: true,
  50439. configurable: true
  50440. });
  50441. /**
  50442. * Resets the runtime animation to the beginning
  50443. * @param restoreOriginal defines whether to restore the target property to the original value
  50444. */
  50445. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50446. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50447. if (restoreOriginal) {
  50448. if (this._target instanceof Array) {
  50449. var index = 0;
  50450. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50451. var target = _a[_i];
  50452. if (this._originalValue[index] !== undefined) {
  50453. this._setValue(target, this._originalValue[index], -1);
  50454. }
  50455. index++;
  50456. }
  50457. }
  50458. else {
  50459. if (this._originalValue[0] !== undefined) {
  50460. this._setValue(this._target, this._originalValue[0], -1);
  50461. }
  50462. }
  50463. }
  50464. this._offsetsCache = {};
  50465. this._highLimitsCache = {};
  50466. this._currentFrame = 0;
  50467. this._blendingFactor = 0;
  50468. this._originalValue = new Array();
  50469. // Events
  50470. for (var index = 0; index < this._events.length; index++) {
  50471. this._events[index].isDone = false;
  50472. }
  50473. };
  50474. /**
  50475. * Specifies if the runtime animation is stopped
  50476. * @returns Boolean specifying if the runtime animation is stopped
  50477. */
  50478. RuntimeAnimation.prototype.isStopped = function () {
  50479. return this._stopped;
  50480. };
  50481. /**
  50482. * Disposes of the runtime animation
  50483. */
  50484. RuntimeAnimation.prototype.dispose = function () {
  50485. var index = this._animation.runtimeAnimations.indexOf(this);
  50486. if (index > -1) {
  50487. this._animation.runtimeAnimations.splice(index, 1);
  50488. }
  50489. };
  50490. /**
  50491. * Interpolates the animation from the current frame
  50492. * @param currentFrame The frame to interpolate the animation to
  50493. * @param repeatCount The number of times that the animation should loop
  50494. * @param loopMode The type of looping mode to use
  50495. * @param offsetValue Animation offset value
  50496. * @param highLimitValue The high limit value
  50497. * @returns The interpolated value
  50498. */
  50499. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50500. this._currentFrame = currentFrame;
  50501. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50502. this._workValue = BABYLON.Matrix.Zero();
  50503. }
  50504. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50505. };
  50506. /**
  50507. * Apply the interpolated value to the target
  50508. * @param currentValue defines the value computed by the animation
  50509. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50510. */
  50511. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50512. if (weight === void 0) { weight = 1.0; }
  50513. if (this._target instanceof Array) {
  50514. var index = 0;
  50515. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50516. var target = _a[_i];
  50517. this._setValue(target, currentValue, weight, index);
  50518. index++;
  50519. }
  50520. }
  50521. else {
  50522. this._setValue(this._target, currentValue, weight);
  50523. }
  50524. };
  50525. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50526. if (targetIndex === void 0) { targetIndex = 0; }
  50527. // Set value
  50528. var path;
  50529. var destination;
  50530. var targetPropertyPath = this._animation.targetPropertyPath;
  50531. if (targetPropertyPath.length > 1) {
  50532. var property = target[targetPropertyPath[0]];
  50533. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50534. property = property[targetPropertyPath[index]];
  50535. }
  50536. path = targetPropertyPath[targetPropertyPath.length - 1];
  50537. destination = property;
  50538. }
  50539. else {
  50540. path = targetPropertyPath[0];
  50541. destination = target;
  50542. }
  50543. this._targetPath = path;
  50544. this._activeTarget = destination;
  50545. this._weight = weight;
  50546. if (this._originalValue[targetIndex] === undefined) {
  50547. var originalValue = void 0;
  50548. if (destination.getRestPose && path === "_matrix") { // For bones
  50549. originalValue = destination.getRestPose();
  50550. }
  50551. else {
  50552. originalValue = destination[path];
  50553. }
  50554. if (originalValue && originalValue.clone) {
  50555. this._originalValue[targetIndex] = originalValue.clone();
  50556. }
  50557. else {
  50558. this._originalValue[targetIndex] = originalValue;
  50559. }
  50560. }
  50561. // Blending
  50562. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50563. if (enableBlending && this._blendingFactor <= 1.0) {
  50564. if (!this._originalBlendValue) {
  50565. var originalValue = destination[path];
  50566. if (originalValue.clone) {
  50567. this._originalBlendValue = originalValue.clone();
  50568. }
  50569. else {
  50570. this._originalBlendValue = originalValue;
  50571. }
  50572. }
  50573. if (this._originalBlendValue.m) { // Matrix
  50574. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50575. if (this._currentValue) {
  50576. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50577. }
  50578. else {
  50579. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50580. }
  50581. }
  50582. else {
  50583. if (this._currentValue) {
  50584. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50585. }
  50586. else {
  50587. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50588. }
  50589. }
  50590. }
  50591. else {
  50592. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50593. }
  50594. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50595. this._blendingFactor += blendingSpeed;
  50596. }
  50597. else {
  50598. this._currentValue = currentValue;
  50599. }
  50600. if (weight !== -1.0) {
  50601. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50602. }
  50603. else {
  50604. destination[path] = this._currentValue;
  50605. }
  50606. if (target.markAsDirty) {
  50607. target.markAsDirty(this._animation.targetProperty);
  50608. }
  50609. };
  50610. /**
  50611. * Gets the loop pmode of the runtime animation
  50612. * @returns Loop Mode
  50613. */
  50614. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50615. if (this._target && this._target.animationPropertiesOverride) {
  50616. return this._target.animationPropertiesOverride.loopMode;
  50617. }
  50618. return this._animation.loopMode;
  50619. };
  50620. /**
  50621. * Move the current animation to a given frame
  50622. * @param frame defines the frame to move to
  50623. */
  50624. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50625. var keys = this._animation.getKeys();
  50626. if (frame < keys[0].frame) {
  50627. frame = keys[0].frame;
  50628. }
  50629. else if (frame > keys[keys.length - 1].frame) {
  50630. frame = keys[keys.length - 1].frame;
  50631. }
  50632. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50633. this.setValue(currentValue, -1);
  50634. };
  50635. /**
  50636. * @hidden Internal use only
  50637. */
  50638. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50639. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50640. this._ratioOffset = this._previousRatio - newRatio;
  50641. };
  50642. /**
  50643. * Execute the current animation
  50644. * @param delay defines the delay to add to the current frame
  50645. * @param from defines the lower bound of the animation range
  50646. * @param to defines the upper bound of the animation range
  50647. * @param loop defines if the current animation must loop
  50648. * @param speedRatio defines the current speed ratio
  50649. * @param weight defines the weight of the animation (default is -1 so no weight)
  50650. * @returns a boolean indicating if the animation is running
  50651. */
  50652. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50653. if (weight === void 0) { weight = -1.0; }
  50654. var targetPropertyPath = this._animation.targetPropertyPath;
  50655. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50656. this._stopped = true;
  50657. return false;
  50658. }
  50659. var returnValue = true;
  50660. var keys = this._animation.getKeys();
  50661. // Adding a start key at frame 0 if missing
  50662. if (keys[0].frame !== 0) {
  50663. var newKey = { frame: 0, value: keys[0].value };
  50664. keys.splice(0, 0, newKey);
  50665. }
  50666. // Adding a duplicate key when there is only one key at frame zero
  50667. else if (keys.length === 1) {
  50668. var newKey = { frame: 0.001, value: keys[0].value };
  50669. keys.push(newKey);
  50670. }
  50671. // Check limits
  50672. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50673. from = keys[0].frame;
  50674. }
  50675. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50676. to = keys[keys.length - 1].frame;
  50677. }
  50678. //to and from cannot be the same key
  50679. if (from === to) {
  50680. if (from > keys[0].frame) {
  50681. from--;
  50682. }
  50683. else if (to < keys[keys.length - 1].frame) {
  50684. to++;
  50685. }
  50686. }
  50687. // Compute ratio
  50688. var range = to - from;
  50689. var offsetValue;
  50690. // ratio represents the frame delta between from and to
  50691. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50692. var highLimitValue = 0;
  50693. this._previousDelay = delay;
  50694. this._previousRatio = ratio;
  50695. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50696. returnValue = false;
  50697. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50698. }
  50699. else {
  50700. // Get max value if required
  50701. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50702. var keyOffset = to.toString() + from.toString();
  50703. if (!this._offsetsCache[keyOffset]) {
  50704. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50705. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50706. switch (this._animation.dataType) {
  50707. // Float
  50708. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50709. this._offsetsCache[keyOffset] = toValue - fromValue;
  50710. break;
  50711. // Quaternion
  50712. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50713. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50714. break;
  50715. // Vector3
  50716. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50717. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50718. // Vector2
  50719. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50720. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50721. // Size
  50722. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50723. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50724. // Color3
  50725. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50726. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50727. default:
  50728. break;
  50729. }
  50730. this._highLimitsCache[keyOffset] = toValue;
  50731. }
  50732. highLimitValue = this._highLimitsCache[keyOffset];
  50733. offsetValue = this._offsetsCache[keyOffset];
  50734. }
  50735. }
  50736. if (offsetValue === undefined) {
  50737. switch (this._animation.dataType) {
  50738. // Float
  50739. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50740. offsetValue = 0;
  50741. break;
  50742. // Quaternion
  50743. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50744. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50745. break;
  50746. // Vector3
  50747. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50748. offsetValue = BABYLON.Vector3.Zero();
  50749. break;
  50750. // Vector2
  50751. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50752. offsetValue = BABYLON.Vector2.Zero();
  50753. break;
  50754. // Size
  50755. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50756. offsetValue = BABYLON.Size.Zero();
  50757. break;
  50758. // Color3
  50759. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50760. offsetValue = BABYLON.Color3.Black();
  50761. }
  50762. }
  50763. // Compute value
  50764. var repeatCount = (ratio / range) >> 0;
  50765. var currentFrame = returnValue ? from + ratio % range : to;
  50766. // Need to normalize?
  50767. if (this._host && this._host.syncRoot) {
  50768. var syncRoot = this._host.syncRoot;
  50769. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50770. currentFrame = from + (to - from) * hostNormalizedFrame;
  50771. }
  50772. // Reset events if looping
  50773. var events = this._events;
  50774. if (range > 0 && this.currentFrame > currentFrame ||
  50775. range < 0 && this.currentFrame < currentFrame) {
  50776. // Need to reset animation events
  50777. for (var index = 0; index < events.length; index++) {
  50778. if (!events[index].onlyOnce) {
  50779. // reset event, the animation is looping
  50780. events[index].isDone = false;
  50781. }
  50782. }
  50783. }
  50784. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50785. // Set value
  50786. this.setValue(currentValue, weight);
  50787. // Check events
  50788. for (var index = 0; index < events.length; index++) {
  50789. // Make sure current frame has passed event frame and that event frame is within the current range
  50790. // Also, handle both forward and reverse animations
  50791. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50792. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50793. var event = events[index];
  50794. if (!event.isDone) {
  50795. // If event should be done only once, remove it.
  50796. if (event.onlyOnce) {
  50797. events.splice(index, 1);
  50798. index--;
  50799. }
  50800. event.isDone = true;
  50801. event.action();
  50802. } // Don't do anything if the event has already be done.
  50803. }
  50804. }
  50805. if (!returnValue) {
  50806. this._stopped = true;
  50807. }
  50808. return returnValue;
  50809. };
  50810. return RuntimeAnimation;
  50811. }());
  50812. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50813. })(BABYLON || (BABYLON = {}));
  50814. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50815. var BABYLON;
  50816. (function (BABYLON) {
  50817. /**
  50818. * Class used to store an actual running animation
  50819. */
  50820. var Animatable = /** @class */ (function () {
  50821. /**
  50822. * Creates a new Animatable
  50823. * @param scene defines the hosting scene
  50824. * @param target defines the target object
  50825. * @param fromFrame defines the starting frame number (default is 0)
  50826. * @param toFrame defines the ending frame number (default is 100)
  50827. * @param loopAnimation defines if the animation must loop (default is false)
  50828. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  50829. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  50830. * @param animations defines a group of animation to add to the new Animatable
  50831. */
  50832. function Animatable(scene,
  50833. /** defines the target object */
  50834. target,
  50835. /** defines the starting frame number (default is 0) */
  50836. fromFrame,
  50837. /** defines the ending frame number (default is 100) */
  50838. toFrame,
  50839. /** defines if the animation must loop (default is false) */
  50840. loopAnimation, speedRatio,
  50841. /** defines a callback to call when animation ends if it is not looping */
  50842. onAnimationEnd, animations) {
  50843. if (fromFrame === void 0) { fromFrame = 0; }
  50844. if (toFrame === void 0) { toFrame = 100; }
  50845. if (loopAnimation === void 0) { loopAnimation = false; }
  50846. if (speedRatio === void 0) { speedRatio = 1.0; }
  50847. this.target = target;
  50848. this.fromFrame = fromFrame;
  50849. this.toFrame = toFrame;
  50850. this.loopAnimation = loopAnimation;
  50851. this.onAnimationEnd = onAnimationEnd;
  50852. this._localDelayOffset = null;
  50853. this._pausedDelay = null;
  50854. this._runtimeAnimations = new Array();
  50855. this._paused = false;
  50856. this._speedRatio = 1;
  50857. this._weight = -1.0;
  50858. /**
  50859. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  50860. * This will only apply for non looping animation (default is true)
  50861. */
  50862. this.disposeOnEnd = true;
  50863. /**
  50864. * Gets a boolean indicating if the animation has started
  50865. */
  50866. this.animationStarted = false;
  50867. /**
  50868. * Observer raised when the animation ends
  50869. */
  50870. this.onAnimationEndObservable = new BABYLON.Observable();
  50871. this._scene = scene;
  50872. if (animations) {
  50873. this.appendAnimations(target, animations);
  50874. }
  50875. this._speedRatio = speedRatio;
  50876. scene._activeAnimatables.push(this);
  50877. }
  50878. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50879. /**
  50880. * Gets the root Animatable used to synchronize and normalize animations
  50881. */
  50882. get: function () {
  50883. return this._syncRoot;
  50884. },
  50885. enumerable: true,
  50886. configurable: true
  50887. });
  50888. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50889. /**
  50890. * Gets the current frame of the first RuntimeAnimation
  50891. * Used to synchronize Animatables
  50892. */
  50893. get: function () {
  50894. if (this._runtimeAnimations.length === 0) {
  50895. return 0;
  50896. }
  50897. return this._runtimeAnimations[0].currentFrame;
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. Object.defineProperty(Animatable.prototype, "weight", {
  50903. /**
  50904. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50905. */
  50906. get: function () {
  50907. return this._weight;
  50908. },
  50909. set: function (value) {
  50910. if (value === -1) { // -1 is ok and means no weight
  50911. this._weight = -1;
  50912. return;
  50913. }
  50914. // Else weight must be in [0, 1] range
  50915. this._weight = Math.min(Math.max(value, 0), 1.0);
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50921. /**
  50922. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50923. */
  50924. get: function () {
  50925. return this._speedRatio;
  50926. },
  50927. set: function (value) {
  50928. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50929. var animation = this._runtimeAnimations[index];
  50930. animation._prepareForSpeedRatioChange(value);
  50931. }
  50932. this._speedRatio = value;
  50933. },
  50934. enumerable: true,
  50935. configurable: true
  50936. });
  50937. // Methods
  50938. /**
  50939. * Synchronize and normalize current Animatable with a source Animatable
  50940. * This is useful when using animation weights and when animations are not of the same length
  50941. * @param root defines the root Animatable to synchronize with
  50942. * @returns the current Animatable
  50943. */
  50944. Animatable.prototype.syncWith = function (root) {
  50945. this._syncRoot = root;
  50946. if (root) {
  50947. // Make sure this animatable will animate after the root
  50948. var index = this._scene._activeAnimatables.indexOf(this);
  50949. if (index > -1) {
  50950. this._scene._activeAnimatables.splice(index, 1);
  50951. this._scene._activeAnimatables.push(this);
  50952. }
  50953. }
  50954. return this;
  50955. };
  50956. /**
  50957. * Gets the list of runtime animations
  50958. * @returns an array of RuntimeAnimation
  50959. */
  50960. Animatable.prototype.getAnimations = function () {
  50961. return this._runtimeAnimations;
  50962. };
  50963. /**
  50964. * Adds more animations to the current animatable
  50965. * @param target defines the target of the animations
  50966. * @param animations defines the new animations to add
  50967. */
  50968. Animatable.prototype.appendAnimations = function (target, animations) {
  50969. for (var index = 0; index < animations.length; index++) {
  50970. var animation = animations[index];
  50971. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50972. }
  50973. };
  50974. /**
  50975. * Gets the source animation for a specific property
  50976. * @param property defines the propertyu to look for
  50977. * @returns null or the source animation for the given property
  50978. */
  50979. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50980. var runtimeAnimations = this._runtimeAnimations;
  50981. for (var index = 0; index < runtimeAnimations.length; index++) {
  50982. if (runtimeAnimations[index].animation.targetProperty === property) {
  50983. return runtimeAnimations[index].animation;
  50984. }
  50985. }
  50986. return null;
  50987. };
  50988. /**
  50989. * Gets the runtime animation for a specific property
  50990. * @param property defines the propertyu to look for
  50991. * @returns null or the runtime animation for the given property
  50992. */
  50993. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50994. var runtimeAnimations = this._runtimeAnimations;
  50995. for (var index = 0; index < runtimeAnimations.length; index++) {
  50996. if (runtimeAnimations[index].animation.targetProperty === property) {
  50997. return runtimeAnimations[index];
  50998. }
  50999. }
  51000. return null;
  51001. };
  51002. /**
  51003. * Resets the animatable to its original state
  51004. */
  51005. Animatable.prototype.reset = function () {
  51006. var runtimeAnimations = this._runtimeAnimations;
  51007. for (var index = 0; index < runtimeAnimations.length; index++) {
  51008. runtimeAnimations[index].reset(true);
  51009. }
  51010. this._localDelayOffset = null;
  51011. this._pausedDelay = null;
  51012. };
  51013. /**
  51014. * Allows the animatable to blend with current running animations
  51015. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51016. * @param blendingSpeed defines the blending speed to use
  51017. */
  51018. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51019. var runtimeAnimations = this._runtimeAnimations;
  51020. for (var index = 0; index < runtimeAnimations.length; index++) {
  51021. runtimeAnimations[index].animation.enableBlending = true;
  51022. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51023. }
  51024. };
  51025. /**
  51026. * Disable animation blending
  51027. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51028. */
  51029. Animatable.prototype.disableBlending = function () {
  51030. var runtimeAnimations = this._runtimeAnimations;
  51031. for (var index = 0; index < runtimeAnimations.length; index++) {
  51032. runtimeAnimations[index].animation.enableBlending = false;
  51033. }
  51034. };
  51035. /**
  51036. * Jump directly to a given frame
  51037. * @param frame defines the frame to jump to
  51038. */
  51039. Animatable.prototype.goToFrame = function (frame) {
  51040. var runtimeAnimations = this._runtimeAnimations;
  51041. if (runtimeAnimations[0]) {
  51042. var fps = runtimeAnimations[0].animation.framePerSecond;
  51043. var currentFrame = runtimeAnimations[0].currentFrame;
  51044. var adjustTime = frame - currentFrame;
  51045. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51046. if (this._localDelayOffset === null) {
  51047. this._localDelayOffset = 0;
  51048. }
  51049. this._localDelayOffset -= delay;
  51050. }
  51051. for (var index = 0; index < runtimeAnimations.length; index++) {
  51052. runtimeAnimations[index].goToFrame(frame);
  51053. }
  51054. };
  51055. /**
  51056. * Pause the animation
  51057. */
  51058. Animatable.prototype.pause = function () {
  51059. if (this._paused) {
  51060. return;
  51061. }
  51062. this._paused = true;
  51063. };
  51064. /**
  51065. * Restart the animation
  51066. */
  51067. Animatable.prototype.restart = function () {
  51068. this._paused = false;
  51069. };
  51070. Animatable.prototype._raiseOnAnimationEnd = function () {
  51071. if (this.onAnimationEnd) {
  51072. this.onAnimationEnd();
  51073. }
  51074. this.onAnimationEndObservable.notifyObservers(this);
  51075. };
  51076. /**
  51077. * Stop and delete the current animation
  51078. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51079. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51080. */
  51081. Animatable.prototype.stop = function (animationName, targetMask) {
  51082. if (animationName || targetMask) {
  51083. var idx = this._scene._activeAnimatables.indexOf(this);
  51084. if (idx > -1) {
  51085. var runtimeAnimations = this._runtimeAnimations;
  51086. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51087. var runtimeAnimation = runtimeAnimations[index];
  51088. if (animationName && runtimeAnimation.animation.name != animationName) {
  51089. continue;
  51090. }
  51091. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51092. continue;
  51093. }
  51094. runtimeAnimation.dispose();
  51095. runtimeAnimations.splice(index, 1);
  51096. }
  51097. if (runtimeAnimations.length == 0) {
  51098. this._scene._activeAnimatables.splice(idx, 1);
  51099. this._raiseOnAnimationEnd();
  51100. }
  51101. }
  51102. }
  51103. else {
  51104. var index = this._scene._activeAnimatables.indexOf(this);
  51105. if (index > -1) {
  51106. this._scene._activeAnimatables.splice(index, 1);
  51107. var runtimeAnimations = this._runtimeAnimations;
  51108. for (var index = 0; index < runtimeAnimations.length; index++) {
  51109. runtimeAnimations[index].dispose();
  51110. }
  51111. this._raiseOnAnimationEnd();
  51112. }
  51113. }
  51114. };
  51115. /**
  51116. * Wait asynchronously for the animation to end
  51117. * @returns a promise which will be fullfilled when the animation ends
  51118. */
  51119. Animatable.prototype.waitAsync = function () {
  51120. var _this = this;
  51121. return new Promise(function (resolve, reject) {
  51122. _this.onAnimationEndObservable.add(function () {
  51123. resolve(_this);
  51124. }, undefined, undefined, _this, true);
  51125. });
  51126. };
  51127. /** @hidden */
  51128. Animatable.prototype._animate = function (delay) {
  51129. if (this._paused) {
  51130. this.animationStarted = false;
  51131. if (this._pausedDelay === null) {
  51132. this._pausedDelay = delay;
  51133. }
  51134. return true;
  51135. }
  51136. if (this._localDelayOffset === null) {
  51137. this._localDelayOffset = delay;
  51138. this._pausedDelay = null;
  51139. }
  51140. else if (this._pausedDelay !== null) {
  51141. this._localDelayOffset += delay - this._pausedDelay;
  51142. this._pausedDelay = null;
  51143. }
  51144. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51145. return true;
  51146. }
  51147. // Animating
  51148. var running = false;
  51149. var runtimeAnimations = this._runtimeAnimations;
  51150. var index;
  51151. for (index = 0; index < runtimeAnimations.length; index++) {
  51152. var animation = runtimeAnimations[index];
  51153. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51154. running = running || isRunning;
  51155. }
  51156. this.animationStarted = running;
  51157. if (!running) {
  51158. if (this.disposeOnEnd) {
  51159. // Remove from active animatables
  51160. index = this._scene._activeAnimatables.indexOf(this);
  51161. this._scene._activeAnimatables.splice(index, 1);
  51162. // Dispose all runtime animations
  51163. for (index = 0; index < runtimeAnimations.length; index++) {
  51164. runtimeAnimations[index].dispose();
  51165. }
  51166. }
  51167. this._raiseOnAnimationEnd();
  51168. if (this.disposeOnEnd) {
  51169. this.onAnimationEnd = null;
  51170. this.onAnimationEndObservable.clear();
  51171. }
  51172. }
  51173. return running;
  51174. };
  51175. return Animatable;
  51176. }());
  51177. BABYLON.Animatable = Animatable;
  51178. })(BABYLON || (BABYLON = {}));
  51179. //# sourceMappingURL=babylon.animatable.js.map
  51180. var BABYLON;
  51181. (function (BABYLON) {
  51182. var EasingFunction = /** @class */ (function () {
  51183. function EasingFunction() {
  51184. // Properties
  51185. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51186. }
  51187. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51188. get: function () {
  51189. return EasingFunction._EASINGMODE_EASEIN;
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51195. get: function () {
  51196. return EasingFunction._EASINGMODE_EASEOUT;
  51197. },
  51198. enumerable: true,
  51199. configurable: true
  51200. });
  51201. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51202. get: function () {
  51203. return EasingFunction._EASINGMODE_EASEINOUT;
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51209. var n = Math.min(Math.max(easingMode, 0), 2);
  51210. this._easingMode = n;
  51211. };
  51212. EasingFunction.prototype.getEasingMode = function () {
  51213. return this._easingMode;
  51214. };
  51215. EasingFunction.prototype.easeInCore = function (gradient) {
  51216. throw new Error('You must implement this method');
  51217. };
  51218. EasingFunction.prototype.ease = function (gradient) {
  51219. switch (this._easingMode) {
  51220. case EasingFunction.EASINGMODE_EASEIN:
  51221. return this.easeInCore(gradient);
  51222. case EasingFunction.EASINGMODE_EASEOUT:
  51223. return (1 - this.easeInCore(1 - gradient));
  51224. }
  51225. if (gradient >= 0.5) {
  51226. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51227. }
  51228. return (this.easeInCore(gradient * 2) * 0.5);
  51229. };
  51230. //Statics
  51231. EasingFunction._EASINGMODE_EASEIN = 0;
  51232. EasingFunction._EASINGMODE_EASEOUT = 1;
  51233. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51234. return EasingFunction;
  51235. }());
  51236. BABYLON.EasingFunction = EasingFunction;
  51237. var CircleEase = /** @class */ (function (_super) {
  51238. __extends(CircleEase, _super);
  51239. function CircleEase() {
  51240. return _super !== null && _super.apply(this, arguments) || this;
  51241. }
  51242. CircleEase.prototype.easeInCore = function (gradient) {
  51243. gradient = Math.max(0, Math.min(1, gradient));
  51244. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51245. };
  51246. return CircleEase;
  51247. }(EasingFunction));
  51248. BABYLON.CircleEase = CircleEase;
  51249. var BackEase = /** @class */ (function (_super) {
  51250. __extends(BackEase, _super);
  51251. function BackEase(amplitude) {
  51252. if (amplitude === void 0) { amplitude = 1; }
  51253. var _this = _super.call(this) || this;
  51254. _this.amplitude = amplitude;
  51255. return _this;
  51256. }
  51257. BackEase.prototype.easeInCore = function (gradient) {
  51258. var num = Math.max(0, this.amplitude);
  51259. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51260. };
  51261. return BackEase;
  51262. }(EasingFunction));
  51263. BABYLON.BackEase = BackEase;
  51264. var BounceEase = /** @class */ (function (_super) {
  51265. __extends(BounceEase, _super);
  51266. function BounceEase(bounces, bounciness) {
  51267. if (bounces === void 0) { bounces = 3; }
  51268. if (bounciness === void 0) { bounciness = 2; }
  51269. var _this = _super.call(this) || this;
  51270. _this.bounces = bounces;
  51271. _this.bounciness = bounciness;
  51272. return _this;
  51273. }
  51274. BounceEase.prototype.easeInCore = function (gradient) {
  51275. var y = Math.max(0.0, this.bounces);
  51276. var bounciness = this.bounciness;
  51277. if (bounciness <= 1.0) {
  51278. bounciness = 1.001;
  51279. }
  51280. var num9 = Math.pow(bounciness, y);
  51281. var num5 = 1.0 - bounciness;
  51282. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51283. var num15 = gradient * num4;
  51284. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51285. var num3 = Math.floor(num65);
  51286. var num13 = num3 + 1.0;
  51287. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51288. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51289. var num7 = (num8 + num12) * 0.5;
  51290. var num6 = gradient - num7;
  51291. var num2 = num7 - num8;
  51292. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51293. };
  51294. return BounceEase;
  51295. }(EasingFunction));
  51296. BABYLON.BounceEase = BounceEase;
  51297. var CubicEase = /** @class */ (function (_super) {
  51298. __extends(CubicEase, _super);
  51299. function CubicEase() {
  51300. return _super !== null && _super.apply(this, arguments) || this;
  51301. }
  51302. CubicEase.prototype.easeInCore = function (gradient) {
  51303. return (gradient * gradient * gradient);
  51304. };
  51305. return CubicEase;
  51306. }(EasingFunction));
  51307. BABYLON.CubicEase = CubicEase;
  51308. var ElasticEase = /** @class */ (function (_super) {
  51309. __extends(ElasticEase, _super);
  51310. function ElasticEase(oscillations, springiness) {
  51311. if (oscillations === void 0) { oscillations = 3; }
  51312. if (springiness === void 0) { springiness = 3; }
  51313. var _this = _super.call(this) || this;
  51314. _this.oscillations = oscillations;
  51315. _this.springiness = springiness;
  51316. return _this;
  51317. }
  51318. ElasticEase.prototype.easeInCore = function (gradient) {
  51319. var num2;
  51320. var num3 = Math.max(0.0, this.oscillations);
  51321. var num = Math.max(0.0, this.springiness);
  51322. if (num == 0) {
  51323. num2 = gradient;
  51324. }
  51325. else {
  51326. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51327. }
  51328. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51329. };
  51330. return ElasticEase;
  51331. }(EasingFunction));
  51332. BABYLON.ElasticEase = ElasticEase;
  51333. var ExponentialEase = /** @class */ (function (_super) {
  51334. __extends(ExponentialEase, _super);
  51335. function ExponentialEase(exponent) {
  51336. if (exponent === void 0) { exponent = 2; }
  51337. var _this = _super.call(this) || this;
  51338. _this.exponent = exponent;
  51339. return _this;
  51340. }
  51341. ExponentialEase.prototype.easeInCore = function (gradient) {
  51342. if (this.exponent <= 0) {
  51343. return gradient;
  51344. }
  51345. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51346. };
  51347. return ExponentialEase;
  51348. }(EasingFunction));
  51349. BABYLON.ExponentialEase = ExponentialEase;
  51350. var PowerEase = /** @class */ (function (_super) {
  51351. __extends(PowerEase, _super);
  51352. function PowerEase(power) {
  51353. if (power === void 0) { power = 2; }
  51354. var _this = _super.call(this) || this;
  51355. _this.power = power;
  51356. return _this;
  51357. }
  51358. PowerEase.prototype.easeInCore = function (gradient) {
  51359. var y = Math.max(0.0, this.power);
  51360. return Math.pow(gradient, y);
  51361. };
  51362. return PowerEase;
  51363. }(EasingFunction));
  51364. BABYLON.PowerEase = PowerEase;
  51365. var QuadraticEase = /** @class */ (function (_super) {
  51366. __extends(QuadraticEase, _super);
  51367. function QuadraticEase() {
  51368. return _super !== null && _super.apply(this, arguments) || this;
  51369. }
  51370. QuadraticEase.prototype.easeInCore = function (gradient) {
  51371. return (gradient * gradient);
  51372. };
  51373. return QuadraticEase;
  51374. }(EasingFunction));
  51375. BABYLON.QuadraticEase = QuadraticEase;
  51376. var QuarticEase = /** @class */ (function (_super) {
  51377. __extends(QuarticEase, _super);
  51378. function QuarticEase() {
  51379. return _super !== null && _super.apply(this, arguments) || this;
  51380. }
  51381. QuarticEase.prototype.easeInCore = function (gradient) {
  51382. return (gradient * gradient * gradient * gradient);
  51383. };
  51384. return QuarticEase;
  51385. }(EasingFunction));
  51386. BABYLON.QuarticEase = QuarticEase;
  51387. var QuinticEase = /** @class */ (function (_super) {
  51388. __extends(QuinticEase, _super);
  51389. function QuinticEase() {
  51390. return _super !== null && _super.apply(this, arguments) || this;
  51391. }
  51392. QuinticEase.prototype.easeInCore = function (gradient) {
  51393. return (gradient * gradient * gradient * gradient * gradient);
  51394. };
  51395. return QuinticEase;
  51396. }(EasingFunction));
  51397. BABYLON.QuinticEase = QuinticEase;
  51398. var SineEase = /** @class */ (function (_super) {
  51399. __extends(SineEase, _super);
  51400. function SineEase() {
  51401. return _super !== null && _super.apply(this, arguments) || this;
  51402. }
  51403. SineEase.prototype.easeInCore = function (gradient) {
  51404. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51405. };
  51406. return SineEase;
  51407. }(EasingFunction));
  51408. BABYLON.SineEase = SineEase;
  51409. var BezierCurveEase = /** @class */ (function (_super) {
  51410. __extends(BezierCurveEase, _super);
  51411. function BezierCurveEase(x1, y1, x2, y2) {
  51412. if (x1 === void 0) { x1 = 0; }
  51413. if (y1 === void 0) { y1 = 0; }
  51414. if (x2 === void 0) { x2 = 1; }
  51415. if (y2 === void 0) { y2 = 1; }
  51416. var _this = _super.call(this) || this;
  51417. _this.x1 = x1;
  51418. _this.y1 = y1;
  51419. _this.x2 = x2;
  51420. _this.y2 = y2;
  51421. return _this;
  51422. }
  51423. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51424. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51425. };
  51426. return BezierCurveEase;
  51427. }(EasingFunction));
  51428. BABYLON.BezierCurveEase = BezierCurveEase;
  51429. })(BABYLON || (BABYLON = {}));
  51430. //# sourceMappingURL=babylon.easing.js.map
  51431. var BABYLON;
  51432. (function (BABYLON) {
  51433. /**
  51434. * A Condition applied to an Action
  51435. */
  51436. var Condition = /** @class */ (function () {
  51437. /**
  51438. * Creates a new Condition
  51439. * @param actionManager the manager of the action the condition is applied to
  51440. */
  51441. function Condition(actionManager) {
  51442. this._actionManager = actionManager;
  51443. }
  51444. /**
  51445. * Check if the current condition is valid
  51446. * @returns a boolean
  51447. */
  51448. Condition.prototype.isValid = function () {
  51449. return true;
  51450. };
  51451. /**
  51452. * Internal only
  51453. * @hidden
  51454. */
  51455. Condition.prototype._getProperty = function (propertyPath) {
  51456. return this._actionManager._getProperty(propertyPath);
  51457. };
  51458. /**
  51459. * Internal only
  51460. * @hidden
  51461. */
  51462. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51463. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51464. };
  51465. /**
  51466. * Serialize placeholder for child classes
  51467. * @returns the serialized object
  51468. */
  51469. Condition.prototype.serialize = function () {
  51470. };
  51471. /**
  51472. * Internal only
  51473. * @hidden
  51474. */
  51475. Condition.prototype._serialize = function (serializedCondition) {
  51476. return {
  51477. type: 2,
  51478. children: [],
  51479. name: serializedCondition.name,
  51480. properties: serializedCondition.properties
  51481. };
  51482. };
  51483. return Condition;
  51484. }());
  51485. BABYLON.Condition = Condition;
  51486. /**
  51487. * Defines specific conditional operators as extensions of Condition
  51488. */
  51489. var ValueCondition = /** @class */ (function (_super) {
  51490. __extends(ValueCondition, _super);
  51491. /**
  51492. * Creates a new ValueCondition
  51493. * @param actionManager manager for the action the condition applies to
  51494. * @param target for the action
  51495. * @param propertyPath path to specify the property of the target the conditional operator uses
  51496. * @param value the value compared by the conditional operator against the current value of the property
  51497. * @param operator the conditional operator, default ValueCondition.IsEqual
  51498. */
  51499. function ValueCondition(actionManager, target,
  51500. /** path to specify the property of the target the conditional operator uses */
  51501. propertyPath,
  51502. /** the value compared by the conditional operator against the current value of the property */
  51503. value,
  51504. /** the conditional operator, default ValueCondition.IsEqual */
  51505. operator) {
  51506. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51507. var _this = _super.call(this, actionManager) || this;
  51508. _this.propertyPath = propertyPath;
  51509. _this.value = value;
  51510. _this.operator = operator;
  51511. _this._target = target;
  51512. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51513. _this._property = _this._getProperty(_this.propertyPath);
  51514. return _this;
  51515. }
  51516. Object.defineProperty(ValueCondition, "IsEqual", {
  51517. /**
  51518. * returns the number for IsEqual
  51519. */
  51520. get: function () {
  51521. return ValueCondition._IsEqual;
  51522. },
  51523. enumerable: true,
  51524. configurable: true
  51525. });
  51526. Object.defineProperty(ValueCondition, "IsDifferent", {
  51527. /**
  51528. * Returns the number for IsDifferent
  51529. */
  51530. get: function () {
  51531. return ValueCondition._IsDifferent;
  51532. },
  51533. enumerable: true,
  51534. configurable: true
  51535. });
  51536. Object.defineProperty(ValueCondition, "IsGreater", {
  51537. /**
  51538. * Returns the number for IsGreater
  51539. */
  51540. get: function () {
  51541. return ValueCondition._IsGreater;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. Object.defineProperty(ValueCondition, "IsLesser", {
  51547. /**
  51548. * Returns the number for IsLesser
  51549. */
  51550. get: function () {
  51551. return ValueCondition._IsLesser;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. /**
  51557. * Compares the given value with the property value for the specified conditional operator
  51558. * @returns the result of the comparison
  51559. */
  51560. ValueCondition.prototype.isValid = function () {
  51561. switch (this.operator) {
  51562. case ValueCondition.IsGreater:
  51563. return this._effectiveTarget[this._property] > this.value;
  51564. case ValueCondition.IsLesser:
  51565. return this._effectiveTarget[this._property] < this.value;
  51566. case ValueCondition.IsEqual:
  51567. case ValueCondition.IsDifferent:
  51568. var check;
  51569. if (this.value.equals) {
  51570. check = this.value.equals(this._effectiveTarget[this._property]);
  51571. }
  51572. else {
  51573. check = this.value === this._effectiveTarget[this._property];
  51574. }
  51575. return this.operator === ValueCondition.IsEqual ? check : !check;
  51576. }
  51577. return false;
  51578. };
  51579. /**
  51580. * Serialize the ValueCondition into a JSON compatible object
  51581. * @returns serialization object
  51582. */
  51583. ValueCondition.prototype.serialize = function () {
  51584. return this._serialize({
  51585. name: "ValueCondition",
  51586. properties: [
  51587. BABYLON.Action._GetTargetProperty(this._target),
  51588. { name: "propertyPath", value: this.propertyPath },
  51589. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51590. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51591. ]
  51592. });
  51593. };
  51594. /**
  51595. * Gets the name of the conditional operator for the ValueCondition
  51596. * @param operator the conditional operator
  51597. * @returns the name
  51598. */
  51599. ValueCondition.GetOperatorName = function (operator) {
  51600. switch (operator) {
  51601. case ValueCondition._IsEqual: return "IsEqual";
  51602. case ValueCondition._IsDifferent: return "IsDifferent";
  51603. case ValueCondition._IsGreater: return "IsGreater";
  51604. case ValueCondition._IsLesser: return "IsLesser";
  51605. default: return "";
  51606. }
  51607. };
  51608. /**
  51609. * Internal only
  51610. * @hidden
  51611. */
  51612. ValueCondition._IsEqual = 0;
  51613. /**
  51614. * Internal only
  51615. * @hidden
  51616. */
  51617. ValueCondition._IsDifferent = 1;
  51618. /**
  51619. * Internal only
  51620. * @hidden
  51621. */
  51622. ValueCondition._IsGreater = 2;
  51623. /**
  51624. * Internal only
  51625. * @hidden
  51626. */
  51627. ValueCondition._IsLesser = 3;
  51628. return ValueCondition;
  51629. }(Condition));
  51630. BABYLON.ValueCondition = ValueCondition;
  51631. /**
  51632. * Defines a predicate condition as an extension of Condition
  51633. */
  51634. var PredicateCondition = /** @class */ (function (_super) {
  51635. __extends(PredicateCondition, _super);
  51636. /**
  51637. * Creates a new PredicateCondition
  51638. * @param actionManager manager for the action the condition applies to
  51639. * @param predicate defines the predicate function used to validate the condition
  51640. */
  51641. function PredicateCondition(actionManager,
  51642. /** defines the predicate function used to validate the condition */
  51643. predicate) {
  51644. var _this = _super.call(this, actionManager) || this;
  51645. _this.predicate = predicate;
  51646. return _this;
  51647. }
  51648. /**
  51649. * @returns the validity of the predicate condition
  51650. */
  51651. PredicateCondition.prototype.isValid = function () {
  51652. return this.predicate();
  51653. };
  51654. return PredicateCondition;
  51655. }(Condition));
  51656. BABYLON.PredicateCondition = PredicateCondition;
  51657. /**
  51658. * Defines a state condition as an extension of Condition
  51659. */
  51660. var StateCondition = /** @class */ (function (_super) {
  51661. __extends(StateCondition, _super);
  51662. /**
  51663. * Creates a new StateCondition
  51664. * @param actionManager manager for the action the condition applies to
  51665. * @param target of the condition
  51666. * @param value to compare with target state
  51667. */
  51668. function StateCondition(actionManager, target, value) {
  51669. var _this = _super.call(this, actionManager) || this;
  51670. _this.value = value;
  51671. _this._target = target;
  51672. return _this;
  51673. }
  51674. /**
  51675. * @returns the validity of the state
  51676. */
  51677. StateCondition.prototype.isValid = function () {
  51678. return this._target.state === this.value;
  51679. };
  51680. /**
  51681. * Serialize the StateCondition into a JSON compatible object
  51682. * @returns serialization object
  51683. */
  51684. StateCondition.prototype.serialize = function () {
  51685. return this._serialize({
  51686. name: "StateCondition",
  51687. properties: [
  51688. BABYLON.Action._GetTargetProperty(this._target),
  51689. { name: "value", value: this.value }
  51690. ]
  51691. });
  51692. };
  51693. return StateCondition;
  51694. }(Condition));
  51695. BABYLON.StateCondition = StateCondition;
  51696. })(BABYLON || (BABYLON = {}));
  51697. //# sourceMappingURL=babylon.condition.js.map
  51698. var BABYLON;
  51699. (function (BABYLON) {
  51700. /**
  51701. * The action to be carried out following a trigger
  51702. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51703. */
  51704. var Action = /** @class */ (function () {
  51705. /**
  51706. * Creates a new Action
  51707. * @param triggerOptions the trigger, with or without parameters, for the action
  51708. * @param condition an optional determinant of action
  51709. */
  51710. function Action(
  51711. /** the trigger, with or without parameters, for the action */
  51712. triggerOptions, condition) {
  51713. this.triggerOptions = triggerOptions;
  51714. /**
  51715. * An event triggered prior to action being executed.
  51716. */
  51717. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51718. if (triggerOptions.parameter) {
  51719. this.trigger = triggerOptions.trigger;
  51720. this._triggerParameter = triggerOptions.parameter;
  51721. }
  51722. else {
  51723. this.trigger = triggerOptions;
  51724. }
  51725. this._nextActiveAction = this;
  51726. this._condition = condition;
  51727. }
  51728. /**
  51729. * Internal only
  51730. * @hidden
  51731. */
  51732. Action.prototype._prepare = function () {
  51733. };
  51734. /**
  51735. * Gets the trigger parameters
  51736. * @returns the trigger parameters
  51737. */
  51738. Action.prototype.getTriggerParameter = function () {
  51739. return this._triggerParameter;
  51740. };
  51741. /**
  51742. * Internal only - executes current action event
  51743. * @hidden
  51744. */
  51745. Action.prototype._executeCurrent = function (evt) {
  51746. if (this._nextActiveAction._condition) {
  51747. var condition = this._nextActiveAction._condition;
  51748. var currentRenderId = this._actionManager.getScene().getRenderId();
  51749. // We cache the current evaluation for the current frame
  51750. if (condition._evaluationId === currentRenderId) {
  51751. if (!condition._currentResult) {
  51752. return;
  51753. }
  51754. }
  51755. else {
  51756. condition._evaluationId = currentRenderId;
  51757. if (!condition.isValid()) {
  51758. condition._currentResult = false;
  51759. return;
  51760. }
  51761. condition._currentResult = true;
  51762. }
  51763. }
  51764. this.onBeforeExecuteObservable.notifyObservers(this);
  51765. this._nextActiveAction.execute(evt);
  51766. this.skipToNextActiveAction();
  51767. };
  51768. /**
  51769. * Execute placeholder for child classes
  51770. * @param evt optional action event
  51771. */
  51772. Action.prototype.execute = function (evt) {
  51773. };
  51774. /**
  51775. * Skips to next active action
  51776. */
  51777. Action.prototype.skipToNextActiveAction = function () {
  51778. if (this._nextActiveAction._child) {
  51779. if (!this._nextActiveAction._child._actionManager) {
  51780. this._nextActiveAction._child._actionManager = this._actionManager;
  51781. }
  51782. this._nextActiveAction = this._nextActiveAction._child;
  51783. }
  51784. else {
  51785. this._nextActiveAction = this;
  51786. }
  51787. };
  51788. /**
  51789. * Adds action to chain of actions, may be a DoNothingAction
  51790. * @param action defines the next action to execute
  51791. * @returns The action passed in
  51792. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51793. */
  51794. Action.prototype.then = function (action) {
  51795. this._child = action;
  51796. action._actionManager = this._actionManager;
  51797. action._prepare();
  51798. return action;
  51799. };
  51800. /**
  51801. * Internal only
  51802. * @hidden
  51803. */
  51804. Action.prototype._getProperty = function (propertyPath) {
  51805. return this._actionManager._getProperty(propertyPath);
  51806. };
  51807. /**
  51808. * Internal only
  51809. * @hidden
  51810. */
  51811. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51812. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51813. };
  51814. /**
  51815. * Serialize placeholder for child classes
  51816. * @param parent of child
  51817. * @returns the serialized object
  51818. */
  51819. Action.prototype.serialize = function (parent) {
  51820. };
  51821. /**
  51822. * Internal only called by serialize
  51823. * @hidden
  51824. */
  51825. Action.prototype._serialize = function (serializedAction, parent) {
  51826. var serializationObject = {
  51827. type: 1,
  51828. children: [],
  51829. name: serializedAction.name,
  51830. properties: serializedAction.properties || []
  51831. };
  51832. // Serialize child
  51833. if (this._child) {
  51834. this._child.serialize(serializationObject);
  51835. }
  51836. // Check if "this" has a condition
  51837. if (this._condition) {
  51838. var serializedCondition = this._condition.serialize();
  51839. serializedCondition.children.push(serializationObject);
  51840. if (parent) {
  51841. parent.children.push(serializedCondition);
  51842. }
  51843. return serializedCondition;
  51844. }
  51845. if (parent) {
  51846. parent.children.push(serializationObject);
  51847. }
  51848. return serializationObject;
  51849. };
  51850. /**
  51851. * Internal only
  51852. * @hidden
  51853. */
  51854. Action._SerializeValueAsString = function (value) {
  51855. if (typeof value === "number") {
  51856. return value.toString();
  51857. }
  51858. if (typeof value === "boolean") {
  51859. return value ? "true" : "false";
  51860. }
  51861. if (value instanceof BABYLON.Vector2) {
  51862. return value.x + ", " + value.y;
  51863. }
  51864. if (value instanceof BABYLON.Vector3) {
  51865. return value.x + ", " + value.y + ", " + value.z;
  51866. }
  51867. if (value instanceof BABYLON.Color3) {
  51868. return value.r + ", " + value.g + ", " + value.b;
  51869. }
  51870. if (value instanceof BABYLON.Color4) {
  51871. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51872. }
  51873. return value; // string
  51874. };
  51875. /**
  51876. * Internal only
  51877. * @hidden
  51878. */
  51879. Action._GetTargetProperty = function (target) {
  51880. return {
  51881. name: "target",
  51882. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51883. : target instanceof BABYLON.Light ? "LightProperties"
  51884. : target instanceof BABYLON.Camera ? "CameraProperties"
  51885. : "SceneProperties",
  51886. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51887. };
  51888. };
  51889. return Action;
  51890. }());
  51891. BABYLON.Action = Action;
  51892. })(BABYLON || (BABYLON = {}));
  51893. //# sourceMappingURL=babylon.action.js.map
  51894. var BABYLON;
  51895. (function (BABYLON) {
  51896. /**
  51897. * ActionEvent is the event being sent when an action is triggered.
  51898. */
  51899. var ActionEvent = /** @class */ (function () {
  51900. /**
  51901. * Creates a new ActionEvent
  51902. * @param source The mesh or sprite that triggered the action
  51903. * @param pointerX The X mouse cursor position at the time of the event
  51904. * @param pointerY The Y mouse cursor position at the time of the event
  51905. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51906. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51907. * @param additionalData additional data for the event
  51908. */
  51909. function ActionEvent(
  51910. /** The mesh or sprite that triggered the action */
  51911. source,
  51912. /** The X mouse cursor position at the time of the event */
  51913. pointerX,
  51914. /** The Y mouse cursor position at the time of the event */
  51915. pointerY,
  51916. /** The mesh that is currently pointed at (can be null) */
  51917. meshUnderPointer,
  51918. /** the original (browser) event that triggered the ActionEvent */
  51919. sourceEvent,
  51920. /** additional data for the event */
  51921. additionalData) {
  51922. this.source = source;
  51923. this.pointerX = pointerX;
  51924. this.pointerY = pointerY;
  51925. this.meshUnderPointer = meshUnderPointer;
  51926. this.sourceEvent = sourceEvent;
  51927. this.additionalData = additionalData;
  51928. }
  51929. /**
  51930. * Helper function to auto-create an ActionEvent from a source mesh.
  51931. * @param source The source mesh that triggered the event
  51932. * @param evt The original (browser) event
  51933. * @param additionalData additional data for the event
  51934. * @returns the new ActionEvent
  51935. */
  51936. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51937. var scene = source.getScene();
  51938. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51939. };
  51940. /**
  51941. * Helper function to auto-create an ActionEvent from a source sprite
  51942. * @param source The source sprite that triggered the event
  51943. * @param scene Scene associated with the sprite
  51944. * @param evt The original (browser) event
  51945. * @param additionalData additional data for the event
  51946. * @returns the new ActionEvent
  51947. */
  51948. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51949. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51950. };
  51951. /**
  51952. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51953. * @param scene the scene where the event occurred
  51954. * @param evt The original (browser) event
  51955. * @returns the new ActionEvent
  51956. */
  51957. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51958. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51959. };
  51960. /**
  51961. * Helper function to auto-create an ActionEvent from a primitive
  51962. * @param prim defines the target primitive
  51963. * @param pointerPos defines the pointer position
  51964. * @param evt The original (browser) event
  51965. * @param additionalData additional data for the event
  51966. * @returns the new ActionEvent
  51967. */
  51968. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51969. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51970. };
  51971. return ActionEvent;
  51972. }());
  51973. BABYLON.ActionEvent = ActionEvent;
  51974. /**
  51975. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51976. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51977. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  51978. */
  51979. var ActionManager = /** @class */ (function () {
  51980. /**
  51981. * Creates a new action manager
  51982. * @param scene defines the hosting scene
  51983. */
  51984. function ActionManager(scene) {
  51985. // Members
  51986. /** Gets the list of actions */
  51987. this.actions = new Array();
  51988. /** Gets the cursor to use when hovering items */
  51989. this.hoverCursor = '';
  51990. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51991. scene.actionManagers.push(this);
  51992. }
  51993. Object.defineProperty(ActionManager, "NothingTrigger", {
  51994. /**
  51995. * Nothing
  51996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51997. */
  51998. get: function () {
  51999. return ActionManager._NothingTrigger;
  52000. },
  52001. enumerable: true,
  52002. configurable: true
  52003. });
  52004. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52005. /**
  52006. * On pick
  52007. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52008. */
  52009. get: function () {
  52010. return ActionManager._OnPickTrigger;
  52011. },
  52012. enumerable: true,
  52013. configurable: true
  52014. });
  52015. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52016. /**
  52017. * On left pick
  52018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52019. */
  52020. get: function () {
  52021. return ActionManager._OnLeftPickTrigger;
  52022. },
  52023. enumerable: true,
  52024. configurable: true
  52025. });
  52026. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52027. /**
  52028. * On right pick
  52029. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52030. */
  52031. get: function () {
  52032. return ActionManager._OnRightPickTrigger;
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52038. /**
  52039. * On center pick
  52040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52041. */
  52042. get: function () {
  52043. return ActionManager._OnCenterPickTrigger;
  52044. },
  52045. enumerable: true,
  52046. configurable: true
  52047. });
  52048. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52049. /**
  52050. * On pick down
  52051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52052. */
  52053. get: function () {
  52054. return ActionManager._OnPickDownTrigger;
  52055. },
  52056. enumerable: true,
  52057. configurable: true
  52058. });
  52059. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52060. /**
  52061. * On double pick
  52062. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52063. */
  52064. get: function () {
  52065. return ActionManager._OnDoublePickTrigger;
  52066. },
  52067. enumerable: true,
  52068. configurable: true
  52069. });
  52070. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52071. /**
  52072. * On pick up
  52073. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52074. */
  52075. get: function () {
  52076. return ActionManager._OnPickUpTrigger;
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52082. /**
  52083. * On pick out.
  52084. * This trigger will only be raised if you also declared a OnPickDown
  52085. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52086. */
  52087. get: function () {
  52088. return ActionManager._OnPickOutTrigger;
  52089. },
  52090. enumerable: true,
  52091. configurable: true
  52092. });
  52093. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52094. /**
  52095. * On long press
  52096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52097. */
  52098. get: function () {
  52099. return ActionManager._OnLongPressTrigger;
  52100. },
  52101. enumerable: true,
  52102. configurable: true
  52103. });
  52104. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52105. /**
  52106. * On pointer over
  52107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52108. */
  52109. get: function () {
  52110. return ActionManager._OnPointerOverTrigger;
  52111. },
  52112. enumerable: true,
  52113. configurable: true
  52114. });
  52115. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52116. /**
  52117. * On pointer out
  52118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52119. */
  52120. get: function () {
  52121. return ActionManager._OnPointerOutTrigger;
  52122. },
  52123. enumerable: true,
  52124. configurable: true
  52125. });
  52126. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52127. /**
  52128. * On every frame
  52129. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52130. */
  52131. get: function () {
  52132. return ActionManager._OnEveryFrameTrigger;
  52133. },
  52134. enumerable: true,
  52135. configurable: true
  52136. });
  52137. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52138. /**
  52139. * On intersection enter
  52140. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52141. */
  52142. get: function () {
  52143. return ActionManager._OnIntersectionEnterTrigger;
  52144. },
  52145. enumerable: true,
  52146. configurable: true
  52147. });
  52148. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52149. /**
  52150. * On intersection exit
  52151. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52152. */
  52153. get: function () {
  52154. return ActionManager._OnIntersectionExitTrigger;
  52155. },
  52156. enumerable: true,
  52157. configurable: true
  52158. });
  52159. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52160. /**
  52161. * On key down
  52162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52163. */
  52164. get: function () {
  52165. return ActionManager._OnKeyDownTrigger;
  52166. },
  52167. enumerable: true,
  52168. configurable: true
  52169. });
  52170. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52171. /**
  52172. * On key up
  52173. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52174. */
  52175. get: function () {
  52176. return ActionManager._OnKeyUpTrigger;
  52177. },
  52178. enumerable: true,
  52179. configurable: true
  52180. });
  52181. // Methods
  52182. /**
  52183. * Releases all associated resources
  52184. */
  52185. ActionManager.prototype.dispose = function () {
  52186. var index = this._scene.actionManagers.indexOf(this);
  52187. for (var i = 0; i < this.actions.length; i++) {
  52188. var action = this.actions[i];
  52189. ActionManager.Triggers[action.trigger]--;
  52190. if (ActionManager.Triggers[action.trigger] === 0) {
  52191. delete ActionManager.Triggers[action.trigger];
  52192. }
  52193. }
  52194. if (index > -1) {
  52195. this._scene.actionManagers.splice(index, 1);
  52196. }
  52197. };
  52198. /**
  52199. * Gets hosting scene
  52200. * @returns the hosting scene
  52201. */
  52202. ActionManager.prototype.getScene = function () {
  52203. return this._scene;
  52204. };
  52205. /**
  52206. * Does this action manager handles actions of any of the given triggers
  52207. * @param triggers defines the triggers to be tested
  52208. * @return a boolean indicating whether one (or more) of the triggers is handled
  52209. */
  52210. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52211. for (var index = 0; index < this.actions.length; index++) {
  52212. var action = this.actions[index];
  52213. if (triggers.indexOf(action.trigger) > -1) {
  52214. return true;
  52215. }
  52216. }
  52217. return false;
  52218. };
  52219. /**
  52220. * Does this action manager handles actions of a given trigger
  52221. * @param trigger defines the trigger to be tested
  52222. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52223. * @return whether the trigger is handled
  52224. */
  52225. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52226. for (var index = 0; index < this.actions.length; index++) {
  52227. var action = this.actions[index];
  52228. if (action.trigger === trigger) {
  52229. if (parameterPredicate) {
  52230. if (parameterPredicate(action.getTriggerParameter())) {
  52231. return true;
  52232. }
  52233. }
  52234. else {
  52235. return true;
  52236. }
  52237. }
  52238. }
  52239. return false;
  52240. };
  52241. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52242. /**
  52243. * Does this action manager has pointer triggers
  52244. */
  52245. get: function () {
  52246. for (var index = 0; index < this.actions.length; index++) {
  52247. var action = this.actions[index];
  52248. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52249. return true;
  52250. }
  52251. }
  52252. return false;
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52258. /**
  52259. * Does this action manager has pick triggers
  52260. */
  52261. get: function () {
  52262. for (var index = 0; index < this.actions.length; index++) {
  52263. var action = this.actions[index];
  52264. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52265. return true;
  52266. }
  52267. }
  52268. return false;
  52269. },
  52270. enumerable: true,
  52271. configurable: true
  52272. });
  52273. Object.defineProperty(ActionManager, "HasTriggers", {
  52274. /**
  52275. * Does exist one action manager with at least one trigger
  52276. **/
  52277. get: function () {
  52278. for (var t in ActionManager.Triggers) {
  52279. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52280. return true;
  52281. }
  52282. }
  52283. return false;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52289. /**
  52290. * Does exist one action manager with at least one pick trigger
  52291. **/
  52292. get: function () {
  52293. for (var t in ActionManager.Triggers) {
  52294. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52295. var t_int = parseInt(t);
  52296. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52297. return true;
  52298. }
  52299. }
  52300. }
  52301. return false;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. /**
  52307. * Does exist one action manager that handles actions of a given trigger
  52308. * @param trigger defines the trigger to be tested
  52309. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52310. **/
  52311. ActionManager.HasSpecificTrigger = function (trigger) {
  52312. for (var t in ActionManager.Triggers) {
  52313. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52314. var t_int = parseInt(t);
  52315. if (t_int === trigger) {
  52316. return true;
  52317. }
  52318. }
  52319. }
  52320. return false;
  52321. };
  52322. /**
  52323. * Registers an action to this action manager
  52324. * @param action defines the action to be registered
  52325. * @return the action amended (prepared) after registration
  52326. */
  52327. ActionManager.prototype.registerAction = function (action) {
  52328. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52329. if (this.getScene().actionManager !== this) {
  52330. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52331. return null;
  52332. }
  52333. }
  52334. this.actions.push(action);
  52335. if (ActionManager.Triggers[action.trigger]) {
  52336. ActionManager.Triggers[action.trigger]++;
  52337. }
  52338. else {
  52339. ActionManager.Triggers[action.trigger] = 1;
  52340. }
  52341. action._actionManager = this;
  52342. action._prepare();
  52343. return action;
  52344. };
  52345. /**
  52346. * Unregisters an action to this action manager
  52347. * @param action defines the action to be unregistered
  52348. * @return a boolean indicating whether the action has been unregistered
  52349. */
  52350. ActionManager.prototype.unregisterAction = function (action) {
  52351. var index = this.actions.indexOf(action);
  52352. if (index !== -1) {
  52353. this.actions.splice(index, 1);
  52354. ActionManager.Triggers[action.trigger] -= 1;
  52355. if (ActionManager.Triggers[action.trigger] === 0) {
  52356. delete ActionManager.Triggers[action.trigger];
  52357. }
  52358. delete action._actionManager;
  52359. return true;
  52360. }
  52361. return false;
  52362. };
  52363. /**
  52364. * Process a specific trigger
  52365. * @param trigger defines the trigger to process
  52366. * @param evt defines the event details to be processed
  52367. */
  52368. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52369. for (var index = 0; index < this.actions.length; index++) {
  52370. var action = this.actions[index];
  52371. if (action.trigger === trigger) {
  52372. if (evt) {
  52373. if (trigger === ActionManager.OnKeyUpTrigger
  52374. || trigger === ActionManager.OnKeyDownTrigger) {
  52375. var parameter = action.getTriggerParameter();
  52376. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52377. if (!parameter.toLowerCase) {
  52378. continue;
  52379. }
  52380. var lowerCase = parameter.toLowerCase();
  52381. if (lowerCase !== evt.sourceEvent.key) {
  52382. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52383. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52384. if (actualkey !== lowerCase) {
  52385. continue;
  52386. }
  52387. }
  52388. }
  52389. }
  52390. }
  52391. action._executeCurrent(evt);
  52392. }
  52393. }
  52394. };
  52395. /** @hidden */
  52396. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52397. var properties = propertyPath.split(".");
  52398. for (var index = 0; index < properties.length - 1; index++) {
  52399. target = target[properties[index]];
  52400. }
  52401. return target;
  52402. };
  52403. /** @hidden */
  52404. ActionManager.prototype._getProperty = function (propertyPath) {
  52405. var properties = propertyPath.split(".");
  52406. return properties[properties.length - 1];
  52407. };
  52408. /**
  52409. * Serialize this manager to a JSON object
  52410. * @param name defines the property name to store this manager
  52411. * @returns a JSON representation of this manager
  52412. */
  52413. ActionManager.prototype.serialize = function (name) {
  52414. var root = {
  52415. children: new Array(),
  52416. name: name,
  52417. type: 3,
  52418. properties: new Array() // Empty for root but required
  52419. };
  52420. for (var i = 0; i < this.actions.length; i++) {
  52421. var triggerObject = {
  52422. type: 0,
  52423. children: new Array(),
  52424. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52425. properties: new Array()
  52426. };
  52427. var triggerOptions = this.actions[i].triggerOptions;
  52428. if (triggerOptions && typeof triggerOptions !== "number") {
  52429. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52430. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52431. }
  52432. else {
  52433. var parameter = {};
  52434. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52435. if (triggerOptions.parameter.mesh) {
  52436. parameter._meshId = triggerOptions.parameter.mesh.id;
  52437. }
  52438. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52439. }
  52440. }
  52441. // Serialize child action, recursively
  52442. this.actions[i].serialize(triggerObject);
  52443. // Add serialized trigger
  52444. root.children.push(triggerObject);
  52445. }
  52446. return root;
  52447. };
  52448. /**
  52449. * Creates a new ActionManager from a JSON data
  52450. * @param parsedActions defines the JSON data to read from
  52451. * @param object defines the hosting mesh
  52452. * @param scene defines the hosting scene
  52453. */
  52454. ActionManager.Parse = function (parsedActions, object, scene) {
  52455. var actionManager = new ActionManager(scene);
  52456. if (object === null)
  52457. scene.actionManager = actionManager;
  52458. else
  52459. object.actionManager = actionManager;
  52460. // instanciate a new object
  52461. var instanciate = function (name, params) {
  52462. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52463. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52464. newInstance.constructor.apply(newInstance, params);
  52465. return newInstance;
  52466. };
  52467. var parseParameter = function (name, value, target, propertyPath) {
  52468. if (propertyPath === null) {
  52469. // String, boolean or float
  52470. var floatValue = parseFloat(value);
  52471. if (value === "true" || value === "false")
  52472. return value === "true";
  52473. else
  52474. return isNaN(floatValue) ? value : floatValue;
  52475. }
  52476. var effectiveTarget = propertyPath.split(".");
  52477. var values = value.split(",");
  52478. // Get effective Target
  52479. for (var i = 0; i < effectiveTarget.length; i++) {
  52480. target = target[effectiveTarget[i]];
  52481. }
  52482. // Return appropriate value with its type
  52483. if (typeof (target) === "boolean")
  52484. return values[0] === "true";
  52485. if (typeof (target) === "string")
  52486. return values[0];
  52487. // Parameters with multiple values such as Vector3 etc.
  52488. var split = new Array();
  52489. for (var i = 0; i < values.length; i++)
  52490. split.push(parseFloat(values[i]));
  52491. if (target instanceof BABYLON.Vector3)
  52492. return BABYLON.Vector3.FromArray(split);
  52493. if (target instanceof BABYLON.Vector4)
  52494. return BABYLON.Vector4.FromArray(split);
  52495. if (target instanceof BABYLON.Color3)
  52496. return BABYLON.Color3.FromArray(split);
  52497. if (target instanceof BABYLON.Color4)
  52498. return BABYLON.Color4.FromArray(split);
  52499. return parseFloat(values[0]);
  52500. };
  52501. // traverse graph per trigger
  52502. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52503. if (combineArray === void 0) { combineArray = null; }
  52504. if (parsedAction.detached)
  52505. return;
  52506. var parameters = new Array();
  52507. var target = null;
  52508. var propertyPath = null;
  52509. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52510. // Parameters
  52511. if (parsedAction.type === 2)
  52512. parameters.push(actionManager);
  52513. else
  52514. parameters.push(trigger);
  52515. if (combine) {
  52516. var actions = new Array();
  52517. for (var j = 0; j < parsedAction.combine.length; j++) {
  52518. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52519. }
  52520. parameters.push(actions);
  52521. }
  52522. else {
  52523. for (var i = 0; i < parsedAction.properties.length; i++) {
  52524. var value = parsedAction.properties[i].value;
  52525. var name = parsedAction.properties[i].name;
  52526. var targetType = parsedAction.properties[i].targetType;
  52527. if (name === "target")
  52528. if (targetType !== null && targetType === "SceneProperties")
  52529. value = target = scene;
  52530. else
  52531. value = target = scene.getNodeByName(value);
  52532. else if (name === "parent")
  52533. value = scene.getNodeByName(value);
  52534. else if (name === "sound")
  52535. value = scene.getSoundByName(value);
  52536. else if (name !== "propertyPath") {
  52537. if (parsedAction.type === 2 && name === "operator")
  52538. value = BABYLON.ValueCondition[value];
  52539. else
  52540. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52541. }
  52542. else {
  52543. propertyPath = value;
  52544. }
  52545. parameters.push(value);
  52546. }
  52547. }
  52548. if (combineArray === null) {
  52549. parameters.push(condition);
  52550. }
  52551. else {
  52552. parameters.push(null);
  52553. }
  52554. // If interpolate value action
  52555. if (parsedAction.name === "InterpolateValueAction") {
  52556. var param = parameters[parameters.length - 2];
  52557. parameters[parameters.length - 1] = param;
  52558. parameters[parameters.length - 2] = condition;
  52559. }
  52560. // Action or condition(s) and not CombineAction
  52561. var newAction = instanciate(parsedAction.name, parameters);
  52562. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52563. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52564. if (action)
  52565. action.then(nothing);
  52566. else
  52567. actionManager.registerAction(nothing);
  52568. action = nothing;
  52569. }
  52570. if (combineArray === null) {
  52571. if (newAction instanceof BABYLON.Condition) {
  52572. condition = newAction;
  52573. newAction = action;
  52574. }
  52575. else {
  52576. condition = null;
  52577. if (action)
  52578. action.then(newAction);
  52579. else
  52580. actionManager.registerAction(newAction);
  52581. }
  52582. }
  52583. else {
  52584. combineArray.push(newAction);
  52585. }
  52586. for (var i = 0; i < parsedAction.children.length; i++)
  52587. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52588. };
  52589. // triggers
  52590. for (var i = 0; i < parsedActions.children.length; i++) {
  52591. var triggerParams;
  52592. var trigger = parsedActions.children[i];
  52593. if (trigger.properties.length > 0) {
  52594. var param = trigger.properties[0].value;
  52595. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52596. if (value._meshId) {
  52597. value.mesh = scene.getMeshByID(value._meshId);
  52598. }
  52599. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52600. }
  52601. else
  52602. triggerParams = ActionManager[trigger.name];
  52603. for (var j = 0; j < trigger.children.length; j++) {
  52604. if (!trigger.detached)
  52605. traverse(trigger.children[j], triggerParams, null, null);
  52606. }
  52607. }
  52608. };
  52609. /**
  52610. * Get a trigger name by index
  52611. * @param trigger defines the trigger index
  52612. * @returns a trigger name
  52613. */
  52614. ActionManager.GetTriggerName = function (trigger) {
  52615. switch (trigger) {
  52616. case 0: return "NothingTrigger";
  52617. case 1: return "OnPickTrigger";
  52618. case 2: return "OnLeftPickTrigger";
  52619. case 3: return "OnRightPickTrigger";
  52620. case 4: return "OnCenterPickTrigger";
  52621. case 5: return "OnPickDownTrigger";
  52622. case 6: return "OnPickUpTrigger";
  52623. case 7: return "OnLongPressTrigger";
  52624. case 8: return "OnPointerOverTrigger";
  52625. case 9: return "OnPointerOutTrigger";
  52626. case 10: return "OnEveryFrameTrigger";
  52627. case 11: return "OnIntersectionEnterTrigger";
  52628. case 12: return "OnIntersectionExitTrigger";
  52629. case 13: return "OnKeyDownTrigger";
  52630. case 14: return "OnKeyUpTrigger";
  52631. case 15: return "OnPickOutTrigger";
  52632. default: return "";
  52633. }
  52634. };
  52635. // Statics
  52636. ActionManager._NothingTrigger = 0;
  52637. ActionManager._OnPickTrigger = 1;
  52638. ActionManager._OnLeftPickTrigger = 2;
  52639. ActionManager._OnRightPickTrigger = 3;
  52640. ActionManager._OnCenterPickTrigger = 4;
  52641. ActionManager._OnPickDownTrigger = 5;
  52642. ActionManager._OnDoublePickTrigger = 6;
  52643. ActionManager._OnPickUpTrigger = 7;
  52644. ActionManager._OnLongPressTrigger = 8;
  52645. ActionManager._OnPointerOverTrigger = 9;
  52646. ActionManager._OnPointerOutTrigger = 10;
  52647. ActionManager._OnEveryFrameTrigger = 11;
  52648. ActionManager._OnIntersectionEnterTrigger = 12;
  52649. ActionManager._OnIntersectionExitTrigger = 13;
  52650. ActionManager._OnKeyDownTrigger = 14;
  52651. ActionManager._OnKeyUpTrigger = 15;
  52652. ActionManager._OnPickOutTrigger = 16;
  52653. /** Gets the list of active triggers */
  52654. ActionManager.Triggers = {};
  52655. return ActionManager;
  52656. }());
  52657. BABYLON.ActionManager = ActionManager;
  52658. })(BABYLON || (BABYLON = {}));
  52659. //# sourceMappingURL=babylon.actionManager.js.map
  52660. var BABYLON;
  52661. (function (BABYLON) {
  52662. var InterpolateValueAction = /** @class */ (function (_super) {
  52663. __extends(InterpolateValueAction, _super);
  52664. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52665. if (duration === void 0) { duration = 1000; }
  52666. var _this = _super.call(this, triggerOptions, condition) || this;
  52667. _this.propertyPath = propertyPath;
  52668. _this.value = value;
  52669. _this.duration = duration;
  52670. _this.stopOtherAnimations = stopOtherAnimations;
  52671. _this.onInterpolationDone = onInterpolationDone;
  52672. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52673. _this._target = _this._effectiveTarget = target;
  52674. return _this;
  52675. }
  52676. InterpolateValueAction.prototype._prepare = function () {
  52677. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52678. this._property = this._getProperty(this.propertyPath);
  52679. };
  52680. InterpolateValueAction.prototype.execute = function () {
  52681. var _this = this;
  52682. var scene = this._actionManager.getScene();
  52683. var keys = [
  52684. {
  52685. frame: 0,
  52686. value: this._effectiveTarget[this._property]
  52687. }, {
  52688. frame: 100,
  52689. value: this.value
  52690. }
  52691. ];
  52692. var dataType;
  52693. if (typeof this.value === "number") {
  52694. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52695. }
  52696. else if (this.value instanceof BABYLON.Color3) {
  52697. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52698. }
  52699. else if (this.value instanceof BABYLON.Vector3) {
  52700. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52701. }
  52702. else if (this.value instanceof BABYLON.Matrix) {
  52703. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52704. }
  52705. else if (this.value instanceof BABYLON.Quaternion) {
  52706. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52707. }
  52708. else {
  52709. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52710. return;
  52711. }
  52712. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52713. animation.setKeys(keys);
  52714. if (this.stopOtherAnimations) {
  52715. scene.stopAnimation(this._effectiveTarget);
  52716. }
  52717. var wrapper = function () {
  52718. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52719. if (_this.onInterpolationDone) {
  52720. _this.onInterpolationDone();
  52721. }
  52722. };
  52723. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52724. };
  52725. InterpolateValueAction.prototype.serialize = function (parent) {
  52726. return _super.prototype._serialize.call(this, {
  52727. name: "InterpolateValueAction",
  52728. properties: [
  52729. BABYLON.Action._GetTargetProperty(this._target),
  52730. { name: "propertyPath", value: this.propertyPath },
  52731. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52732. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52733. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52734. ]
  52735. }, parent);
  52736. };
  52737. return InterpolateValueAction;
  52738. }(BABYLON.Action));
  52739. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52740. })(BABYLON || (BABYLON = {}));
  52741. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52742. var BABYLON;
  52743. (function (BABYLON) {
  52744. var SwitchBooleanAction = /** @class */ (function (_super) {
  52745. __extends(SwitchBooleanAction, _super);
  52746. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52747. var _this = _super.call(this, triggerOptions, condition) || this;
  52748. _this.propertyPath = propertyPath;
  52749. _this._target = _this._effectiveTarget = target;
  52750. return _this;
  52751. }
  52752. SwitchBooleanAction.prototype._prepare = function () {
  52753. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52754. this._property = this._getProperty(this.propertyPath);
  52755. };
  52756. SwitchBooleanAction.prototype.execute = function () {
  52757. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52758. };
  52759. SwitchBooleanAction.prototype.serialize = function (parent) {
  52760. return _super.prototype._serialize.call(this, {
  52761. name: "SwitchBooleanAction",
  52762. properties: [
  52763. BABYLON.Action._GetTargetProperty(this._target),
  52764. { name: "propertyPath", value: this.propertyPath }
  52765. ]
  52766. }, parent);
  52767. };
  52768. return SwitchBooleanAction;
  52769. }(BABYLON.Action));
  52770. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52771. var SetStateAction = /** @class */ (function (_super) {
  52772. __extends(SetStateAction, _super);
  52773. function SetStateAction(triggerOptions, target, value, condition) {
  52774. var _this = _super.call(this, triggerOptions, condition) || this;
  52775. _this.value = value;
  52776. _this._target = target;
  52777. return _this;
  52778. }
  52779. SetStateAction.prototype.execute = function () {
  52780. this._target.state = this.value;
  52781. };
  52782. SetStateAction.prototype.serialize = function (parent) {
  52783. return _super.prototype._serialize.call(this, {
  52784. name: "SetStateAction",
  52785. properties: [
  52786. BABYLON.Action._GetTargetProperty(this._target),
  52787. { name: "value", value: this.value }
  52788. ]
  52789. }, parent);
  52790. };
  52791. return SetStateAction;
  52792. }(BABYLON.Action));
  52793. BABYLON.SetStateAction = SetStateAction;
  52794. var SetValueAction = /** @class */ (function (_super) {
  52795. __extends(SetValueAction, _super);
  52796. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52797. var _this = _super.call(this, triggerOptions, condition) || this;
  52798. _this.propertyPath = propertyPath;
  52799. _this.value = value;
  52800. _this._target = _this._effectiveTarget = target;
  52801. return _this;
  52802. }
  52803. SetValueAction.prototype._prepare = function () {
  52804. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52805. this._property = this._getProperty(this.propertyPath);
  52806. };
  52807. SetValueAction.prototype.execute = function () {
  52808. this._effectiveTarget[this._property] = this.value;
  52809. if (this._target.markAsDirty) {
  52810. this._target.markAsDirty(this._property);
  52811. }
  52812. };
  52813. SetValueAction.prototype.serialize = function (parent) {
  52814. return _super.prototype._serialize.call(this, {
  52815. name: "SetValueAction",
  52816. properties: [
  52817. BABYLON.Action._GetTargetProperty(this._target),
  52818. { name: "propertyPath", value: this.propertyPath },
  52819. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52820. ]
  52821. }, parent);
  52822. };
  52823. return SetValueAction;
  52824. }(BABYLON.Action));
  52825. BABYLON.SetValueAction = SetValueAction;
  52826. var IncrementValueAction = /** @class */ (function (_super) {
  52827. __extends(IncrementValueAction, _super);
  52828. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52829. var _this = _super.call(this, triggerOptions, condition) || this;
  52830. _this.propertyPath = propertyPath;
  52831. _this.value = value;
  52832. _this._target = _this._effectiveTarget = target;
  52833. return _this;
  52834. }
  52835. IncrementValueAction.prototype._prepare = function () {
  52836. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52837. this._property = this._getProperty(this.propertyPath);
  52838. if (typeof this._effectiveTarget[this._property] !== "number") {
  52839. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52840. }
  52841. };
  52842. IncrementValueAction.prototype.execute = function () {
  52843. this._effectiveTarget[this._property] += this.value;
  52844. if (this._target.markAsDirty) {
  52845. this._target.markAsDirty(this._property);
  52846. }
  52847. };
  52848. IncrementValueAction.prototype.serialize = function (parent) {
  52849. return _super.prototype._serialize.call(this, {
  52850. name: "IncrementValueAction",
  52851. properties: [
  52852. BABYLON.Action._GetTargetProperty(this._target),
  52853. { name: "propertyPath", value: this.propertyPath },
  52854. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52855. ]
  52856. }, parent);
  52857. };
  52858. return IncrementValueAction;
  52859. }(BABYLON.Action));
  52860. BABYLON.IncrementValueAction = IncrementValueAction;
  52861. var PlayAnimationAction = /** @class */ (function (_super) {
  52862. __extends(PlayAnimationAction, _super);
  52863. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52864. var _this = _super.call(this, triggerOptions, condition) || this;
  52865. _this.from = from;
  52866. _this.to = to;
  52867. _this.loop = loop;
  52868. _this._target = target;
  52869. return _this;
  52870. }
  52871. PlayAnimationAction.prototype._prepare = function () {
  52872. };
  52873. PlayAnimationAction.prototype.execute = function () {
  52874. var scene = this._actionManager.getScene();
  52875. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52876. };
  52877. PlayAnimationAction.prototype.serialize = function (parent) {
  52878. return _super.prototype._serialize.call(this, {
  52879. name: "PlayAnimationAction",
  52880. properties: [
  52881. BABYLON.Action._GetTargetProperty(this._target),
  52882. { name: "from", value: String(this.from) },
  52883. { name: "to", value: String(this.to) },
  52884. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52885. ]
  52886. }, parent);
  52887. };
  52888. return PlayAnimationAction;
  52889. }(BABYLON.Action));
  52890. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52891. var StopAnimationAction = /** @class */ (function (_super) {
  52892. __extends(StopAnimationAction, _super);
  52893. function StopAnimationAction(triggerOptions, target, condition) {
  52894. var _this = _super.call(this, triggerOptions, condition) || this;
  52895. _this._target = target;
  52896. return _this;
  52897. }
  52898. StopAnimationAction.prototype._prepare = function () {
  52899. };
  52900. StopAnimationAction.prototype.execute = function () {
  52901. var scene = this._actionManager.getScene();
  52902. scene.stopAnimation(this._target);
  52903. };
  52904. StopAnimationAction.prototype.serialize = function (parent) {
  52905. return _super.prototype._serialize.call(this, {
  52906. name: "StopAnimationAction",
  52907. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52908. }, parent);
  52909. };
  52910. return StopAnimationAction;
  52911. }(BABYLON.Action));
  52912. BABYLON.StopAnimationAction = StopAnimationAction;
  52913. var DoNothingAction = /** @class */ (function (_super) {
  52914. __extends(DoNothingAction, _super);
  52915. function DoNothingAction(triggerOptions, condition) {
  52916. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52917. return _super.call(this, triggerOptions, condition) || this;
  52918. }
  52919. DoNothingAction.prototype.execute = function () {
  52920. };
  52921. DoNothingAction.prototype.serialize = function (parent) {
  52922. return _super.prototype._serialize.call(this, {
  52923. name: "DoNothingAction",
  52924. properties: []
  52925. }, parent);
  52926. };
  52927. return DoNothingAction;
  52928. }(BABYLON.Action));
  52929. BABYLON.DoNothingAction = DoNothingAction;
  52930. var CombineAction = /** @class */ (function (_super) {
  52931. __extends(CombineAction, _super);
  52932. function CombineAction(triggerOptions, children, condition) {
  52933. var _this = _super.call(this, triggerOptions, condition) || this;
  52934. _this.children = children;
  52935. return _this;
  52936. }
  52937. CombineAction.prototype._prepare = function () {
  52938. for (var index = 0; index < this.children.length; index++) {
  52939. this.children[index]._actionManager = this._actionManager;
  52940. this.children[index]._prepare();
  52941. }
  52942. };
  52943. CombineAction.prototype.execute = function (evt) {
  52944. for (var index = 0; index < this.children.length; index++) {
  52945. this.children[index].execute(evt);
  52946. }
  52947. };
  52948. CombineAction.prototype.serialize = function (parent) {
  52949. var serializationObject = _super.prototype._serialize.call(this, {
  52950. name: "CombineAction",
  52951. properties: [],
  52952. combine: []
  52953. }, parent);
  52954. for (var i = 0; i < this.children.length; i++) {
  52955. serializationObject.combine.push(this.children[i].serialize(null));
  52956. }
  52957. return serializationObject;
  52958. };
  52959. return CombineAction;
  52960. }(BABYLON.Action));
  52961. BABYLON.CombineAction = CombineAction;
  52962. var ExecuteCodeAction = /** @class */ (function (_super) {
  52963. __extends(ExecuteCodeAction, _super);
  52964. function ExecuteCodeAction(triggerOptions, func, condition) {
  52965. var _this = _super.call(this, triggerOptions, condition) || this;
  52966. _this.func = func;
  52967. return _this;
  52968. }
  52969. ExecuteCodeAction.prototype.execute = function (evt) {
  52970. this.func(evt);
  52971. };
  52972. return ExecuteCodeAction;
  52973. }(BABYLON.Action));
  52974. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52975. var SetParentAction = /** @class */ (function (_super) {
  52976. __extends(SetParentAction, _super);
  52977. function SetParentAction(triggerOptions, target, parent, condition) {
  52978. var _this = _super.call(this, triggerOptions, condition) || this;
  52979. _this._target = target;
  52980. _this._parent = parent;
  52981. return _this;
  52982. }
  52983. SetParentAction.prototype._prepare = function () {
  52984. };
  52985. SetParentAction.prototype.execute = function () {
  52986. if (this._target.parent === this._parent) {
  52987. return;
  52988. }
  52989. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52990. invertParentWorldMatrix.invert();
  52991. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52992. this._target.parent = this._parent;
  52993. };
  52994. SetParentAction.prototype.serialize = function (parent) {
  52995. return _super.prototype._serialize.call(this, {
  52996. name: "SetParentAction",
  52997. properties: [
  52998. BABYLON.Action._GetTargetProperty(this._target),
  52999. BABYLON.Action._GetTargetProperty(this._parent),
  53000. ]
  53001. }, parent);
  53002. };
  53003. return SetParentAction;
  53004. }(BABYLON.Action));
  53005. BABYLON.SetParentAction = SetParentAction;
  53006. var PlaySoundAction = /** @class */ (function (_super) {
  53007. __extends(PlaySoundAction, _super);
  53008. function PlaySoundAction(triggerOptions, sound, condition) {
  53009. var _this = _super.call(this, triggerOptions, condition) || this;
  53010. _this._sound = sound;
  53011. return _this;
  53012. }
  53013. PlaySoundAction.prototype._prepare = function () {
  53014. };
  53015. PlaySoundAction.prototype.execute = function () {
  53016. if (this._sound !== undefined)
  53017. this._sound.play();
  53018. };
  53019. PlaySoundAction.prototype.serialize = function (parent) {
  53020. return _super.prototype._serialize.call(this, {
  53021. name: "PlaySoundAction",
  53022. properties: [{ name: "sound", value: this._sound.name }]
  53023. }, parent);
  53024. };
  53025. return PlaySoundAction;
  53026. }(BABYLON.Action));
  53027. BABYLON.PlaySoundAction = PlaySoundAction;
  53028. var StopSoundAction = /** @class */ (function (_super) {
  53029. __extends(StopSoundAction, _super);
  53030. function StopSoundAction(triggerOptions, sound, condition) {
  53031. var _this = _super.call(this, triggerOptions, condition) || this;
  53032. _this._sound = sound;
  53033. return _this;
  53034. }
  53035. StopSoundAction.prototype._prepare = function () {
  53036. };
  53037. StopSoundAction.prototype.execute = function () {
  53038. if (this._sound !== undefined)
  53039. this._sound.stop();
  53040. };
  53041. StopSoundAction.prototype.serialize = function (parent) {
  53042. return _super.prototype._serialize.call(this, {
  53043. name: "StopSoundAction",
  53044. properties: [{ name: "sound", value: this._sound.name }]
  53045. }, parent);
  53046. };
  53047. return StopSoundAction;
  53048. }(BABYLON.Action));
  53049. BABYLON.StopSoundAction = StopSoundAction;
  53050. })(BABYLON || (BABYLON = {}));
  53051. //# sourceMappingURL=babylon.directActions.js.map
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. var SpriteManager = /** @class */ (function () {
  53055. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53056. if (epsilon === void 0) { epsilon = 0.01; }
  53057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53058. this.name = name;
  53059. this.sprites = new Array();
  53060. this.renderingGroupId = 0;
  53061. this.layerMask = 0x0FFFFFFF;
  53062. this.fogEnabled = true;
  53063. this.isPickable = false;
  53064. /**
  53065. * An event triggered when the manager is disposed.
  53066. */
  53067. this.onDisposeObservable = new BABYLON.Observable();
  53068. this._vertexBuffers = {};
  53069. this._capacity = capacity;
  53070. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53071. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53072. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53073. if (cellSize.width && cellSize.height) {
  53074. this.cellWidth = cellSize.width;
  53075. this.cellHeight = cellSize.height;
  53076. }
  53077. else if (cellSize !== undefined) {
  53078. this.cellWidth = cellSize;
  53079. this.cellHeight = cellSize;
  53080. }
  53081. else {
  53082. return;
  53083. }
  53084. this._epsilon = epsilon;
  53085. this._scene = scene;
  53086. this._scene.spriteManagers.push(this);
  53087. var indices = [];
  53088. var index = 0;
  53089. for (var count = 0; count < capacity; count++) {
  53090. indices.push(index);
  53091. indices.push(index + 1);
  53092. indices.push(index + 2);
  53093. indices.push(index);
  53094. indices.push(index + 2);
  53095. indices.push(index + 3);
  53096. index += 4;
  53097. }
  53098. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53099. // VBO
  53100. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53101. this._vertexData = new Float32Array(capacity * 16 * 4);
  53102. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53103. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53104. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53105. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53106. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53108. this._vertexBuffers["options"] = options;
  53109. this._vertexBuffers["cellInfo"] = cellInfo;
  53110. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53111. // Effects
  53112. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53113. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53114. }
  53115. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53116. set: function (callback) {
  53117. if (this._onDisposeObserver) {
  53118. this.onDisposeObservable.remove(this._onDisposeObserver);
  53119. }
  53120. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53121. },
  53122. enumerable: true,
  53123. configurable: true
  53124. });
  53125. Object.defineProperty(SpriteManager.prototype, "texture", {
  53126. get: function () {
  53127. return this._spriteTexture;
  53128. },
  53129. set: function (value) {
  53130. this._spriteTexture = value;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53136. var arrayOffset = index * 16;
  53137. if (offsetX === 0)
  53138. offsetX = this._epsilon;
  53139. else if (offsetX === 1)
  53140. offsetX = 1 - this._epsilon;
  53141. if (offsetY === 0)
  53142. offsetY = this._epsilon;
  53143. else if (offsetY === 1)
  53144. offsetY = 1 - this._epsilon;
  53145. this._vertexData[arrayOffset] = sprite.position.x;
  53146. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53147. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53148. this._vertexData[arrayOffset + 3] = sprite.angle;
  53149. this._vertexData[arrayOffset + 4] = sprite.width;
  53150. this._vertexData[arrayOffset + 5] = sprite.height;
  53151. this._vertexData[arrayOffset + 6] = offsetX;
  53152. this._vertexData[arrayOffset + 7] = offsetY;
  53153. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53154. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53155. var offset = (sprite.cellIndex / rowSize) >> 0;
  53156. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53157. this._vertexData[arrayOffset + 11] = offset;
  53158. // Color
  53159. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53160. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53161. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53162. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53163. };
  53164. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53165. var count = Math.min(this._capacity, this.sprites.length);
  53166. var min = BABYLON.Vector3.Zero();
  53167. var max = BABYLON.Vector3.Zero();
  53168. var distance = Number.MAX_VALUE;
  53169. var currentSprite = null;
  53170. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53171. var cameraView = camera.getViewMatrix();
  53172. for (var index = 0; index < count; index++) {
  53173. var sprite = this.sprites[index];
  53174. if (!sprite) {
  53175. continue;
  53176. }
  53177. if (predicate) {
  53178. if (!predicate(sprite)) {
  53179. continue;
  53180. }
  53181. }
  53182. else if (!sprite.isPickable) {
  53183. continue;
  53184. }
  53185. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53186. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53187. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53188. if (ray.intersectsBoxMinMax(min, max)) {
  53189. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53190. if (distance > currentDistance) {
  53191. distance = currentDistance;
  53192. currentSprite = sprite;
  53193. if (fastCheck) {
  53194. break;
  53195. }
  53196. }
  53197. }
  53198. }
  53199. if (currentSprite) {
  53200. var result = new BABYLON.PickingInfo();
  53201. result.hit = true;
  53202. result.pickedSprite = currentSprite;
  53203. result.distance = distance;
  53204. return result;
  53205. }
  53206. return null;
  53207. };
  53208. SpriteManager.prototype.render = function () {
  53209. // Check
  53210. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53211. return;
  53212. var engine = this._scene.getEngine();
  53213. var baseSize = this._spriteTexture.getBaseSize();
  53214. // Sprites
  53215. var deltaTime = engine.getDeltaTime();
  53216. var max = Math.min(this._capacity, this.sprites.length);
  53217. var rowSize = baseSize.width / this.cellWidth;
  53218. var offset = 0;
  53219. for (var index = 0; index < max; index++) {
  53220. var sprite = this.sprites[index];
  53221. if (!sprite || !sprite.isVisible) {
  53222. continue;
  53223. }
  53224. sprite._animate(deltaTime);
  53225. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53226. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53227. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53228. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53229. }
  53230. this._buffer.update(this._vertexData);
  53231. // Render
  53232. var effect = this._effectBase;
  53233. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53234. effect = this._effectFog;
  53235. }
  53236. engine.enableEffect(effect);
  53237. var viewMatrix = this._scene.getViewMatrix();
  53238. effect.setTexture("diffuseSampler", this._spriteTexture);
  53239. effect.setMatrix("view", viewMatrix);
  53240. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53241. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53242. // Fog
  53243. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53244. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53245. effect.setColor3("vFogColor", this._scene.fogColor);
  53246. }
  53247. // VBOs
  53248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53249. // Draw order
  53250. engine.setDepthFunctionToLessOrEqual();
  53251. effect.setBool("alphaTest", true);
  53252. engine.setColorWrite(false);
  53253. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53254. engine.setColorWrite(true);
  53255. effect.setBool("alphaTest", false);
  53256. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53257. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53258. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53259. };
  53260. SpriteManager.prototype.dispose = function () {
  53261. if (this._buffer) {
  53262. this._buffer.dispose();
  53263. this._buffer = null;
  53264. }
  53265. if (this._indexBuffer) {
  53266. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53267. this._indexBuffer = null;
  53268. }
  53269. if (this._spriteTexture) {
  53270. this._spriteTexture.dispose();
  53271. this._spriteTexture = null;
  53272. }
  53273. // Remove from scene
  53274. var index = this._scene.spriteManagers.indexOf(this);
  53275. this._scene.spriteManagers.splice(index, 1);
  53276. // Callback
  53277. this.onDisposeObservable.notifyObservers(this);
  53278. this.onDisposeObservable.clear();
  53279. };
  53280. return SpriteManager;
  53281. }());
  53282. BABYLON.SpriteManager = SpriteManager;
  53283. })(BABYLON || (BABYLON = {}));
  53284. //# sourceMappingURL=babylon.spriteManager.js.map
  53285. var BABYLON;
  53286. (function (BABYLON) {
  53287. var Sprite = /** @class */ (function () {
  53288. function Sprite(name, manager) {
  53289. this.name = name;
  53290. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53291. this.width = 1.0;
  53292. this.height = 1.0;
  53293. this.angle = 0;
  53294. this.cellIndex = 0;
  53295. this.invertU = 0;
  53296. this.invertV = 0;
  53297. this.animations = new Array();
  53298. this.isPickable = false;
  53299. this._animationStarted = false;
  53300. this._loopAnimation = false;
  53301. this._fromIndex = 0;
  53302. this._toIndex = 0;
  53303. this._delay = 0;
  53304. this._direction = 1;
  53305. this._time = 0;
  53306. /**
  53307. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53308. */
  53309. this.isVisible = true;
  53310. this._manager = manager;
  53311. this._manager.sprites.push(this);
  53312. this.position = BABYLON.Vector3.Zero();
  53313. }
  53314. Object.defineProperty(Sprite.prototype, "size", {
  53315. get: function () {
  53316. return this.width;
  53317. },
  53318. set: function (value) {
  53319. this.width = value;
  53320. this.height = value;
  53321. },
  53322. enumerable: true,
  53323. configurable: true
  53324. });
  53325. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53326. this._fromIndex = from;
  53327. this._toIndex = to;
  53328. this._loopAnimation = loop;
  53329. this._delay = delay;
  53330. this._animationStarted = true;
  53331. this._direction = from < to ? 1 : -1;
  53332. this.cellIndex = from;
  53333. this._time = 0;
  53334. this._onAnimationEnd = onAnimationEnd;
  53335. };
  53336. Sprite.prototype.stopAnimation = function () {
  53337. this._animationStarted = false;
  53338. };
  53339. Sprite.prototype._animate = function (deltaTime) {
  53340. if (!this._animationStarted)
  53341. return;
  53342. this._time += deltaTime;
  53343. if (this._time > this._delay) {
  53344. this._time = this._time % this._delay;
  53345. this.cellIndex += this._direction;
  53346. if (this.cellIndex > this._toIndex) {
  53347. if (this._loopAnimation) {
  53348. this.cellIndex = this._fromIndex;
  53349. }
  53350. else {
  53351. this.cellIndex = this._toIndex;
  53352. this._animationStarted = false;
  53353. if (this._onAnimationEnd) {
  53354. this._onAnimationEnd();
  53355. }
  53356. if (this.disposeWhenFinishedAnimating) {
  53357. this.dispose();
  53358. }
  53359. }
  53360. }
  53361. }
  53362. };
  53363. Sprite.prototype.dispose = function () {
  53364. for (var i = 0; i < this._manager.sprites.length; i++) {
  53365. if (this._manager.sprites[i] == this) {
  53366. this._manager.sprites.splice(i, 1);
  53367. }
  53368. }
  53369. };
  53370. return Sprite;
  53371. }());
  53372. BABYLON.Sprite = Sprite;
  53373. })(BABYLON || (BABYLON = {}));
  53374. //# sourceMappingURL=babylon.sprite.js.map
  53375. var BABYLON;
  53376. (function (BABYLON) {
  53377. var IntersectionInfo = /** @class */ (function () {
  53378. function IntersectionInfo(bu, bv, distance) {
  53379. this.bu = bu;
  53380. this.bv = bv;
  53381. this.distance = distance;
  53382. this.faceId = 0;
  53383. this.subMeshId = 0;
  53384. }
  53385. return IntersectionInfo;
  53386. }());
  53387. BABYLON.IntersectionInfo = IntersectionInfo;
  53388. /**
  53389. * Information about the result of picking within a scene
  53390. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53391. */
  53392. var PickingInfo = /** @class */ (function () {
  53393. function PickingInfo() {
  53394. /**
  53395. * If the pick collided with an object
  53396. */
  53397. this.hit = false;
  53398. /**
  53399. * Distance away where the pick collided
  53400. */
  53401. this.distance = 0;
  53402. /**
  53403. * The location of pick collision
  53404. */
  53405. this.pickedPoint = null;
  53406. /**
  53407. * The mesh corrisponding the the pick collision
  53408. */
  53409. this.pickedMesh = null;
  53410. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53411. this.bu = 0;
  53412. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53413. this.bv = 0;
  53414. /** The id of the face on the mesh that was picked */
  53415. this.faceId = -1;
  53416. /** Id of the the submesh that was picked */
  53417. this.subMeshId = 0;
  53418. /** If a sprite was picked, this will be the sprite the pick collided with */
  53419. this.pickedSprite = null;
  53420. /**
  53421. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53422. */
  53423. this.originMesh = null;
  53424. /**
  53425. * The ray that was used to perform the picking.
  53426. */
  53427. this.ray = null;
  53428. }
  53429. /**
  53430. * Gets the normal corrispodning to the face the pick collided with
  53431. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53432. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53433. * @returns The normal corrispodning to the face the pick collided with
  53434. */
  53435. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53436. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53437. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53438. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53439. return null;
  53440. }
  53441. var indices = this.pickedMesh.getIndices();
  53442. if (!indices) {
  53443. return null;
  53444. }
  53445. var result;
  53446. if (useVerticesNormals) {
  53447. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53448. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53449. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53450. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53451. normal0 = normal0.scale(this.bu);
  53452. normal1 = normal1.scale(this.bv);
  53453. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53454. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53455. }
  53456. else {
  53457. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53458. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53459. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53460. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53461. var p1p2 = vertex1.subtract(vertex2);
  53462. var p3p2 = vertex3.subtract(vertex2);
  53463. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53464. }
  53465. if (useWorldCoordinates) {
  53466. var wm = this.pickedMesh.getWorldMatrix();
  53467. if (this.pickedMesh.nonUniformScaling) {
  53468. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53469. wm = BABYLON.Tmp.Matrix[0];
  53470. wm.setTranslationFromFloats(0, 0, 0);
  53471. wm.invert();
  53472. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53473. wm = BABYLON.Tmp.Matrix[1];
  53474. }
  53475. result = BABYLON.Vector3.TransformNormal(result, wm);
  53476. }
  53477. result.normalize();
  53478. return result;
  53479. };
  53480. /**
  53481. * Gets the texture coordinates of where the pick occured
  53482. * @returns the vector containing the coordnates of the texture
  53483. */
  53484. PickingInfo.prototype.getTextureCoordinates = function () {
  53485. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53486. return null;
  53487. }
  53488. var indices = this.pickedMesh.getIndices();
  53489. if (!indices) {
  53490. return null;
  53491. }
  53492. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53493. if (!uvs) {
  53494. return null;
  53495. }
  53496. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53497. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53498. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53499. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53500. uv1 = uv1.scale(this.bu);
  53501. uv2 = uv2.scale(this.bv);
  53502. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53503. };
  53504. return PickingInfo;
  53505. }());
  53506. BABYLON.PickingInfo = PickingInfo;
  53507. })(BABYLON || (BABYLON = {}));
  53508. //# sourceMappingURL=babylon.pickingInfo.js.map
  53509. var BABYLON;
  53510. (function (BABYLON) {
  53511. var Ray = /** @class */ (function () {
  53512. function Ray(origin, direction, length) {
  53513. if (length === void 0) { length = Number.MAX_VALUE; }
  53514. this.origin = origin;
  53515. this.direction = direction;
  53516. this.length = length;
  53517. }
  53518. // Methods
  53519. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53520. var d = 0.0;
  53521. var maxValue = Number.MAX_VALUE;
  53522. var inv;
  53523. var min;
  53524. var max;
  53525. var temp;
  53526. if (Math.abs(this.direction.x) < 0.0000001) {
  53527. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53528. return false;
  53529. }
  53530. }
  53531. else {
  53532. inv = 1.0 / this.direction.x;
  53533. min = (minimum.x - this.origin.x) * inv;
  53534. max = (maximum.x - this.origin.x) * inv;
  53535. if (max === -Infinity) {
  53536. max = Infinity;
  53537. }
  53538. if (min > max) {
  53539. temp = min;
  53540. min = max;
  53541. max = temp;
  53542. }
  53543. d = Math.max(min, d);
  53544. maxValue = Math.min(max, maxValue);
  53545. if (d > maxValue) {
  53546. return false;
  53547. }
  53548. }
  53549. if (Math.abs(this.direction.y) < 0.0000001) {
  53550. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53551. return false;
  53552. }
  53553. }
  53554. else {
  53555. inv = 1.0 / this.direction.y;
  53556. min = (minimum.y - this.origin.y) * inv;
  53557. max = (maximum.y - this.origin.y) * inv;
  53558. if (max === -Infinity) {
  53559. max = Infinity;
  53560. }
  53561. if (min > max) {
  53562. temp = min;
  53563. min = max;
  53564. max = temp;
  53565. }
  53566. d = Math.max(min, d);
  53567. maxValue = Math.min(max, maxValue);
  53568. if (d > maxValue) {
  53569. return false;
  53570. }
  53571. }
  53572. if (Math.abs(this.direction.z) < 0.0000001) {
  53573. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53574. return false;
  53575. }
  53576. }
  53577. else {
  53578. inv = 1.0 / this.direction.z;
  53579. min = (minimum.z - this.origin.z) * inv;
  53580. max = (maximum.z - this.origin.z) * inv;
  53581. if (max === -Infinity) {
  53582. max = Infinity;
  53583. }
  53584. if (min > max) {
  53585. temp = min;
  53586. min = max;
  53587. max = temp;
  53588. }
  53589. d = Math.max(min, d);
  53590. maxValue = Math.min(max, maxValue);
  53591. if (d > maxValue) {
  53592. return false;
  53593. }
  53594. }
  53595. return true;
  53596. };
  53597. Ray.prototype.intersectsBox = function (box) {
  53598. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53599. };
  53600. Ray.prototype.intersectsSphere = function (sphere) {
  53601. var x = sphere.center.x - this.origin.x;
  53602. var y = sphere.center.y - this.origin.y;
  53603. var z = sphere.center.z - this.origin.z;
  53604. var pyth = (x * x) + (y * y) + (z * z);
  53605. var rr = sphere.radius * sphere.radius;
  53606. if (pyth <= rr) {
  53607. return true;
  53608. }
  53609. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53610. if (dot < 0.0) {
  53611. return false;
  53612. }
  53613. var temp = pyth - (dot * dot);
  53614. return temp <= rr;
  53615. };
  53616. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53617. if (!this._edge1) {
  53618. this._edge1 = BABYLON.Vector3.Zero();
  53619. this._edge2 = BABYLON.Vector3.Zero();
  53620. this._pvec = BABYLON.Vector3.Zero();
  53621. this._tvec = BABYLON.Vector3.Zero();
  53622. this._qvec = BABYLON.Vector3.Zero();
  53623. }
  53624. vertex1.subtractToRef(vertex0, this._edge1);
  53625. vertex2.subtractToRef(vertex0, this._edge2);
  53626. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53627. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53628. if (det === 0) {
  53629. return null;
  53630. }
  53631. var invdet = 1 / det;
  53632. this.origin.subtractToRef(vertex0, this._tvec);
  53633. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53634. if (bu < 0 || bu > 1.0) {
  53635. return null;
  53636. }
  53637. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53638. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53639. if (bv < 0 || bu + bv > 1.0) {
  53640. return null;
  53641. }
  53642. //check if the distance is longer than the predefined length.
  53643. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53644. if (distance > this.length) {
  53645. return null;
  53646. }
  53647. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53648. };
  53649. Ray.prototype.intersectsPlane = function (plane) {
  53650. var distance;
  53651. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53652. if (Math.abs(result1) < 9.99999997475243E-07) {
  53653. return null;
  53654. }
  53655. else {
  53656. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53657. distance = (-plane.d - result2) / result1;
  53658. if (distance < 0.0) {
  53659. if (distance < -9.99999997475243E-07) {
  53660. return null;
  53661. }
  53662. else {
  53663. return 0;
  53664. }
  53665. }
  53666. return distance;
  53667. }
  53668. };
  53669. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53670. var tm = BABYLON.Tmp.Matrix[0];
  53671. mesh.getWorldMatrix().invertToRef(tm);
  53672. if (this._tmpRay) {
  53673. Ray.TransformToRef(this, tm, this._tmpRay);
  53674. }
  53675. else {
  53676. this._tmpRay = Ray.Transform(this, tm);
  53677. }
  53678. return mesh.intersects(this._tmpRay, fastCheck);
  53679. };
  53680. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53681. if (results) {
  53682. results.length = 0;
  53683. }
  53684. else {
  53685. results = [];
  53686. }
  53687. for (var i = 0; i < meshes.length; i++) {
  53688. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53689. if (pickInfo.hit) {
  53690. results.push(pickInfo);
  53691. }
  53692. }
  53693. results.sort(this._comparePickingInfo);
  53694. return results;
  53695. };
  53696. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53697. if (pickingInfoA.distance < pickingInfoB.distance) {
  53698. return -1;
  53699. }
  53700. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53701. return 1;
  53702. }
  53703. else {
  53704. return 0;
  53705. }
  53706. };
  53707. /**
  53708. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53709. * @param sega the first point of the segment to test the intersection against
  53710. * @param segb the second point of the segment to test the intersection against
  53711. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53712. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53713. */
  53714. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53715. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53716. var u = segb.subtract(sega);
  53717. var v = rsegb.subtract(this.origin);
  53718. var w = sega.subtract(this.origin);
  53719. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53720. var b = BABYLON.Vector3.Dot(u, v);
  53721. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53722. var d = BABYLON.Vector3.Dot(u, w);
  53723. var e = BABYLON.Vector3.Dot(v, w);
  53724. var D = a * c - b * b; // always >= 0
  53725. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53726. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53727. // compute the line parameters of the two closest points
  53728. if (D < Ray.smallnum) { // the lines are almost parallel
  53729. sN = 0.0; // force using point P0 on segment S1
  53730. sD = 1.0; // to prevent possible division by 0.0 later
  53731. tN = e;
  53732. tD = c;
  53733. }
  53734. else { // get the closest points on the infinite lines
  53735. sN = (b * e - c * d);
  53736. tN = (a * e - b * d);
  53737. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53738. sN = 0.0;
  53739. tN = e;
  53740. tD = c;
  53741. }
  53742. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53743. sN = sD;
  53744. tN = e + b;
  53745. tD = c;
  53746. }
  53747. }
  53748. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53749. tN = 0.0;
  53750. // recompute sc for this edge
  53751. if (-d < 0.0) {
  53752. sN = 0.0;
  53753. }
  53754. else if (-d > a)
  53755. sN = sD;
  53756. else {
  53757. sN = -d;
  53758. sD = a;
  53759. }
  53760. }
  53761. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53762. tN = tD;
  53763. // recompute sc for this edge
  53764. if ((-d + b) < 0.0) {
  53765. sN = 0;
  53766. }
  53767. else if ((-d + b) > a) {
  53768. sN = sD;
  53769. }
  53770. else {
  53771. sN = (-d + b);
  53772. sD = a;
  53773. }
  53774. }
  53775. // finally do the division to get sc and tc
  53776. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53777. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53778. // get the difference of the two closest points
  53779. var qtc = v.multiplyByFloats(tc, tc, tc);
  53780. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53781. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53782. if (isIntersected) {
  53783. return qtc.length();
  53784. }
  53785. return -1;
  53786. };
  53787. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53788. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53789. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53790. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53791. this.direction.normalize();
  53792. return this;
  53793. };
  53794. // Statics
  53795. Ray.Zero = function () {
  53796. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53797. };
  53798. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53799. var result = Ray.Zero();
  53800. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53801. };
  53802. /**
  53803. * 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
  53804. * transformed to the given world matrix.
  53805. * @param origin The origin point
  53806. * @param end The end point
  53807. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53808. */
  53809. Ray.CreateNewFromTo = function (origin, end, world) {
  53810. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53811. var direction = end.subtract(origin);
  53812. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53813. direction.normalize();
  53814. return Ray.Transform(new Ray(origin, direction, length), world);
  53815. };
  53816. Ray.Transform = function (ray, matrix) {
  53817. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53818. Ray.TransformToRef(ray, matrix, result);
  53819. return result;
  53820. };
  53821. Ray.TransformToRef = function (ray, matrix, result) {
  53822. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53823. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53824. result.length = ray.length;
  53825. var dir = result.direction;
  53826. var len = dir.length();
  53827. if (!(len === 0 || len === 1)) {
  53828. var num = 1.0 / len;
  53829. dir.x *= num;
  53830. dir.y *= num;
  53831. dir.z *= num;
  53832. result.length *= len;
  53833. }
  53834. };
  53835. Ray.smallnum = 0.00000001;
  53836. Ray.rayl = 10e8;
  53837. return Ray;
  53838. }());
  53839. BABYLON.Ray = Ray;
  53840. })(BABYLON || (BABYLON = {}));
  53841. //# sourceMappingURL=babylon.ray.js.map
  53842. var BABYLON;
  53843. (function (BABYLON) {
  53844. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53845. if (boxMin.x > sphereCenter.x + sphereRadius)
  53846. return false;
  53847. if (sphereCenter.x - sphereRadius > boxMax.x)
  53848. return false;
  53849. if (boxMin.y > sphereCenter.y + sphereRadius)
  53850. return false;
  53851. if (sphereCenter.y - sphereRadius > boxMax.y)
  53852. return false;
  53853. if (boxMin.z > sphereCenter.z + sphereRadius)
  53854. return false;
  53855. if (sphereCenter.z - sphereRadius > boxMax.z)
  53856. return false;
  53857. return true;
  53858. };
  53859. var getLowestRoot = (function () {
  53860. var result = { root: 0, found: false };
  53861. return function (a, b, c, maxR) {
  53862. result.root = 0;
  53863. result.found = false;
  53864. var determinant = b * b - 4.0 * a * c;
  53865. if (determinant < 0)
  53866. return result;
  53867. var sqrtD = Math.sqrt(determinant);
  53868. var r1 = (-b - sqrtD) / (2.0 * a);
  53869. var r2 = (-b + sqrtD) / (2.0 * a);
  53870. if (r1 > r2) {
  53871. var temp = r2;
  53872. r2 = r1;
  53873. r1 = temp;
  53874. }
  53875. if (r1 > 0 && r1 < maxR) {
  53876. result.root = r1;
  53877. result.found = true;
  53878. return result;
  53879. }
  53880. if (r2 > 0 && r2 < maxR) {
  53881. result.root = r2;
  53882. result.found = true;
  53883. return result;
  53884. }
  53885. return result;
  53886. };
  53887. })();
  53888. var Collider = /** @class */ (function () {
  53889. function Collider() {
  53890. this._collisionPoint = BABYLON.Vector3.Zero();
  53891. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53892. this._tempVector = BABYLON.Vector3.Zero();
  53893. this._tempVector2 = BABYLON.Vector3.Zero();
  53894. this._tempVector3 = BABYLON.Vector3.Zero();
  53895. this._tempVector4 = BABYLON.Vector3.Zero();
  53896. this._edge = BABYLON.Vector3.Zero();
  53897. this._baseToVertex = BABYLON.Vector3.Zero();
  53898. this._destinationPoint = BABYLON.Vector3.Zero();
  53899. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53900. this._displacementVector = BABYLON.Vector3.Zero();
  53901. this._radius = BABYLON.Vector3.One();
  53902. this._retry = 0;
  53903. this._basePointWorld = BABYLON.Vector3.Zero();
  53904. this._velocityWorld = BABYLON.Vector3.Zero();
  53905. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53906. this._collisionMask = -1;
  53907. }
  53908. Object.defineProperty(Collider.prototype, "collisionMask", {
  53909. get: function () {
  53910. return this._collisionMask;
  53911. },
  53912. set: function (mask) {
  53913. this._collisionMask = !isNaN(mask) ? mask : -1;
  53914. },
  53915. enumerable: true,
  53916. configurable: true
  53917. });
  53918. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53919. /**
  53920. * Gets the plane normal used to compute the sliding response (in local space)
  53921. */
  53922. get: function () {
  53923. return this._slidePlaneNormal;
  53924. },
  53925. enumerable: true,
  53926. configurable: true
  53927. });
  53928. // Methods
  53929. Collider.prototype._initialize = function (source, dir, e) {
  53930. this._velocity = dir;
  53931. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53932. this._basePoint = source;
  53933. source.multiplyToRef(this._radius, this._basePointWorld);
  53934. dir.multiplyToRef(this._radius, this._velocityWorld);
  53935. this._velocityWorldLength = this._velocityWorld.length();
  53936. this._epsilon = e;
  53937. this.collisionFound = false;
  53938. };
  53939. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53940. pa.subtractToRef(point, this._tempVector);
  53941. pb.subtractToRef(point, this._tempVector2);
  53942. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53943. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53944. if (d < 0)
  53945. return false;
  53946. pc.subtractToRef(point, this._tempVector3);
  53947. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53948. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53949. if (d < 0)
  53950. return false;
  53951. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53952. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53953. return d >= 0;
  53954. };
  53955. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53956. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53957. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53958. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53959. return false;
  53960. }
  53961. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53962. return false;
  53963. return true;
  53964. };
  53965. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53966. var t0;
  53967. var embeddedInPlane = false;
  53968. //defensive programming, actually not needed.
  53969. if (!trianglePlaneArray) {
  53970. trianglePlaneArray = [];
  53971. }
  53972. if (!trianglePlaneArray[faceIndex]) {
  53973. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53974. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53975. }
  53976. var trianglePlane = trianglePlaneArray[faceIndex];
  53977. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53978. return;
  53979. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53980. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53981. if (normalDotVelocity == 0) {
  53982. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53983. return;
  53984. embeddedInPlane = true;
  53985. t0 = 0;
  53986. }
  53987. else {
  53988. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53989. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53990. if (t0 > t1) {
  53991. var temp = t1;
  53992. t1 = t0;
  53993. t0 = temp;
  53994. }
  53995. if (t0 > 1.0 || t1 < 0.0)
  53996. return;
  53997. if (t0 < 0)
  53998. t0 = 0;
  53999. if (t0 > 1.0)
  54000. t0 = 1.0;
  54001. }
  54002. this._collisionPoint.copyFromFloats(0, 0, 0);
  54003. var found = false;
  54004. var t = 1.0;
  54005. if (!embeddedInPlane) {
  54006. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54007. this._velocity.scaleToRef(t0, this._tempVector);
  54008. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54009. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54010. found = true;
  54011. t = t0;
  54012. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54013. }
  54014. }
  54015. if (!found) {
  54016. var velocitySquaredLength = this._velocity.lengthSquared();
  54017. var a = velocitySquaredLength;
  54018. this._basePoint.subtractToRef(p1, this._tempVector);
  54019. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54020. var c = this._tempVector.lengthSquared() - 1.0;
  54021. var lowestRoot = getLowestRoot(a, b, c, t);
  54022. if (lowestRoot.found) {
  54023. t = lowestRoot.root;
  54024. found = true;
  54025. this._collisionPoint.copyFrom(p1);
  54026. }
  54027. this._basePoint.subtractToRef(p2, this._tempVector);
  54028. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54029. c = this._tempVector.lengthSquared() - 1.0;
  54030. lowestRoot = getLowestRoot(a, b, c, t);
  54031. if (lowestRoot.found) {
  54032. t = lowestRoot.root;
  54033. found = true;
  54034. this._collisionPoint.copyFrom(p2);
  54035. }
  54036. this._basePoint.subtractToRef(p3, this._tempVector);
  54037. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54038. c = this._tempVector.lengthSquared() - 1.0;
  54039. lowestRoot = getLowestRoot(a, b, c, t);
  54040. if (lowestRoot.found) {
  54041. t = lowestRoot.root;
  54042. found = true;
  54043. this._collisionPoint.copyFrom(p3);
  54044. }
  54045. p2.subtractToRef(p1, this._edge);
  54046. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54047. var edgeSquaredLength = this._edge.lengthSquared();
  54048. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54049. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54050. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54051. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54052. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54053. lowestRoot = getLowestRoot(a, b, c, t);
  54054. if (lowestRoot.found) {
  54055. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54056. if (f >= 0.0 && f <= 1.0) {
  54057. t = lowestRoot.root;
  54058. found = true;
  54059. this._edge.scaleInPlace(f);
  54060. p1.addToRef(this._edge, this._collisionPoint);
  54061. }
  54062. }
  54063. p3.subtractToRef(p2, this._edge);
  54064. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54065. edgeSquaredLength = this._edge.lengthSquared();
  54066. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54067. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54068. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54069. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54070. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54071. lowestRoot = getLowestRoot(a, b, c, t);
  54072. if (lowestRoot.found) {
  54073. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54074. if (f >= 0.0 && f <= 1.0) {
  54075. t = lowestRoot.root;
  54076. found = true;
  54077. this._edge.scaleInPlace(f);
  54078. p2.addToRef(this._edge, this._collisionPoint);
  54079. }
  54080. }
  54081. p1.subtractToRef(p3, this._edge);
  54082. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54083. edgeSquaredLength = this._edge.lengthSquared();
  54084. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54085. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54086. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54087. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54088. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54089. lowestRoot = getLowestRoot(a, b, c, t);
  54090. if (lowestRoot.found) {
  54091. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54092. if (f >= 0.0 && f <= 1.0) {
  54093. t = lowestRoot.root;
  54094. found = true;
  54095. this._edge.scaleInPlace(f);
  54096. p3.addToRef(this._edge, this._collisionPoint);
  54097. }
  54098. }
  54099. }
  54100. if (found) {
  54101. var distToCollision = t * this._velocity.length();
  54102. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54103. if (!this.intersectionPoint) {
  54104. this.intersectionPoint = this._collisionPoint.clone();
  54105. }
  54106. else {
  54107. this.intersectionPoint.copyFrom(this._collisionPoint);
  54108. }
  54109. this._nearestDistance = distToCollision;
  54110. this.collisionFound = true;
  54111. }
  54112. }
  54113. };
  54114. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54115. for (var i = indexStart; i < indexEnd; i += 3) {
  54116. var p1 = pts[indices[i] - decal];
  54117. var p2 = pts[indices[i + 1] - decal];
  54118. var p3 = pts[indices[i + 2] - decal];
  54119. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54120. }
  54121. };
  54122. Collider.prototype._getResponse = function (pos, vel) {
  54123. pos.addToRef(vel, this._destinationPoint);
  54124. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54125. this._basePoint.addToRef(vel, pos);
  54126. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54127. this._slidePlaneNormal.normalize();
  54128. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54129. pos.addInPlace(this._displacementVector);
  54130. this.intersectionPoint.addInPlace(this._displacementVector);
  54131. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54132. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54133. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54134. };
  54135. return Collider;
  54136. }());
  54137. BABYLON.Collider = Collider;
  54138. })(BABYLON || (BABYLON = {}));
  54139. //# sourceMappingURL=babylon.collider.js.map
  54140. var BABYLON;
  54141. (function (BABYLON) {
  54142. //WebWorker code will be inserted to this variable.
  54143. BABYLON.CollisionWorker = "";
  54144. /** Defines supported task for worker process */
  54145. var WorkerTaskType;
  54146. (function (WorkerTaskType) {
  54147. /** Initialization */
  54148. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54149. /** Update of geometry */
  54150. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54151. /** Evaluate collision */
  54152. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54153. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54154. /** Defines kind of replies returned by worker */
  54155. var WorkerReplyType;
  54156. (function (WorkerReplyType) {
  54157. /** Success */
  54158. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54159. /** Unkown error */
  54160. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54161. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54162. var CollisionCoordinatorWorker = /** @class */ (function () {
  54163. function CollisionCoordinatorWorker() {
  54164. var _this = this;
  54165. this._scaledPosition = BABYLON.Vector3.Zero();
  54166. this._scaledVelocity = BABYLON.Vector3.Zero();
  54167. this.onMeshUpdated = function (transformNode) {
  54168. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54169. };
  54170. this.onGeometryUpdated = function (geometry) {
  54171. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54172. };
  54173. this._afterRender = function () {
  54174. if (!_this._init)
  54175. return;
  54176. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54177. return;
  54178. }
  54179. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54180. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54181. if (_this._runningUpdated > 4) {
  54182. return;
  54183. }
  54184. ++_this._runningUpdated;
  54185. var payload = {
  54186. updatedMeshes: _this._addUpdateMeshesList,
  54187. updatedGeometries: _this._addUpdateGeometriesList,
  54188. removedGeometries: _this._toRemoveGeometryArray,
  54189. removedMeshes: _this._toRemoveMeshesArray
  54190. };
  54191. var message = {
  54192. payload: payload,
  54193. taskType: WorkerTaskType.UPDATE
  54194. };
  54195. var serializable = [];
  54196. for (var id in payload.updatedGeometries) {
  54197. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54198. //prepare transferables
  54199. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54200. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54201. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54202. }
  54203. }
  54204. _this._worker.postMessage(message, serializable);
  54205. _this._addUpdateMeshesList = {};
  54206. _this._addUpdateGeometriesList = {};
  54207. _this._toRemoveGeometryArray = [];
  54208. _this._toRemoveMeshesArray = [];
  54209. };
  54210. this._onMessageFromWorker = function (e) {
  54211. var returnData = e.data;
  54212. if (returnData.error != WorkerReplyType.SUCCESS) {
  54213. //TODO what errors can be returned from the worker?
  54214. BABYLON.Tools.Warn("error returned from worker!");
  54215. return;
  54216. }
  54217. switch (returnData.taskType) {
  54218. case WorkerTaskType.INIT:
  54219. _this._init = true;
  54220. //Update the worked with ALL of the scene's current state
  54221. _this._scene.meshes.forEach(function (mesh) {
  54222. _this.onMeshAdded(mesh);
  54223. });
  54224. _this._scene.getGeometries().forEach(function (geometry) {
  54225. _this.onGeometryAdded(geometry);
  54226. });
  54227. break;
  54228. case WorkerTaskType.UPDATE:
  54229. _this._runningUpdated--;
  54230. break;
  54231. case WorkerTaskType.COLLIDE:
  54232. var returnPayload = returnData.payload;
  54233. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54234. return;
  54235. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54236. if (callback) {
  54237. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54238. if (mesh) {
  54239. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54240. }
  54241. }
  54242. //cleanup
  54243. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54244. break;
  54245. }
  54246. };
  54247. this._collisionsCallbackArray = [];
  54248. this._init = false;
  54249. this._runningUpdated = 0;
  54250. this._addUpdateMeshesList = {};
  54251. this._addUpdateGeometriesList = {};
  54252. this._toRemoveGeometryArray = [];
  54253. this._toRemoveMeshesArray = [];
  54254. }
  54255. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54256. if (!this._init)
  54257. return;
  54258. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54259. return;
  54260. position.divideToRef(collider._radius, this._scaledPosition);
  54261. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54262. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54263. var payload = {
  54264. collider: {
  54265. position: this._scaledPosition.asArray(),
  54266. velocity: this._scaledVelocity.asArray(),
  54267. radius: collider._radius.asArray()
  54268. },
  54269. collisionId: collisionIndex,
  54270. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54271. maximumRetry: maximumRetry
  54272. };
  54273. var message = {
  54274. payload: payload,
  54275. taskType: WorkerTaskType.COLLIDE
  54276. };
  54277. this._worker.postMessage(message);
  54278. };
  54279. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54280. this._scene = scene;
  54281. this._scene.registerAfterRender(this._afterRender);
  54282. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54283. this._worker = new Worker(workerUrl);
  54284. this._worker.onmessage = this._onMessageFromWorker;
  54285. var message = {
  54286. payload: {},
  54287. taskType: WorkerTaskType.INIT
  54288. };
  54289. this._worker.postMessage(message);
  54290. };
  54291. CollisionCoordinatorWorker.prototype.destroy = function () {
  54292. this._scene.unregisterAfterRender(this._afterRender);
  54293. this._worker.terminate();
  54294. };
  54295. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54296. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54297. this.onMeshUpdated(mesh);
  54298. };
  54299. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54300. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54301. };
  54302. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54303. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54304. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54305. this.onGeometryUpdated(geometry);
  54306. };
  54307. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54308. this._toRemoveGeometryArray.push(geometry.id);
  54309. };
  54310. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54311. var submeshes = [];
  54312. if (mesh.subMeshes) {
  54313. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54314. var boundingInfo = sm.getBoundingInfo();
  54315. return {
  54316. position: idx,
  54317. verticesStart: sm.verticesStart,
  54318. verticesCount: sm.verticesCount,
  54319. indexStart: sm.indexStart,
  54320. indexCount: sm.indexCount,
  54321. hasMaterial: !!sm.getMaterial(),
  54322. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54323. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54324. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54325. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54326. };
  54327. });
  54328. }
  54329. var geometryId = null;
  54330. if (mesh instanceof BABYLON.Mesh) {
  54331. var geometry = mesh.geometry;
  54332. geometryId = geometry ? geometry.id : null;
  54333. }
  54334. else if (mesh instanceof BABYLON.InstancedMesh) {
  54335. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54336. geometryId = geometry ? geometry.id : null;
  54337. }
  54338. var boundingInfo = mesh.getBoundingInfo();
  54339. return {
  54340. uniqueId: mesh.uniqueId,
  54341. id: mesh.id,
  54342. name: mesh.name,
  54343. geometryId: geometryId,
  54344. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54345. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54346. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54347. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54348. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54349. subMeshes: submeshes,
  54350. checkCollisions: mesh.checkCollisions
  54351. };
  54352. };
  54353. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54354. return {
  54355. id: geometry.id,
  54356. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54357. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54358. indices: new Uint32Array(geometry.getIndices() || []),
  54359. };
  54360. };
  54361. return CollisionCoordinatorWorker;
  54362. }());
  54363. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54364. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54365. function CollisionCoordinatorLegacy() {
  54366. this._scaledPosition = BABYLON.Vector3.Zero();
  54367. this._scaledVelocity = BABYLON.Vector3.Zero();
  54368. this._finalPosition = BABYLON.Vector3.Zero();
  54369. }
  54370. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54371. position.divideToRef(collider._radius, this._scaledPosition);
  54372. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54373. collider.collidedMesh = null;
  54374. collider._retry = 0;
  54375. collider._initialVelocity = this._scaledVelocity;
  54376. collider._initialPosition = this._scaledPosition;
  54377. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54378. this._finalPosition.multiplyInPlace(collider._radius);
  54379. //run the callback
  54380. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54381. };
  54382. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54383. this._scene = scene;
  54384. };
  54385. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54386. //Legacy need no destruction method.
  54387. };
  54388. //No update in legacy mode
  54389. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54390. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54391. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54392. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54393. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54394. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54395. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54396. if (excludedMesh === void 0) { excludedMesh = null; }
  54397. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54398. if (collider._retry >= maximumRetry) {
  54399. finalPosition.copyFrom(position);
  54400. return;
  54401. }
  54402. // Check if this is a mesh else camera or -1
  54403. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54404. collider._initialize(position, velocity, closeDistance);
  54405. // Check all meshes
  54406. for (var index = 0; index < this._scene.meshes.length; index++) {
  54407. var mesh = this._scene.meshes[index];
  54408. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54409. mesh._checkCollision(collider);
  54410. }
  54411. }
  54412. if (!collider.collisionFound) {
  54413. position.addToRef(velocity, finalPosition);
  54414. return;
  54415. }
  54416. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54417. collider._getResponse(position, velocity);
  54418. }
  54419. if (velocity.length() <= closeDistance) {
  54420. finalPosition.copyFrom(position);
  54421. return;
  54422. }
  54423. collider._retry++;
  54424. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54425. };
  54426. return CollisionCoordinatorLegacy;
  54427. }());
  54428. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54429. })(BABYLON || (BABYLON = {}));
  54430. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54431. var BABYLON;
  54432. (function (BABYLON) {
  54433. /**
  54434. * A particle represents one of the element emitted by a particle system.
  54435. * This is mainly define by its coordinates, direction, velocity and age.
  54436. */
  54437. var Particle = /** @class */ (function () {
  54438. /**
  54439. * Creates a new instance Particle
  54440. * @param particleSystem the particle system the particle belongs to
  54441. */
  54442. function Particle(
  54443. /**
  54444. * particleSystem the particle system the particle belongs to.
  54445. */
  54446. particleSystem) {
  54447. this.particleSystem = particleSystem;
  54448. /**
  54449. * The world position of the particle in the scene.
  54450. */
  54451. this.position = BABYLON.Vector3.Zero();
  54452. /**
  54453. * The world direction of the particle in the scene.
  54454. */
  54455. this.direction = BABYLON.Vector3.Zero();
  54456. /**
  54457. * The color of the particle.
  54458. */
  54459. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54460. /**
  54461. * The color change of the particle per step.
  54462. */
  54463. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54464. /**
  54465. * Defines how long will the life of the particle be.
  54466. */
  54467. this.lifeTime = 1.0;
  54468. /**
  54469. * The current age of the particle.
  54470. */
  54471. this.age = 0;
  54472. /**
  54473. * The current size of the particle.
  54474. */
  54475. this.size = 0;
  54476. /**
  54477. * The current scale of the particle.
  54478. */
  54479. this.scale = new BABYLON.Vector2(1, 1);
  54480. /**
  54481. * The current angle of the particle.
  54482. */
  54483. this.angle = 0;
  54484. /**
  54485. * Defines how fast is the angle changing.
  54486. */
  54487. this.angularSpeed = 0;
  54488. /**
  54489. * Defines the cell index used by the particle to be rendered from a sprite.
  54490. */
  54491. this.cellIndex = 0;
  54492. /** @hidden */
  54493. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54494. /** @hidden */
  54495. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54496. /** @hidden */
  54497. this._currentSize1 = 0;
  54498. /** @hidden */
  54499. this._currentSize2 = 0;
  54500. /** @hidden */
  54501. this._currentAngularSpeed1 = 0;
  54502. /** @hidden */
  54503. this._currentAngularSpeed2 = 0;
  54504. /** @hidden */
  54505. this._currentVelocity1 = 0;
  54506. /** @hidden */
  54507. this._currentVelocity2 = 0;
  54508. if (!this.particleSystem.isAnimationSheetEnabled) {
  54509. return;
  54510. }
  54511. this.updateCellInfoFromSystem();
  54512. }
  54513. Particle.prototype.updateCellInfoFromSystem = function () {
  54514. this.cellIndex = this.particleSystem.startSpriteCellID;
  54515. };
  54516. /**
  54517. * Defines how the sprite cell index is updated for the particle
  54518. */
  54519. Particle.prototype.updateCellIndex = function () {
  54520. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54521. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54522. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54523. };
  54524. /**
  54525. * Copy the properties of particle to another one.
  54526. * @param other the particle to copy the information to.
  54527. */
  54528. Particle.prototype.copyTo = function (other) {
  54529. other.position.copyFrom(this.position);
  54530. if (this._initialDirection) {
  54531. if (other._initialDirection) {
  54532. other._initialDirection.copyFrom(this._initialDirection);
  54533. }
  54534. else {
  54535. other._initialDirection = this._initialDirection.clone();
  54536. }
  54537. }
  54538. else {
  54539. other._initialDirection = null;
  54540. }
  54541. other.direction.copyFrom(this.direction);
  54542. other.color.copyFrom(this.color);
  54543. other.colorStep.copyFrom(this.colorStep);
  54544. other.lifeTime = this.lifeTime;
  54545. other.age = this.age;
  54546. other.size = this.size;
  54547. other.scale.copyFrom(this.scale);
  54548. other.angle = this.angle;
  54549. other.angularSpeed = this.angularSpeed;
  54550. other.particleSystem = this.particleSystem;
  54551. other.cellIndex = this.cellIndex;
  54552. if (this._currentColorGradient) {
  54553. other._currentColorGradient = this._currentColorGradient;
  54554. other._currentColor1.copyFrom(this._currentColor1);
  54555. other._currentColor2.copyFrom(this._currentColor2);
  54556. }
  54557. if (this._currentSizeGradient) {
  54558. other._currentSizeGradient = this._currentSizeGradient;
  54559. other._currentSize1 = this._currentSize1;
  54560. other._currentSize2 = this._currentSize2;
  54561. }
  54562. if (this._currentAngularSpeedGradient) {
  54563. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54564. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54565. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54566. }
  54567. if (this._currentVelocityGradient) {
  54568. other._currentVelocityGradient = this._currentVelocityGradient;
  54569. other._currentVelocity1 = this._currentVelocity1;
  54570. other._currentVelocity2 = this._currentVelocity2;
  54571. }
  54572. if (this.particleSystem.isAnimationSheetEnabled) {
  54573. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54574. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54575. }
  54576. };
  54577. return Particle;
  54578. }());
  54579. BABYLON.Particle = Particle;
  54580. })(BABYLON || (BABYLON = {}));
  54581. //# sourceMappingURL=babylon.particle.js.map
  54582. var BABYLON;
  54583. (function (BABYLON) {
  54584. /**
  54585. * This represents a particle system in Babylon.
  54586. * 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.
  54587. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54588. * @example https://doc.babylonjs.com/babylon101/particles
  54589. */
  54590. var ParticleSystem = /** @class */ (function () {
  54591. /**
  54592. * Instantiates a particle system.
  54593. * 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.
  54594. * @param name The name of the particle system
  54595. * @param capacity The max number of particles alive at the same time
  54596. * @param scene The scene the particle system belongs to
  54597. * @param customEffect a custom effect used to change the way particles are rendered by default
  54598. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54599. * @param epsilon Offset used to render the particles
  54600. */
  54601. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54602. if (customEffect === void 0) { customEffect = null; }
  54603. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54604. if (epsilon === void 0) { epsilon = 0.01; }
  54605. var _this = this;
  54606. /**
  54607. * List of animations used by the particle system.
  54608. */
  54609. this.animations = [];
  54610. /**
  54611. * The rendering group used by the Particle system to chose when to render.
  54612. */
  54613. this.renderingGroupId = 0;
  54614. /**
  54615. * The emitter represents the Mesh or position we are attaching the particle system to.
  54616. */
  54617. this.emitter = null;
  54618. /**
  54619. * The maximum number of particles to emit per frame
  54620. */
  54621. this.emitRate = 10;
  54622. /**
  54623. * If you want to launch only a few particles at once, that can be done, as well.
  54624. */
  54625. this.manualEmitCount = -1;
  54626. /**
  54627. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54628. */
  54629. this.updateSpeed = 0.01;
  54630. /**
  54631. * The amount of time the particle system is running (depends of the overall update speed).
  54632. */
  54633. this.targetStopDuration = 0;
  54634. /**
  54635. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54636. */
  54637. this.disposeOnStop = false;
  54638. /**
  54639. * Minimum power of emitting particles.
  54640. */
  54641. this.minEmitPower = 1;
  54642. /**
  54643. * Maximum power of emitting particles.
  54644. */
  54645. this.maxEmitPower = 1;
  54646. /**
  54647. * Minimum life time of emitting particles.
  54648. */
  54649. this.minLifeTime = 1;
  54650. /**
  54651. * Maximum life time of emitting particles.
  54652. */
  54653. this.maxLifeTime = 1;
  54654. /**
  54655. * Minimum Size of emitting particles.
  54656. */
  54657. this.minSize = 1;
  54658. /**
  54659. * Maximum Size of emitting particles.
  54660. */
  54661. this.maxSize = 1;
  54662. /**
  54663. * Minimum scale of emitting particles on X axis.
  54664. */
  54665. this.minScaleX = 1;
  54666. /**
  54667. * Maximum scale of emitting particles on X axis.
  54668. */
  54669. this.maxScaleX = 1;
  54670. /**
  54671. * Minimum scale of emitting particles on Y axis.
  54672. */
  54673. this.minScaleY = 1;
  54674. /**
  54675. * Maximum scale of emitting particles on Y axis.
  54676. */
  54677. this.maxScaleY = 1;
  54678. /**
  54679. * Gets or sets the minimal initial rotation in radians.
  54680. */
  54681. this.minInitialRotation = 0;
  54682. /**
  54683. * Gets or sets the maximal initial rotation in radians.
  54684. */
  54685. this.maxInitialRotation = 0;
  54686. /**
  54687. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54688. */
  54689. this.minAngularSpeed = 0;
  54690. /**
  54691. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54692. */
  54693. this.maxAngularSpeed = 0;
  54694. /**
  54695. * The layer mask we are rendering the particles through.
  54696. */
  54697. this.layerMask = 0x0FFFFFFF;
  54698. /**
  54699. * This can help using your own shader to render the particle system.
  54700. * The according effect will be created
  54701. */
  54702. this.customShader = null;
  54703. /**
  54704. * By default particle system starts as soon as they are created. This prevents the
  54705. * automatic start to happen and let you decide when to start emitting particles.
  54706. */
  54707. this.preventAutoStart = false;
  54708. /**
  54709. * Callback triggered when the particle animation is ending.
  54710. */
  54711. this.onAnimationEnd = null;
  54712. /**
  54713. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54714. */
  54715. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54716. /**
  54717. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54718. * to override the particles.
  54719. */
  54720. this.forceDepthWrite = false;
  54721. /**
  54722. * You can use gravity if you want to give an orientation to your particles.
  54723. */
  54724. this.gravity = BABYLON.Vector3.Zero();
  54725. this._colorGradients = null;
  54726. this._sizeGradients = null;
  54727. this._lifeTimeGradients = null;
  54728. this._angularSpeedGradients = null;
  54729. this._velocityGradients = null;
  54730. /**
  54731. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54732. */
  54733. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54734. /**
  54735. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54736. */
  54737. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54738. /**
  54739. * Color the particle will have at the end of its lifetime
  54740. */
  54741. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54742. /**
  54743. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54744. */
  54745. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54746. /**
  54747. * 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)
  54748. */
  54749. this.spriteCellChangeSpeed = 1;
  54750. /**
  54751. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  54752. */
  54753. this.startSpriteCellID = 0;
  54754. /**
  54755. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  54756. */
  54757. this.endSpriteCellID = 0;
  54758. /**
  54759. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  54760. */
  54761. this.spriteCellWidth = 0;
  54762. /**
  54763. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  54764. */
  54765. this.spriteCellHeight = 0;
  54766. /** 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 */
  54767. this.preWarmCycles = 0;
  54768. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  54769. this.preWarmStepOffset = 1;
  54770. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  54771. this.translationPivot = new BABYLON.Vector2(0, 0);
  54772. /**
  54773. * An event triggered when the system is disposed
  54774. */
  54775. this.onDisposeObservable = new BABYLON.Observable();
  54776. /**
  54777. * Gets or sets the billboard mode to use when isBillboardBased = true.
  54778. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  54779. */
  54780. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54781. this._particles = new Array();
  54782. this._stockParticles = new Array();
  54783. this._newPartsExcess = 0;
  54784. this._vertexBuffers = {};
  54785. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54786. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54787. this._scaledDirection = BABYLON.Vector3.Zero();
  54788. this._scaledGravity = BABYLON.Vector3.Zero();
  54789. this._currentRenderId = -1;
  54790. this._useInstancing = false;
  54791. this._started = false;
  54792. this._stopped = false;
  54793. this._actualFrame = 0;
  54794. this._isBillboardBased = true;
  54795. // start of sub system methods
  54796. /**
  54797. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54798. * Its lifetime will start back at 0.
  54799. */
  54800. this.recycleParticle = function (particle) {
  54801. var lastParticle = _this._particles.pop();
  54802. if (lastParticle !== particle) {
  54803. lastParticle.copyTo(particle);
  54804. }
  54805. _this._stockParticles.push(lastParticle);
  54806. };
  54807. this._createParticle = function () {
  54808. var particle;
  54809. if (_this._stockParticles.length !== 0) {
  54810. particle = _this._stockParticles.pop();
  54811. particle.age = 0;
  54812. particle._currentColorGradient = null;
  54813. particle.cellIndex = _this.startSpriteCellID;
  54814. }
  54815. else {
  54816. particle = new BABYLON.Particle(_this);
  54817. }
  54818. return particle;
  54819. };
  54820. this._emitFromParticle = function (particle) {
  54821. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54822. return;
  54823. }
  54824. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54825. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54826. subSystem._rootParticleSystem = _this;
  54827. _this.activeSubSystems.push(subSystem);
  54828. subSystem.start();
  54829. };
  54830. this.id = name;
  54831. this.name = name;
  54832. this._capacity = capacity;
  54833. this._epsilon = epsilon;
  54834. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54835. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54836. this._customEffect = customEffect;
  54837. scene.particleSystems.push(this);
  54838. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  54839. this._createIndexBuffer();
  54840. this._createVertexBuffers();
  54841. // Default emitter type
  54842. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54843. this.updateFunction = function (particles) {
  54844. var _loop_1 = function () {
  54845. particle = particles[index];
  54846. particle.age += _this._scaledUpdateSpeed;
  54847. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  54848. _this._emitFromParticle(particle);
  54849. _this.recycleParticle(particle);
  54850. index--;
  54851. return "continue";
  54852. }
  54853. else {
  54854. var ratio = particle.age / particle.lifeTime;
  54855. // Color
  54856. if (_this._colorGradients && _this._colorGradients.length > 0) {
  54857. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  54858. if (currentGradient !== particle._currentColorGradient) {
  54859. particle._currentColor1.copyFrom(particle._currentColor2);
  54860. nextGradient.getColorToRef(particle._currentColor2);
  54861. particle._currentColorGradient = currentGradient;
  54862. }
  54863. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  54864. });
  54865. }
  54866. else {
  54867. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54868. particle.color.addInPlace(_this._scaledColorStep);
  54869. if (particle.color.a < 0) {
  54870. particle.color.a = 0;
  54871. }
  54872. }
  54873. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  54874. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  54875. if (currentGradient !== particle._currentAngularSpeedGradient) {
  54876. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  54877. particle._currentAngularSpeed2 = nextGradient.getFactor();
  54878. particle._currentAngularSpeedGradient = currentGradient;
  54879. }
  54880. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  54881. });
  54882. }
  54883. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54884. var directionScale_1 = _this._scaledUpdateSpeed;
  54885. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  54886. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  54887. if (currentGradient !== particle._currentVelocityGradient) {
  54888. particle._currentVelocity1 = particle._currentVelocity2;
  54889. particle._currentVelocity2 = nextGradient.getFactor();
  54890. particle._currentVelocityGradient = currentGradient;
  54891. }
  54892. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  54893. });
  54894. }
  54895. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  54896. particle.position.addInPlace(_this._scaledDirection);
  54897. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54898. particle.direction.addInPlace(_this._scaledGravity);
  54899. // Size
  54900. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  54901. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  54902. if (currentGradient !== particle._currentSizeGradient) {
  54903. particle._currentSize1 = particle._currentSize2;
  54904. particle._currentSize2 = nextGradient.getFactor();
  54905. particle._currentSizeGradient = currentGradient;
  54906. }
  54907. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  54908. });
  54909. }
  54910. if (_this._isAnimationSheetEnabled) {
  54911. particle.updateCellIndex();
  54912. }
  54913. }
  54914. };
  54915. var particle;
  54916. for (var index = 0; index < particles.length; index++) {
  54917. _loop_1();
  54918. }
  54919. };
  54920. }
  54921. /**
  54922. * Gets the current list of color gradients.
  54923. * You must use addColorGradient and removeColorGradient to udpate this list
  54924. * @returns the list of color gradients
  54925. */
  54926. ParticleSystem.prototype.getColorGradients = function () {
  54927. return this._colorGradients;
  54928. };
  54929. /**
  54930. * Gets the current list of size gradients.
  54931. * You must use addSizeGradient and removeSizeGradient to udpate this list
  54932. * @returns the list of size gradients
  54933. */
  54934. ParticleSystem.prototype.getSizeGradients = function () {
  54935. return this._sizeGradients;
  54936. };
  54937. /**
  54938. * Gets the current list of life time gradients.
  54939. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  54940. * @returns the list of life time gradients
  54941. */
  54942. ParticleSystem.prototype.getLifeTimeGradients = function () {
  54943. return this._lifeTimeGradients;
  54944. };
  54945. /**
  54946. * Gets the current list of angular speed gradients.
  54947. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  54948. * @returns the list of angular speed gradients
  54949. */
  54950. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  54951. return this._angularSpeedGradients;
  54952. };
  54953. /**
  54954. * Gets the current list of velocity gradients.
  54955. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  54956. * @returns the list of velocity gradients
  54957. */
  54958. ParticleSystem.prototype.getVelocityGradients = function () {
  54959. return this._velocityGradients;
  54960. };
  54961. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54962. /**
  54963. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54964. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54965. */
  54966. get: function () {
  54967. if (this.particleEmitterType.direction1) {
  54968. return this.particleEmitterType.direction1;
  54969. }
  54970. return BABYLON.Vector3.Zero();
  54971. },
  54972. set: function (value) {
  54973. if (this.particleEmitterType.direction1) {
  54974. this.particleEmitterType.direction1 = value;
  54975. }
  54976. },
  54977. enumerable: true,
  54978. configurable: true
  54979. });
  54980. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54981. /**
  54982. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54983. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54984. */
  54985. get: function () {
  54986. if (this.particleEmitterType.direction2) {
  54987. return this.particleEmitterType.direction2;
  54988. }
  54989. return BABYLON.Vector3.Zero();
  54990. },
  54991. set: function (value) {
  54992. if (this.particleEmitterType.direction2) {
  54993. this.particleEmitterType.direction2 = value;
  54994. }
  54995. },
  54996. enumerable: true,
  54997. configurable: true
  54998. });
  54999. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55000. /**
  55001. * 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.
  55002. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55003. */
  55004. get: function () {
  55005. if (this.particleEmitterType.minEmitBox) {
  55006. return this.particleEmitterType.minEmitBox;
  55007. }
  55008. return BABYLON.Vector3.Zero();
  55009. },
  55010. set: function (value) {
  55011. if (this.particleEmitterType.minEmitBox) {
  55012. this.particleEmitterType.minEmitBox = value;
  55013. }
  55014. },
  55015. enumerable: true,
  55016. configurable: true
  55017. });
  55018. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55019. /**
  55020. * 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.
  55021. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55022. */
  55023. get: function () {
  55024. if (this.particleEmitterType.maxEmitBox) {
  55025. return this.particleEmitterType.maxEmitBox;
  55026. }
  55027. return BABYLON.Vector3.Zero();
  55028. },
  55029. set: function (value) {
  55030. if (this.particleEmitterType.maxEmitBox) {
  55031. this.particleEmitterType.maxEmitBox = value;
  55032. }
  55033. },
  55034. enumerable: true,
  55035. configurable: true
  55036. });
  55037. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55038. /**
  55039. * Sets a callback that will be triggered when the system is disposed
  55040. */
  55041. set: function (callback) {
  55042. if (this._onDisposeObserver) {
  55043. this.onDisposeObservable.remove(this._onDisposeObserver);
  55044. }
  55045. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55046. },
  55047. enumerable: true,
  55048. configurable: true
  55049. });
  55050. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55051. /**
  55052. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55053. */
  55054. get: function () {
  55055. return this._isAnimationSheetEnabled;
  55056. },
  55057. enumerable: true,
  55058. configurable: true
  55059. });
  55060. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55061. /**
  55062. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55063. */
  55064. get: function () {
  55065. return this._isBillboardBased;
  55066. },
  55067. set: function (value) {
  55068. if (this._isBillboardBased === value) {
  55069. return;
  55070. }
  55071. this._isBillboardBased = value;
  55072. this._resetEffect();
  55073. },
  55074. enumerable: true,
  55075. configurable: true
  55076. });
  55077. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55078. //end of Sub-emitter
  55079. /**
  55080. * Gets the current list of active particles
  55081. */
  55082. get: function () {
  55083. return this._particles;
  55084. },
  55085. enumerable: true,
  55086. configurable: true
  55087. });
  55088. /**
  55089. * Returns the string "ParticleSystem"
  55090. * @returns a string containing the class name
  55091. */
  55092. ParticleSystem.prototype.getClassName = function () {
  55093. return "ParticleSystem";
  55094. };
  55095. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55096. var newGradient = new BABYLON.FactorGradient();
  55097. newGradient.gradient = gradient;
  55098. newGradient.factor1 = factor;
  55099. newGradient.factor2 = factor2;
  55100. factorGradients.push(newGradient);
  55101. factorGradients.sort(function (a, b) {
  55102. if (a.gradient < b.gradient) {
  55103. return -1;
  55104. }
  55105. else if (a.gradient > b.gradient) {
  55106. return 1;
  55107. }
  55108. return 0;
  55109. });
  55110. };
  55111. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55112. if (!factorGradients) {
  55113. return;
  55114. }
  55115. var index = 0;
  55116. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55117. var factorGradient = factorGradients_1[_i];
  55118. if (factorGradient.gradient === gradient) {
  55119. factorGradients.splice(index, 1);
  55120. break;
  55121. }
  55122. index++;
  55123. }
  55124. };
  55125. /**
  55126. * Adds a new life time gradient
  55127. * @param gradient defines the gradient to use (between 0 and 1)
  55128. * @param factor defines the life time factor to affect to the specified gradient
  55129. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55130. * @returns the current particle system
  55131. */
  55132. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55133. if (!this._lifeTimeGradients) {
  55134. this._lifeTimeGradients = [];
  55135. }
  55136. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55137. return this;
  55138. };
  55139. /**
  55140. * Remove a specific life time gradient
  55141. * @param gradient defines the gradient to remove
  55142. * @returns the current particle system
  55143. */
  55144. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55145. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55146. return this;
  55147. };
  55148. /**
  55149. * Adds a new size gradient
  55150. * @param gradient defines the gradient to use (between 0 and 1)
  55151. * @param factor defines the size factor to affect to the specified gradient
  55152. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55153. * @returns the current particle system
  55154. */
  55155. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55156. if (!this._sizeGradients) {
  55157. this._sizeGradients = [];
  55158. }
  55159. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55160. return this;
  55161. };
  55162. /**
  55163. * Remove a specific size gradient
  55164. * @param gradient defines the gradient to remove
  55165. * @returns the current particle system
  55166. */
  55167. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55168. this._removeFactorGradient(this._sizeGradients, gradient);
  55169. return this;
  55170. };
  55171. /**
  55172. * Adds a new angular speed gradient
  55173. * @param gradient defines the gradient to use (between 0 and 1)
  55174. * @param factor defines the size factor to affect to the specified gradient
  55175. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55176. * @returns the current particle system
  55177. */
  55178. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55179. if (!this._angularSpeedGradients) {
  55180. this._angularSpeedGradients = [];
  55181. }
  55182. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55183. return this;
  55184. };
  55185. /**
  55186. * Remove a specific angular speed gradient
  55187. * @param gradient defines the gradient to remove
  55188. * @returns the current particle system
  55189. */
  55190. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55191. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55192. return this;
  55193. };
  55194. /**
  55195. * Adds a new velocity gradient
  55196. * @param gradient defines the gradient to use (between 0 and 1)
  55197. * @param factor defines the size factor to affect to the specified gradient
  55198. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55199. * @returns the current particle system
  55200. */
  55201. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55202. if (!this._velocityGradients) {
  55203. this._velocityGradients = [];
  55204. }
  55205. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55206. return this;
  55207. };
  55208. /**
  55209. * Remove a specific velocity gradient
  55210. * @param gradient defines the gradient to remove
  55211. * @returns the current particle system
  55212. */
  55213. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55214. this._removeFactorGradient(this._velocityGradients, gradient);
  55215. return this;
  55216. };
  55217. /**
  55218. * Adds a new color gradient
  55219. * @param gradient defines the gradient to use (between 0 and 1)
  55220. * @param color defines the color to affect to the specified gradient
  55221. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55222. */
  55223. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55224. if (!this._colorGradients) {
  55225. this._colorGradients = [];
  55226. }
  55227. var colorGradient = new BABYLON.ColorGradient();
  55228. colorGradient.gradient = gradient;
  55229. colorGradient.color1 = color;
  55230. colorGradient.color2 = color2;
  55231. this._colorGradients.push(colorGradient);
  55232. this._colorGradients.sort(function (a, b) {
  55233. if (a.gradient < b.gradient) {
  55234. return -1;
  55235. }
  55236. else if (a.gradient > b.gradient) {
  55237. return 1;
  55238. }
  55239. return 0;
  55240. });
  55241. return this;
  55242. };
  55243. /**
  55244. * Remove a specific color gradient
  55245. * @param gradient defines the gradient to remove
  55246. */
  55247. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55248. if (!this._colorGradients) {
  55249. return this;
  55250. }
  55251. var index = 0;
  55252. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55253. var colorGradient = _a[_i];
  55254. if (colorGradient.gradient === gradient) {
  55255. this._colorGradients.splice(index, 1);
  55256. break;
  55257. }
  55258. index++;
  55259. }
  55260. return this;
  55261. };
  55262. ParticleSystem.prototype._resetEffect = function () {
  55263. if (this._vertexBuffer) {
  55264. this._vertexBuffer.dispose();
  55265. this._vertexBuffer = null;
  55266. }
  55267. if (this._spriteBuffer) {
  55268. this._spriteBuffer.dispose();
  55269. this._spriteBuffer = null;
  55270. }
  55271. this._createVertexBuffers();
  55272. };
  55273. ParticleSystem.prototype._createVertexBuffers = function () {
  55274. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55275. if (this._isAnimationSheetEnabled) {
  55276. this._vertexBufferSize += 1;
  55277. }
  55278. if (!this._isBillboardBased) {
  55279. this._vertexBufferSize += 3;
  55280. }
  55281. var engine = this._scene.getEngine();
  55282. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55283. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55284. var dataOffset = 0;
  55285. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55287. dataOffset += 3;
  55288. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55289. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55290. dataOffset += 4;
  55291. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55292. this._vertexBuffers["angle"] = options;
  55293. dataOffset += 1;
  55294. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55295. this._vertexBuffers["size"] = size;
  55296. dataOffset += 2;
  55297. if (this._isAnimationSheetEnabled) {
  55298. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55299. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55300. dataOffset += 1;
  55301. }
  55302. if (!this._isBillboardBased) {
  55303. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55304. this._vertexBuffers["direction"] = directionBuffer;
  55305. dataOffset += 3;
  55306. }
  55307. var offsets;
  55308. if (this._useInstancing) {
  55309. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55310. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55311. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55312. }
  55313. else {
  55314. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55315. dataOffset += 2;
  55316. }
  55317. this._vertexBuffers["offset"] = offsets;
  55318. };
  55319. ParticleSystem.prototype._createIndexBuffer = function () {
  55320. if (this._useInstancing) {
  55321. return;
  55322. }
  55323. var indices = [];
  55324. var index = 0;
  55325. for (var count = 0; count < this._capacity; count++) {
  55326. indices.push(index);
  55327. indices.push(index + 1);
  55328. indices.push(index + 2);
  55329. indices.push(index);
  55330. indices.push(index + 2);
  55331. indices.push(index + 3);
  55332. index += 4;
  55333. }
  55334. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55335. };
  55336. /**
  55337. * Gets the maximum number of particles active at the same time.
  55338. * @returns The max number of active particles.
  55339. */
  55340. ParticleSystem.prototype.getCapacity = function () {
  55341. return this._capacity;
  55342. };
  55343. /**
  55344. * Gets Wether there are still active particles in the system.
  55345. * @returns True if it is alive, otherwise false.
  55346. */
  55347. ParticleSystem.prototype.isAlive = function () {
  55348. return this._alive;
  55349. };
  55350. /**
  55351. * Gets Wether the system has been started.
  55352. * @returns True if it has been started, otherwise false.
  55353. */
  55354. ParticleSystem.prototype.isStarted = function () {
  55355. return this._started;
  55356. };
  55357. /**
  55358. * Starts the particle system and begins to emit
  55359. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55360. */
  55361. ParticleSystem.prototype.start = function (delay) {
  55362. var _this = this;
  55363. if (delay === void 0) { delay = 0; }
  55364. if (delay) {
  55365. setTimeout(function () {
  55366. _this.start(0);
  55367. }, delay);
  55368. return;
  55369. }
  55370. this._started = true;
  55371. this._stopped = false;
  55372. this._actualFrame = 0;
  55373. if (this.subEmitters && this.subEmitters.length != 0) {
  55374. this.activeSubSystems = new Array();
  55375. }
  55376. if (this.preWarmCycles) {
  55377. for (var index = 0; index < this.preWarmCycles; index++) {
  55378. this.animate(true);
  55379. }
  55380. }
  55381. };
  55382. /**
  55383. * Stops the particle system.
  55384. * @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.
  55385. */
  55386. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55387. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55388. this._stopped = true;
  55389. if (stopSubEmitters) {
  55390. this._stopSubEmitters();
  55391. }
  55392. };
  55393. // animation sheet
  55394. /**
  55395. * Remove all active particles
  55396. */
  55397. ParticleSystem.prototype.reset = function () {
  55398. this._stockParticles = [];
  55399. this._particles = [];
  55400. };
  55401. /**
  55402. * @hidden (for internal use only)
  55403. */
  55404. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55405. var offset = index * this._vertexBufferSize;
  55406. this._vertexData[offset++] = particle.position.x;
  55407. this._vertexData[offset++] = particle.position.y;
  55408. this._vertexData[offset++] = particle.position.z;
  55409. this._vertexData[offset++] = particle.color.r;
  55410. this._vertexData[offset++] = particle.color.g;
  55411. this._vertexData[offset++] = particle.color.b;
  55412. this._vertexData[offset++] = particle.color.a;
  55413. this._vertexData[offset++] = particle.angle;
  55414. this._vertexData[offset++] = particle.scale.x * particle.size;
  55415. this._vertexData[offset++] = particle.scale.y * particle.size;
  55416. if (this._isAnimationSheetEnabled) {
  55417. this._vertexData[offset++] = particle.cellIndex;
  55418. }
  55419. if (!this._isBillboardBased) {
  55420. if (particle._initialDirection) {
  55421. this._vertexData[offset++] = particle._initialDirection.x;
  55422. this._vertexData[offset++] = particle._initialDirection.y;
  55423. this._vertexData[offset++] = particle._initialDirection.z;
  55424. }
  55425. else {
  55426. this._vertexData[offset++] = particle.direction.x;
  55427. this._vertexData[offset++] = particle.direction.y;
  55428. this._vertexData[offset++] = particle.direction.z;
  55429. }
  55430. }
  55431. if (!this._useInstancing) {
  55432. if (this._isAnimationSheetEnabled) {
  55433. if (offsetX === 0)
  55434. offsetX = this._epsilon;
  55435. else if (offsetX === 1)
  55436. offsetX = 1 - this._epsilon;
  55437. if (offsetY === 0)
  55438. offsetY = this._epsilon;
  55439. else if (offsetY === 1)
  55440. offsetY = 1 - this._epsilon;
  55441. }
  55442. this._vertexData[offset++] = offsetX;
  55443. this._vertexData[offset++] = offsetY;
  55444. }
  55445. };
  55446. ParticleSystem.prototype._stopSubEmitters = function () {
  55447. if (!this.activeSubSystems) {
  55448. return;
  55449. }
  55450. this.activeSubSystems.forEach(function (subSystem) {
  55451. subSystem.stop(true);
  55452. });
  55453. this.activeSubSystems = new Array();
  55454. };
  55455. ParticleSystem.prototype._removeFromRoot = function () {
  55456. if (!this._rootParticleSystem) {
  55457. return;
  55458. }
  55459. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55460. if (index !== -1) {
  55461. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55462. }
  55463. };
  55464. // End of sub system methods
  55465. ParticleSystem.prototype._update = function (newParticles) {
  55466. // Update current
  55467. this._alive = this._particles.length > 0;
  55468. this.updateFunction(this._particles);
  55469. // Add new ones
  55470. var worldMatrix;
  55471. if (this.emitter.position) {
  55472. var emitterMesh = this.emitter;
  55473. worldMatrix = emitterMesh.getWorldMatrix();
  55474. }
  55475. else {
  55476. var emitterPosition = this.emitter;
  55477. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55478. }
  55479. var particle;
  55480. var _loop_2 = function () {
  55481. if (this_1._particles.length === this_1._capacity) {
  55482. return "break";
  55483. }
  55484. particle = this_1._createParticle();
  55485. this_1._particles.push(particle);
  55486. // Emitter
  55487. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55488. if (this_1.startPositionFunction) {
  55489. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55490. }
  55491. else {
  55492. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55493. }
  55494. if (this_1.startDirectionFunction) {
  55495. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55496. }
  55497. else {
  55498. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55499. }
  55500. if (emitPower === 0) {
  55501. if (!particle._initialDirection) {
  55502. particle._initialDirection = particle.direction.clone();
  55503. }
  55504. else {
  55505. particle._initialDirection.copyFrom(particle.direction);
  55506. }
  55507. }
  55508. else {
  55509. particle._initialDirection = null;
  55510. }
  55511. particle.direction.scaleInPlace(emitPower);
  55512. // Life time
  55513. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55514. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55515. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55516. var factorGradient1 = currentGradient;
  55517. var factorGradient2 = nextGradient;
  55518. var lifeTime1 = factorGradient1.getFactor();
  55519. var lifeTime2 = factorGradient2.getFactor();
  55520. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55521. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55522. });
  55523. }
  55524. else {
  55525. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55526. }
  55527. // Size
  55528. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55529. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55530. }
  55531. else {
  55532. particle._currentSizeGradient = this_1._sizeGradients[0];
  55533. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55534. particle.size = particle._currentSize1;
  55535. if (this_1._sizeGradients.length > 1) {
  55536. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55537. }
  55538. else {
  55539. particle._currentSize2 = particle._currentSize1;
  55540. }
  55541. }
  55542. // Size and scale
  55543. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55544. // Angle
  55545. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55546. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55547. }
  55548. else {
  55549. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55550. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55551. particle._currentAngularSpeed1 = particle.angularSpeed;
  55552. if (this_1._angularSpeedGradients.length > 1) {
  55553. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55554. }
  55555. else {
  55556. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55557. }
  55558. }
  55559. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55560. // Velocity
  55561. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55562. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55563. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55564. if (this_1._velocityGradients.length > 1) {
  55565. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55566. }
  55567. else {
  55568. particle._currentVelocity2 = particle._currentVelocity1;
  55569. }
  55570. }
  55571. // Color
  55572. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55573. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55574. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55575. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55576. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55577. }
  55578. else {
  55579. particle._currentColorGradient = this_1._colorGradients[0];
  55580. particle._currentColorGradient.getColorToRef(particle.color);
  55581. particle._currentColor1.copyFrom(particle.color);
  55582. if (this_1._colorGradients.length > 1) {
  55583. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55584. }
  55585. else {
  55586. particle._currentColor2.copyFrom(particle.color);
  55587. }
  55588. }
  55589. // Sheet
  55590. if (this_1._isAnimationSheetEnabled) {
  55591. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55592. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55593. }
  55594. };
  55595. var this_1 = this, step;
  55596. for (var index = 0; index < newParticles; index++) {
  55597. var state_1 = _loop_2();
  55598. if (state_1 === "break")
  55599. break;
  55600. }
  55601. };
  55602. /** @hidden */
  55603. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55604. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55605. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55606. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55607. if (isAnimationSheetEnabled) {
  55608. attributeNamesOrOptions.push("cellIndex");
  55609. }
  55610. if (!isBillboardBased) {
  55611. attributeNamesOrOptions.push("direction");
  55612. }
  55613. return attributeNamesOrOptions;
  55614. };
  55615. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55616. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55617. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55618. if (isAnimationSheetEnabled) {
  55619. effectCreationOption.push("particlesInfos");
  55620. }
  55621. return effectCreationOption;
  55622. };
  55623. ParticleSystem.prototype._getEffect = function () {
  55624. if (this._customEffect) {
  55625. return this._customEffect;
  55626. }
  55627. ;
  55628. var defines = [];
  55629. if (this._scene.clipPlane) {
  55630. defines.push("#define CLIPPLANE");
  55631. }
  55632. if (this._isAnimationSheetEnabled) {
  55633. defines.push("#define ANIMATESHEET");
  55634. }
  55635. if (this._isBillboardBased) {
  55636. defines.push("#define BILLBOARD");
  55637. switch (this.billboardMode) {
  55638. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55639. defines.push("#define BILLBOARDY");
  55640. break;
  55641. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55642. default:
  55643. break;
  55644. }
  55645. }
  55646. // Effect
  55647. var join = defines.join("\n");
  55648. if (this._cachedDefines !== join) {
  55649. this._cachedDefines = join;
  55650. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55651. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55652. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55653. }
  55654. return this._effect;
  55655. };
  55656. /**
  55657. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55658. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55659. */
  55660. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55661. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55662. if (!this._started)
  55663. return;
  55664. if (!preWarmOnly) {
  55665. var effect = this._getEffect();
  55666. // Check
  55667. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55668. return;
  55669. if (this._currentRenderId === this._scene.getRenderId()) {
  55670. return;
  55671. }
  55672. this._currentRenderId = this._scene.getRenderId();
  55673. }
  55674. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55675. // determine the number of particles we need to create
  55676. var newParticles;
  55677. if (this.manualEmitCount > -1) {
  55678. newParticles = this.manualEmitCount;
  55679. this._newPartsExcess = 0;
  55680. this.manualEmitCount = 0;
  55681. }
  55682. else {
  55683. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55684. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55685. }
  55686. if (this._newPartsExcess > 1.0) {
  55687. newParticles += this._newPartsExcess >> 0;
  55688. this._newPartsExcess -= this._newPartsExcess >> 0;
  55689. }
  55690. this._alive = false;
  55691. if (!this._stopped) {
  55692. this._actualFrame += this._scaledUpdateSpeed;
  55693. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55694. this.stop();
  55695. }
  55696. else {
  55697. newParticles = 0;
  55698. }
  55699. this._update(newParticles);
  55700. // Stopped?
  55701. if (this._stopped) {
  55702. if (!this._alive) {
  55703. this._started = false;
  55704. if (this.onAnimationEnd) {
  55705. this.onAnimationEnd();
  55706. }
  55707. if (this.disposeOnStop) {
  55708. this._scene._toBeDisposed.push(this);
  55709. }
  55710. }
  55711. }
  55712. if (!preWarmOnly) {
  55713. // Update VBO
  55714. var offset = 0;
  55715. for (var index = 0; index < this._particles.length; index++) {
  55716. var particle = this._particles[index];
  55717. this._appendParticleVertices(offset, particle);
  55718. offset += this._useInstancing ? 1 : 4;
  55719. }
  55720. if (this._vertexBuffer) {
  55721. this._vertexBuffer.update(this._vertexData);
  55722. }
  55723. }
  55724. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55725. this.stop();
  55726. }
  55727. };
  55728. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55729. this._appendParticleVertex(offset++, particle, 0, 0);
  55730. if (!this._useInstancing) {
  55731. this._appendParticleVertex(offset++, particle, 1, 0);
  55732. this._appendParticleVertex(offset++, particle, 1, 1);
  55733. this._appendParticleVertex(offset++, particle, 0, 1);
  55734. }
  55735. };
  55736. /**
  55737. * Rebuilds the particle system.
  55738. */
  55739. ParticleSystem.prototype.rebuild = function () {
  55740. this._createIndexBuffer();
  55741. if (this._vertexBuffer) {
  55742. this._vertexBuffer._rebuild();
  55743. }
  55744. };
  55745. /**
  55746. * Is this system ready to be used/rendered
  55747. * @return true if the system is ready
  55748. */
  55749. ParticleSystem.prototype.isReady = function () {
  55750. var effect = this._getEffect();
  55751. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55752. return false;
  55753. }
  55754. return true;
  55755. };
  55756. /**
  55757. * Renders the particle system in its current state.
  55758. * @returns the current number of particles
  55759. */
  55760. ParticleSystem.prototype.render = function () {
  55761. var effect = this._getEffect();
  55762. // Check
  55763. if (!this.isReady() || !this._particles.length) {
  55764. return 0;
  55765. }
  55766. var engine = this._scene.getEngine();
  55767. // Render
  55768. engine.enableEffect(effect);
  55769. engine.setState(false);
  55770. var viewMatrix = this._scene.getViewMatrix();
  55771. effect.setTexture("diffuseSampler", this.particleTexture);
  55772. effect.setMatrix("view", viewMatrix);
  55773. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55774. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55775. var baseSize = this.particleTexture.getBaseSize();
  55776. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55777. }
  55778. effect.setVector2("translationPivot", this.translationPivot);
  55779. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55780. if (this._isBillboardBased) {
  55781. var camera = this._scene.activeCamera;
  55782. effect.setVector3("eyePosition", camera.globalPosition);
  55783. }
  55784. if (this._scene.clipPlane) {
  55785. var clipPlane = this._scene.clipPlane;
  55786. var invView = viewMatrix.clone();
  55787. invView.invert();
  55788. effect.setMatrix("invView", invView);
  55789. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55790. }
  55791. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55792. // Draw order
  55793. switch (this.blendMode) {
  55794. case ParticleSystem.BLENDMODE_ADD:
  55795. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55796. break;
  55797. case ParticleSystem.BLENDMODE_ONEONE:
  55798. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55799. break;
  55800. case ParticleSystem.BLENDMODE_STANDARD:
  55801. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55802. break;
  55803. }
  55804. if (this.forceDepthWrite) {
  55805. engine.setDepthWrite(true);
  55806. }
  55807. if (this._useInstancing) {
  55808. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55809. engine.unbindInstanceAttributes();
  55810. }
  55811. else {
  55812. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55813. }
  55814. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55815. return this._particles.length;
  55816. };
  55817. /**
  55818. * Disposes the particle system and free the associated resources
  55819. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55820. */
  55821. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55822. if (disposeTexture === void 0) { disposeTexture = true; }
  55823. if (this._vertexBuffer) {
  55824. this._vertexBuffer.dispose();
  55825. this._vertexBuffer = null;
  55826. }
  55827. if (this._spriteBuffer) {
  55828. this._spriteBuffer.dispose();
  55829. this._spriteBuffer = null;
  55830. }
  55831. if (this._indexBuffer) {
  55832. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55833. this._indexBuffer = null;
  55834. }
  55835. if (disposeTexture && this.particleTexture) {
  55836. this.particleTexture.dispose();
  55837. this.particleTexture = null;
  55838. }
  55839. this._removeFromRoot();
  55840. // Remove from scene
  55841. var index = this._scene.particleSystems.indexOf(this);
  55842. if (index > -1) {
  55843. this._scene.particleSystems.splice(index, 1);
  55844. }
  55845. // Callback
  55846. this.onDisposeObservable.notifyObservers(this);
  55847. this.onDisposeObservable.clear();
  55848. };
  55849. /**
  55850. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55851. * @param radius The radius of the sphere to emit from
  55852. * @returns the emitter
  55853. */
  55854. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55855. if (radius === void 0) { radius = 1; }
  55856. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55857. this.particleEmitterType = particleEmitter;
  55858. return particleEmitter;
  55859. };
  55860. /**
  55861. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55862. * @param radius The radius of the sphere to emit from
  55863. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55864. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55865. * @returns the emitter
  55866. */
  55867. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55868. if (radius === void 0) { radius = 1; }
  55869. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55870. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55871. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55872. this.particleEmitterType = particleEmitter;
  55873. return particleEmitter;
  55874. };
  55875. /**
  55876. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55877. * @param radius The radius of the cone to emit from
  55878. * @param angle The base angle of the cone
  55879. * @returns the emitter
  55880. */
  55881. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55882. if (radius === void 0) { radius = 1; }
  55883. if (angle === void 0) { angle = Math.PI / 4; }
  55884. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55885. this.particleEmitterType = particleEmitter;
  55886. return particleEmitter;
  55887. };
  55888. // 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.
  55889. /**
  55890. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55891. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55892. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55893. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55894. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55895. * @returns the emitter
  55896. */
  55897. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55898. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55899. this.particleEmitterType = particleEmitter;
  55900. this.direction1 = direction1;
  55901. this.direction2 = direction2;
  55902. this.minEmitBox = minEmitBox;
  55903. this.maxEmitBox = maxEmitBox;
  55904. return particleEmitter;
  55905. };
  55906. // Clone
  55907. /**
  55908. * Clones the particle system.
  55909. * @param name The name of the cloned object
  55910. * @param newEmitter The new emitter to use
  55911. * @returns the cloned particle system
  55912. */
  55913. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55914. var custom = null;
  55915. var program = null;
  55916. if (this.customShader != null) {
  55917. program = this.customShader;
  55918. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55919. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55920. }
  55921. else if (this._customEffect) {
  55922. custom = this._customEffect;
  55923. }
  55924. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55925. result.customShader = program;
  55926. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55927. if (newEmitter === undefined) {
  55928. newEmitter = this.emitter;
  55929. }
  55930. result.emitter = newEmitter;
  55931. if (this.particleTexture) {
  55932. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55933. }
  55934. if (!this.preventAutoStart) {
  55935. result.start();
  55936. }
  55937. return result;
  55938. };
  55939. /**
  55940. * Serializes the particle system to a JSON object.
  55941. * @returns the JSON object
  55942. */
  55943. ParticleSystem.prototype.serialize = function () {
  55944. var serializationObject = {};
  55945. ParticleSystem._Serialize(serializationObject, this);
  55946. serializationObject.textureMask = this.textureMask.asArray();
  55947. serializationObject.customShader = this.customShader;
  55948. serializationObject.preventAutoStart = this.preventAutoStart;
  55949. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55950. return serializationObject;
  55951. };
  55952. /** @hidden */
  55953. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55954. serializationObject.name = particleSystem.name;
  55955. serializationObject.id = particleSystem.id;
  55956. serializationObject.capacity = particleSystem.getCapacity();
  55957. // Emitter
  55958. if (particleSystem.emitter.position) {
  55959. var emitterMesh = particleSystem.emitter;
  55960. serializationObject.emitterId = emitterMesh.id;
  55961. }
  55962. else {
  55963. var emitterPosition = particleSystem.emitter;
  55964. serializationObject.emitter = emitterPosition.asArray();
  55965. }
  55966. // Emitter
  55967. if (particleSystem.particleEmitterType) {
  55968. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  55969. }
  55970. if (particleSystem.particleTexture) {
  55971. serializationObject.textureName = particleSystem.particleTexture.name;
  55972. }
  55973. // Animations
  55974. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  55975. // Particle system
  55976. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  55977. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  55978. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  55979. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  55980. serializationObject.minSize = particleSystem.minSize;
  55981. serializationObject.maxSize = particleSystem.maxSize;
  55982. serializationObject.minScaleX = particleSystem.minScaleX;
  55983. serializationObject.maxScaleX = particleSystem.maxScaleX;
  55984. serializationObject.minScaleY = particleSystem.minScaleY;
  55985. serializationObject.maxScaleY = particleSystem.maxScaleY;
  55986. serializationObject.minEmitPower = particleSystem.minEmitPower;
  55987. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  55988. serializationObject.minLifeTime = particleSystem.minLifeTime;
  55989. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  55990. serializationObject.emitRate = particleSystem.emitRate;
  55991. serializationObject.gravity = particleSystem.gravity.asArray();
  55992. serializationObject.color1 = particleSystem.color1.asArray();
  55993. serializationObject.color2 = particleSystem.color2.asArray();
  55994. serializationObject.colorDead = particleSystem.colorDead.asArray();
  55995. serializationObject.updateSpeed = particleSystem.updateSpeed;
  55996. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  55997. serializationObject.blendMode = particleSystem.blendMode;
  55998. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  55999. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56000. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56001. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56002. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56003. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56004. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56005. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56006. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56007. var colorGradients = particleSystem.getColorGradients();
  56008. if (colorGradients) {
  56009. serializationObject.colorGradients = [];
  56010. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56011. var colorGradient = colorGradients_1[_i];
  56012. var serializedGradient = {
  56013. gradient: colorGradient.gradient,
  56014. color1: colorGradient.color1.asArray()
  56015. };
  56016. if (colorGradient.color2) {
  56017. serializedGradient.color2 = colorGradient.color2.asArray();
  56018. }
  56019. serializationObject.colorGradients.push(serializedGradient);
  56020. }
  56021. }
  56022. var sizeGradients = particleSystem.getSizeGradients();
  56023. if (sizeGradients) {
  56024. serializationObject.sizeGradients = [];
  56025. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56026. var sizeGradient = sizeGradients_1[_a];
  56027. var serializedGradient = {
  56028. gradient: sizeGradient.gradient,
  56029. factor1: sizeGradient.factor1
  56030. };
  56031. if (sizeGradient.factor2 !== undefined) {
  56032. serializedGradient.factor2 = sizeGradient.factor2;
  56033. }
  56034. serializationObject.sizeGradients.push(serializedGradient);
  56035. }
  56036. }
  56037. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56038. if (angularSpeedGradients) {
  56039. serializationObject.angularSpeedGradients = [];
  56040. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56041. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56042. var serializedGradient = {
  56043. gradient: angularSpeedGradient.gradient,
  56044. factor1: angularSpeedGradient.factor1
  56045. };
  56046. if (angularSpeedGradient.factor2 !== undefined) {
  56047. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56048. }
  56049. serializationObject.angularSpeedGradients.push(serializedGradient);
  56050. }
  56051. }
  56052. var velocityGradients = particleSystem.getVelocityGradients();
  56053. if (velocityGradients) {
  56054. serializationObject.velocityGradients = [];
  56055. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56056. var velocityGradient = velocityGradients_1[_c];
  56057. var serializedGradient = {
  56058. gradient: velocityGradient.gradient,
  56059. factor1: velocityGradient.factor1
  56060. };
  56061. if (velocityGradient.factor2 !== undefined) {
  56062. serializedGradient.factor2 = velocityGradient.factor2;
  56063. }
  56064. serializationObject.velocityGradients.push(serializedGradient);
  56065. }
  56066. }
  56067. };
  56068. /** @hidden */
  56069. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56070. // Texture
  56071. if (parsedParticleSystem.textureName) {
  56072. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56073. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56074. }
  56075. // Emitter
  56076. if (parsedParticleSystem.emitterId === undefined) {
  56077. particleSystem.emitter = BABYLON.Vector3.Zero();
  56078. }
  56079. else if (parsedParticleSystem.emitterId) {
  56080. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56081. }
  56082. else {
  56083. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56084. }
  56085. // Misc.
  56086. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56087. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56088. }
  56089. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56090. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56091. }
  56092. // Animations
  56093. if (parsedParticleSystem.animations) {
  56094. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56095. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56096. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56097. }
  56098. }
  56099. if (parsedParticleSystem.autoAnimate) {
  56100. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56101. }
  56102. // Particle system
  56103. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56104. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56105. particleSystem.minSize = parsedParticleSystem.minSize;
  56106. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56107. if (parsedParticleSystem.minScaleX) {
  56108. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56109. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56110. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56111. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56112. }
  56113. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56114. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56115. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56116. }
  56117. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56118. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56119. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56120. }
  56121. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56122. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56123. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56124. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56125. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56126. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56127. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56128. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56129. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56130. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56131. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56132. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56133. if (parsedParticleSystem.colorGradients) {
  56134. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56135. var colorGradient = _a[_i];
  56136. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56137. }
  56138. }
  56139. if (parsedParticleSystem.sizeGradients) {
  56140. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56141. var sizeGradient = _c[_b];
  56142. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56143. }
  56144. }
  56145. if (parsedParticleSystem.angularSpeedGradients) {
  56146. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56147. var angularSpeedGradient = _e[_d];
  56148. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56149. }
  56150. }
  56151. if (parsedParticleSystem.velocityGradients) {
  56152. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56153. var velocityGradient = _g[_f];
  56154. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56155. }
  56156. }
  56157. // Emitter
  56158. var emitterType;
  56159. if (parsedParticleSystem.particleEmitterType) {
  56160. switch (parsedParticleSystem.particleEmitterType.type) {
  56161. case "SphereParticleEmitter":
  56162. emitterType = new BABYLON.SphereParticleEmitter();
  56163. break;
  56164. case "SphereDirectedParticleEmitter":
  56165. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56166. break;
  56167. case "ConeEmitter":
  56168. case "ConeParticleEmitter":
  56169. emitterType = new BABYLON.ConeParticleEmitter();
  56170. break;
  56171. case "BoxEmitter":
  56172. case "BoxParticleEmitter":
  56173. default:
  56174. emitterType = new BABYLON.BoxParticleEmitter();
  56175. break;
  56176. }
  56177. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56178. }
  56179. else {
  56180. emitterType = new BABYLON.BoxParticleEmitter();
  56181. emitterType.parse(parsedParticleSystem);
  56182. }
  56183. particleSystem.particleEmitterType = emitterType;
  56184. // Animation sheet
  56185. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56186. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56187. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56188. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56189. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56190. };
  56191. /**
  56192. * Parses a JSON object to create a particle system.
  56193. * @param parsedParticleSystem The JSON object to parse
  56194. * @param scene The scene to create the particle system in
  56195. * @param rootUrl The root url to use to load external dependencies like texture
  56196. * @returns the Parsed particle system
  56197. */
  56198. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56199. var name = parsedParticleSystem.name;
  56200. var custom = null;
  56201. var program = null;
  56202. if (parsedParticleSystem.customShader) {
  56203. program = parsedParticleSystem.customShader;
  56204. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56205. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56206. }
  56207. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56208. particleSystem.customShader = program;
  56209. if (parsedParticleSystem.id) {
  56210. particleSystem.id = parsedParticleSystem.id;
  56211. }
  56212. // Auto start
  56213. if (parsedParticleSystem.preventAutoStart) {
  56214. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56215. }
  56216. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56217. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56218. if (!particleSystem.preventAutoStart) {
  56219. particleSystem.start();
  56220. }
  56221. return particleSystem;
  56222. };
  56223. /**
  56224. * Source color is added to the destination color without alpha affecting the result.
  56225. */
  56226. ParticleSystem.BLENDMODE_ONEONE = 0;
  56227. /**
  56228. * Blend current color and particle color using particle’s alpha.
  56229. */
  56230. ParticleSystem.BLENDMODE_STANDARD = 1;
  56231. /**
  56232. * Add current color and particle color multiplied by particle’s alpha.
  56233. */
  56234. ParticleSystem.BLENDMODE_ADD = 2;
  56235. return ParticleSystem;
  56236. }());
  56237. BABYLON.ParticleSystem = ParticleSystem;
  56238. })(BABYLON || (BABYLON = {}));
  56239. //# sourceMappingURL=babylon.particleSystem.js.map
  56240. var BABYLON;
  56241. (function (BABYLON) {
  56242. /**
  56243. * Particle emitter emitting particles from the inside of a box.
  56244. * It emits the particles randomly between 2 given directions.
  56245. */
  56246. var BoxParticleEmitter = /** @class */ (function () {
  56247. /**
  56248. * Creates a new instance BoxParticleEmitter
  56249. */
  56250. function BoxParticleEmitter() {
  56251. /**
  56252. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56253. */
  56254. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56255. /**
  56256. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56257. */
  56258. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56259. /**
  56260. * 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.
  56261. */
  56262. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56263. /**
  56264. * 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.
  56265. */
  56266. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56267. }
  56268. /**
  56269. * Called by the particle System when the direction is computed for the created particle.
  56270. * @param worldMatrix is the world matrix of the particle system
  56271. * @param directionToUpdate is the direction vector to update with the result
  56272. * @param particle is the particle we are computed the direction for
  56273. */
  56274. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56275. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56276. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56277. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56278. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56279. };
  56280. /**
  56281. * Called by the particle System when the position is computed for the created particle.
  56282. * @param worldMatrix is the world matrix of the particle system
  56283. * @param positionToUpdate is the position vector to update with the result
  56284. * @param particle is the particle we are computed the position for
  56285. */
  56286. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56287. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56288. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56289. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56291. };
  56292. /**
  56293. * Clones the current emitter and returns a copy of it
  56294. * @returns the new emitter
  56295. */
  56296. BoxParticleEmitter.prototype.clone = function () {
  56297. var newOne = new BoxParticleEmitter();
  56298. BABYLON.Tools.DeepCopy(this, newOne);
  56299. return newOne;
  56300. };
  56301. /**
  56302. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56303. * @param effect defines the update shader
  56304. */
  56305. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56306. effect.setVector3("direction1", this.direction1);
  56307. effect.setVector3("direction2", this.direction2);
  56308. effect.setVector3("minEmitBox", this.minEmitBox);
  56309. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56310. };
  56311. /**
  56312. * Returns a string to use to update the GPU particles update shader
  56313. * @returns a string containng the defines string
  56314. */
  56315. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56316. return "#define BOXEMITTER";
  56317. };
  56318. /**
  56319. * Returns the string "BoxParticleEmitter"
  56320. * @returns a string containing the class name
  56321. */
  56322. BoxParticleEmitter.prototype.getClassName = function () {
  56323. return "BoxParticleEmitter";
  56324. };
  56325. /**
  56326. * Serializes the particle system to a JSON object.
  56327. * @returns the JSON object
  56328. */
  56329. BoxParticleEmitter.prototype.serialize = function () {
  56330. var serializationObject = {};
  56331. serializationObject.type = this.getClassName();
  56332. serializationObject.direction1 = this.direction1.asArray();
  56333. serializationObject.direction2 = this.direction2.asArray();
  56334. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56335. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56336. return serializationObject;
  56337. };
  56338. /**
  56339. * Parse properties from a JSON object
  56340. * @param serializationObject defines the JSON object
  56341. */
  56342. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56343. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56344. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56345. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56346. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56347. };
  56348. return BoxParticleEmitter;
  56349. }());
  56350. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56351. })(BABYLON || (BABYLON = {}));
  56352. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56353. var BABYLON;
  56354. (function (BABYLON) {
  56355. /**
  56356. * Particle emitter emitting particles from the inside of a cone.
  56357. * It emits the particles alongside the cone volume from the base to the particle.
  56358. * The emission direction might be randomized.
  56359. */
  56360. var ConeParticleEmitter = /** @class */ (function () {
  56361. /**
  56362. * Creates a new instance ConeParticleEmitter
  56363. * @param radius the radius of the emission cone (1 by default)
  56364. * @param angles the cone base angle (PI by default)
  56365. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56366. */
  56367. function ConeParticleEmitter(radius, angle,
  56368. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56369. directionRandomizer) {
  56370. if (radius === void 0) { radius = 1; }
  56371. if (angle === void 0) { angle = Math.PI; }
  56372. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56373. this.directionRandomizer = directionRandomizer;
  56374. /**
  56375. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56376. */
  56377. this.radiusRange = 1;
  56378. /**
  56379. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56380. */
  56381. this.heightRange = 1;
  56382. this.angle = angle;
  56383. this.radius = radius;
  56384. }
  56385. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56386. /**
  56387. * Gets or sets the radius of the emission cone
  56388. */
  56389. get: function () {
  56390. return this._radius;
  56391. },
  56392. set: function (value) {
  56393. this._radius = value;
  56394. this._buildHeight();
  56395. },
  56396. enumerable: true,
  56397. configurable: true
  56398. });
  56399. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56400. /**
  56401. * Gets or sets the angle of the emission cone
  56402. */
  56403. get: function () {
  56404. return this._angle;
  56405. },
  56406. set: function (value) {
  56407. this._angle = value;
  56408. this._buildHeight();
  56409. },
  56410. enumerable: true,
  56411. configurable: true
  56412. });
  56413. ConeParticleEmitter.prototype._buildHeight = function () {
  56414. if (this._angle !== 0) {
  56415. this._height = this._radius / Math.tan(this._angle / 2);
  56416. }
  56417. else {
  56418. this._height = 1;
  56419. }
  56420. };
  56421. /**
  56422. * Called by the particle System when the direction is computed for the created particle.
  56423. * @param worldMatrix is the world matrix of the particle system
  56424. * @param directionToUpdate is the direction vector to update with the result
  56425. * @param particle is the particle we are computed the direction for
  56426. */
  56427. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56428. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56429. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56430. }
  56431. else {
  56432. // measure the direction Vector from the emitter to the particle.
  56433. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56434. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56435. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56436. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56437. direction.x += randX;
  56438. direction.y += randY;
  56439. direction.z += randZ;
  56440. direction.normalize();
  56441. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56442. }
  56443. };
  56444. /**
  56445. * Called by the particle System when the position is computed for the created particle.
  56446. * @param worldMatrix is the world matrix of the particle system
  56447. * @param positionToUpdate is the position vector to update with the result
  56448. * @param particle is the particle we are computed the position for
  56449. */
  56450. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56451. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56452. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56453. // Better distribution in a cone at normal angles.
  56454. h = 1 - h * h;
  56455. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56456. radius = radius * h;
  56457. var randX = radius * Math.sin(s);
  56458. var randZ = radius * Math.cos(s);
  56459. var randY = h * this._height;
  56460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56461. };
  56462. /**
  56463. * Clones the current emitter and returns a copy of it
  56464. * @returns the new emitter
  56465. */
  56466. ConeParticleEmitter.prototype.clone = function () {
  56467. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56468. BABYLON.Tools.DeepCopy(this, newOne);
  56469. return newOne;
  56470. };
  56471. /**
  56472. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56473. * @param effect defines the update shader
  56474. */
  56475. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56476. effect.setFloat2("radius", this._radius, this.radiusRange);
  56477. effect.setFloat("coneAngle", this._angle);
  56478. effect.setFloat2("height", this._height, this.heightRange);
  56479. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56480. };
  56481. /**
  56482. * Returns a string to use to update the GPU particles update shader
  56483. * @returns a string containng the defines string
  56484. */
  56485. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56486. return "#define CONEEMITTER";
  56487. };
  56488. /**
  56489. * Returns the string "ConeParticleEmitter"
  56490. * @returns a string containing the class name
  56491. */
  56492. ConeParticleEmitter.prototype.getClassName = function () {
  56493. return "ConeParticleEmitter";
  56494. };
  56495. /**
  56496. * Serializes the particle system to a JSON object.
  56497. * @returns the JSON object
  56498. */
  56499. ConeParticleEmitter.prototype.serialize = function () {
  56500. var serializationObject = {};
  56501. serializationObject.type = this.getClassName();
  56502. serializationObject.radius = this._radius;
  56503. serializationObject.angle = this._angle;
  56504. serializationObject.directionRandomizer = this.directionRandomizer;
  56505. return serializationObject;
  56506. };
  56507. /**
  56508. * Parse properties from a JSON object
  56509. * @param serializationObject defines the JSON object
  56510. */
  56511. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56512. this.radius = serializationObject.radius;
  56513. this.angle = serializationObject.angle;
  56514. this.directionRandomizer = serializationObject.directionRandomizer;
  56515. };
  56516. return ConeParticleEmitter;
  56517. }());
  56518. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56519. })(BABYLON || (BABYLON = {}));
  56520. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56521. var BABYLON;
  56522. (function (BABYLON) {
  56523. /**
  56524. * Particle emitter emitting particles from the inside of a sphere.
  56525. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56526. */
  56527. var SphereParticleEmitter = /** @class */ (function () {
  56528. /**
  56529. * Creates a new instance SphereParticleEmitter
  56530. * @param radius the radius of the emission sphere (1 by default)
  56531. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56532. */
  56533. function SphereParticleEmitter(
  56534. /**
  56535. * The radius of the emission sphere.
  56536. */
  56537. radius,
  56538. /**
  56539. * How much to randomize the particle direction [0-1].
  56540. */
  56541. directionRandomizer) {
  56542. if (radius === void 0) { radius = 1; }
  56543. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56544. this.radius = radius;
  56545. this.directionRandomizer = directionRandomizer;
  56546. /**
  56547. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56548. */
  56549. this.radiusRange = 1;
  56550. }
  56551. /**
  56552. * Called by the particle System when the direction is computed for the created particle.
  56553. * @param worldMatrix is the world matrix of the particle system
  56554. * @param directionToUpdate is the direction vector to update with the result
  56555. * @param particle is the particle we are computed the direction for
  56556. */
  56557. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56558. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56559. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56560. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56561. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56562. direction.x += randX;
  56563. direction.y += randY;
  56564. direction.z += randZ;
  56565. direction.normalize();
  56566. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56567. };
  56568. /**
  56569. * Called by the particle System when the position is computed for the created particle.
  56570. * @param worldMatrix is the world matrix of the particle system
  56571. * @param positionToUpdate is the position vector to update with the result
  56572. * @param particle is the particle we are computed the position for
  56573. */
  56574. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56575. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56576. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56577. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56578. var theta = Math.acos(2 * v - 1);
  56579. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56580. var randY = randRadius * Math.cos(theta);
  56581. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56583. };
  56584. /**
  56585. * Clones the current emitter and returns a copy of it
  56586. * @returns the new emitter
  56587. */
  56588. SphereParticleEmitter.prototype.clone = function () {
  56589. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56590. BABYLON.Tools.DeepCopy(this, newOne);
  56591. return newOne;
  56592. };
  56593. /**
  56594. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56595. * @param effect defines the update shader
  56596. */
  56597. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56598. effect.setFloat("radius", this.radius);
  56599. effect.setFloat("radiusRange", this.radiusRange);
  56600. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56601. };
  56602. /**
  56603. * Returns a string to use to update the GPU particles update shader
  56604. * @returns a string containng the defines string
  56605. */
  56606. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56607. return "#define SPHEREEMITTER";
  56608. };
  56609. /**
  56610. * Returns the string "SphereParticleEmitter"
  56611. * @returns a string containing the class name
  56612. */
  56613. SphereParticleEmitter.prototype.getClassName = function () {
  56614. return "SphereParticleEmitter";
  56615. };
  56616. /**
  56617. * Serializes the particle system to a JSON object.
  56618. * @returns the JSON object
  56619. */
  56620. SphereParticleEmitter.prototype.serialize = function () {
  56621. var serializationObject = {};
  56622. serializationObject.type = this.getClassName();
  56623. serializationObject.radius = this.radius;
  56624. serializationObject.radiusRange = this.radiusRange;
  56625. serializationObject.directionRandomizer = this.directionRandomizer;
  56626. return serializationObject;
  56627. };
  56628. /**
  56629. * Parse properties from a JSON object
  56630. * @param serializationObject defines the JSON object
  56631. */
  56632. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56633. this.radius = serializationObject.radius;
  56634. this.radiusRange = serializationObject.radiusRange;
  56635. this.directionRandomizer = serializationObject.directionRandomizer;
  56636. };
  56637. return SphereParticleEmitter;
  56638. }());
  56639. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56640. /**
  56641. * Particle emitter emitting particles from the inside of a sphere.
  56642. * It emits the particles randomly between two vectors.
  56643. */
  56644. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56645. __extends(SphereDirectedParticleEmitter, _super);
  56646. /**
  56647. * Creates a new instance SphereDirectedParticleEmitter
  56648. * @param radius the radius of the emission sphere (1 by default)
  56649. * @param direction1 the min limit of the emission direction (up vector by default)
  56650. * @param direction2 the max limit of the emission direction (up vector by default)
  56651. */
  56652. function SphereDirectedParticleEmitter(radius,
  56653. /**
  56654. * The min limit of the emission direction.
  56655. */
  56656. direction1,
  56657. /**
  56658. * The max limit of the emission direction.
  56659. */
  56660. direction2) {
  56661. if (radius === void 0) { radius = 1; }
  56662. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56663. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56664. var _this = _super.call(this, radius) || this;
  56665. _this.direction1 = direction1;
  56666. _this.direction2 = direction2;
  56667. return _this;
  56668. }
  56669. /**
  56670. * Called by the particle System when the direction is computed for the created particle.
  56671. * @param worldMatrix is the world matrix of the particle system
  56672. * @param directionToUpdate is the direction vector to update with the result
  56673. * @param particle is the particle we are computed the direction for
  56674. */
  56675. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56676. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56677. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56678. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56679. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56680. };
  56681. /**
  56682. * Clones the current emitter and returns a copy of it
  56683. * @returns the new emitter
  56684. */
  56685. SphereDirectedParticleEmitter.prototype.clone = function () {
  56686. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56687. BABYLON.Tools.DeepCopy(this, newOne);
  56688. return newOne;
  56689. };
  56690. /**
  56691. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56692. * @param effect defines the update shader
  56693. */
  56694. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56695. effect.setFloat("radius", this.radius);
  56696. effect.setFloat("radiusRange", this.radiusRange);
  56697. effect.setVector3("direction1", this.direction1);
  56698. effect.setVector3("direction2", this.direction2);
  56699. };
  56700. /**
  56701. * Returns a string to use to update the GPU particles update shader
  56702. * @returns a string containng the defines string
  56703. */
  56704. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56705. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56706. };
  56707. /**
  56708. * Returns the string "SphereDirectedParticleEmitter"
  56709. * @returns a string containing the class name
  56710. */
  56711. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56712. return "SphereDirectedParticleEmitter";
  56713. };
  56714. /**
  56715. * Serializes the particle system to a JSON object.
  56716. * @returns the JSON object
  56717. */
  56718. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56719. var serializationObject = _super.prototype.serialize.call(this);
  56720. serializationObject.direction1 = this.direction1.asArray();
  56721. serializationObject.direction2 = this.direction2.asArray();
  56722. return serializationObject;
  56723. };
  56724. /**
  56725. * Parse properties from a JSON object
  56726. * @param serializationObject defines the JSON object
  56727. */
  56728. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56729. _super.prototype.parse.call(this, serializationObject);
  56730. this.direction1.copyFrom(serializationObject.direction1);
  56731. this.direction2.copyFrom(serializationObject.direction2);
  56732. };
  56733. return SphereDirectedParticleEmitter;
  56734. }(SphereParticleEmitter));
  56735. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56736. })(BABYLON || (BABYLON = {}));
  56737. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56738. var BABYLON;
  56739. (function (BABYLON) {
  56740. // Adds the parsers to the scene parsers.
  56741. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  56742. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  56743. if (!individualParser) {
  56744. return;
  56745. }
  56746. // Particles Systems
  56747. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56748. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56749. var parsedParticleSystem = parsedData.particleSystems[index];
  56750. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  56751. }
  56752. }
  56753. });
  56754. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  56755. if (parsedParticleSystem.activeParticleCount) {
  56756. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56757. return ps;
  56758. }
  56759. else {
  56760. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56761. return ps;
  56762. }
  56763. });
  56764. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  56765. if (uniformsNames === void 0) { uniformsNames = []; }
  56766. if (samplers === void 0) { samplers = []; }
  56767. if (defines === void 0) { defines = ""; }
  56768. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  56769. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  56770. if (defines.indexOf(" BILLBOARD") === -1) {
  56771. defines += "\n#define BILLBOARD\n";
  56772. }
  56773. if (samplers.indexOf("diffuseSampler") === -1) {
  56774. samplers.push("diffuseSampler");
  56775. }
  56776. return this.createEffect({
  56777. vertex: "particles",
  56778. fragmentElement: fragmentName
  56779. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  56780. };
  56781. })(BABYLON || (BABYLON = {}));
  56782. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  56783. var BABYLON;
  56784. (function (BABYLON) {
  56785. var ShaderMaterial = /** @class */ (function (_super) {
  56786. __extends(ShaderMaterial, _super);
  56787. function ShaderMaterial(name, scene, shaderPath, options) {
  56788. var _this = _super.call(this, name, scene) || this;
  56789. _this._textures = {};
  56790. _this._textureArrays = {};
  56791. _this._floats = {};
  56792. _this._ints = {};
  56793. _this._floatsArrays = {};
  56794. _this._colors3 = {};
  56795. _this._colors3Arrays = {};
  56796. _this._colors4 = {};
  56797. _this._vectors2 = {};
  56798. _this._vectors3 = {};
  56799. _this._vectors4 = {};
  56800. _this._matrices = {};
  56801. _this._matrices3x3 = {};
  56802. _this._matrices2x2 = {};
  56803. _this._vectors2Arrays = {};
  56804. _this._vectors3Arrays = {};
  56805. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  56806. _this._shaderPath = shaderPath;
  56807. options.needAlphaBlending = options.needAlphaBlending || false;
  56808. options.needAlphaTesting = options.needAlphaTesting || false;
  56809. options.attributes = options.attributes || ["position", "normal", "uv"];
  56810. options.uniforms = options.uniforms || ["worldViewProjection"];
  56811. options.uniformBuffers = options.uniformBuffers || [];
  56812. options.samplers = options.samplers || [];
  56813. options.defines = options.defines || [];
  56814. _this._options = options;
  56815. return _this;
  56816. }
  56817. ShaderMaterial.prototype.getClassName = function () {
  56818. return "ShaderMaterial";
  56819. };
  56820. ShaderMaterial.prototype.needAlphaBlending = function () {
  56821. return this._options.needAlphaBlending;
  56822. };
  56823. ShaderMaterial.prototype.needAlphaTesting = function () {
  56824. return this._options.needAlphaTesting;
  56825. };
  56826. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  56827. if (this._options.uniforms.indexOf(uniformName) === -1) {
  56828. this._options.uniforms.push(uniformName);
  56829. }
  56830. };
  56831. ShaderMaterial.prototype.setTexture = function (name, texture) {
  56832. if (this._options.samplers.indexOf(name) === -1) {
  56833. this._options.samplers.push(name);
  56834. }
  56835. this._textures[name] = texture;
  56836. return this;
  56837. };
  56838. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  56839. if (this._options.samplers.indexOf(name) === -1) {
  56840. this._options.samplers.push(name);
  56841. }
  56842. this._checkUniform(name);
  56843. this._textureArrays[name] = textures;
  56844. return this;
  56845. };
  56846. ShaderMaterial.prototype.setFloat = function (name, value) {
  56847. this._checkUniform(name);
  56848. this._floats[name] = value;
  56849. return this;
  56850. };
  56851. ShaderMaterial.prototype.setInt = function (name, value) {
  56852. this._checkUniform(name);
  56853. this._ints[name] = value;
  56854. return this;
  56855. };
  56856. ShaderMaterial.prototype.setFloats = function (name, value) {
  56857. this._checkUniform(name);
  56858. this._floatsArrays[name] = value;
  56859. return this;
  56860. };
  56861. ShaderMaterial.prototype.setColor3 = function (name, value) {
  56862. this._checkUniform(name);
  56863. this._colors3[name] = value;
  56864. return this;
  56865. };
  56866. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  56867. this._checkUniform(name);
  56868. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  56869. color.toArray(arr, arr.length);
  56870. return arr;
  56871. }, []);
  56872. return this;
  56873. };
  56874. ShaderMaterial.prototype.setColor4 = function (name, value) {
  56875. this._checkUniform(name);
  56876. this._colors4[name] = value;
  56877. return this;
  56878. };
  56879. ShaderMaterial.prototype.setVector2 = function (name, value) {
  56880. this._checkUniform(name);
  56881. this._vectors2[name] = value;
  56882. return this;
  56883. };
  56884. ShaderMaterial.prototype.setVector3 = function (name, value) {
  56885. this._checkUniform(name);
  56886. this._vectors3[name] = value;
  56887. return this;
  56888. };
  56889. ShaderMaterial.prototype.setVector4 = function (name, value) {
  56890. this._checkUniform(name);
  56891. this._vectors4[name] = value;
  56892. return this;
  56893. };
  56894. ShaderMaterial.prototype.setMatrix = function (name, value) {
  56895. this._checkUniform(name);
  56896. this._matrices[name] = value;
  56897. return this;
  56898. };
  56899. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  56900. this._checkUniform(name);
  56901. this._matrices3x3[name] = value;
  56902. return this;
  56903. };
  56904. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  56905. this._checkUniform(name);
  56906. this._matrices2x2[name] = value;
  56907. return this;
  56908. };
  56909. ShaderMaterial.prototype.setArray2 = function (name, value) {
  56910. this._checkUniform(name);
  56911. this._vectors2Arrays[name] = value;
  56912. return this;
  56913. };
  56914. ShaderMaterial.prototype.setArray3 = function (name, value) {
  56915. this._checkUniform(name);
  56916. this._vectors3Arrays[name] = value;
  56917. return this;
  56918. };
  56919. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56920. if (!mesh) {
  56921. return true;
  56922. }
  56923. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  56924. return false;
  56925. }
  56926. return false;
  56927. };
  56928. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  56929. var scene = this.getScene();
  56930. var engine = scene.getEngine();
  56931. if (!this.checkReadyOnEveryCall) {
  56932. if (this._renderId === scene.getRenderId()) {
  56933. if (this._checkCache(scene, mesh, useInstances)) {
  56934. return true;
  56935. }
  56936. }
  56937. }
  56938. // Instances
  56939. var defines = [];
  56940. var attribs = [];
  56941. var fallbacks = new BABYLON.EffectFallbacks();
  56942. if (useInstances) {
  56943. defines.push("#define INSTANCES");
  56944. }
  56945. for (var index = 0; index < this._options.defines.length; index++) {
  56946. defines.push(this._options.defines[index]);
  56947. }
  56948. for (var index = 0; index < this._options.attributes.length; index++) {
  56949. attribs.push(this._options.attributes[index]);
  56950. }
  56951. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56952. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56953. defines.push("#define VERTEXCOLOR");
  56954. }
  56955. // Bones
  56956. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56959. if (mesh.numBoneInfluencers > 4) {
  56960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56962. }
  56963. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56964. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56965. fallbacks.addCPUSkinningFallback(0, mesh);
  56966. if (this._options.uniforms.indexOf("mBones") === -1) {
  56967. this._options.uniforms.push("mBones");
  56968. }
  56969. }
  56970. else {
  56971. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56972. }
  56973. // Textures
  56974. for (var name in this._textures) {
  56975. if (!this._textures[name].isReady()) {
  56976. return false;
  56977. }
  56978. }
  56979. // Alpha test
  56980. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  56981. defines.push("#define ALPHATEST");
  56982. }
  56983. var previousEffect = this._effect;
  56984. var join = defines.join("\n");
  56985. this._effect = engine.createEffect(this._shaderPath, {
  56986. attributes: attribs,
  56987. uniformsNames: this._options.uniforms,
  56988. uniformBuffersNames: this._options.uniformBuffers,
  56989. samplers: this._options.samplers,
  56990. defines: join,
  56991. fallbacks: fallbacks,
  56992. onCompiled: this.onCompiled,
  56993. onError: this.onError
  56994. }, engine);
  56995. if (!this._effect.isReady()) {
  56996. return false;
  56997. }
  56998. if (previousEffect !== this._effect) {
  56999. scene.resetCachedMaterial();
  57000. }
  57001. this._renderId = scene.getRenderId();
  57002. return true;
  57003. };
  57004. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57005. var scene = this.getScene();
  57006. if (!this._effect) {
  57007. return;
  57008. }
  57009. if (this._options.uniforms.indexOf("world") !== -1) {
  57010. this._effect.setMatrix("world", world);
  57011. }
  57012. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57013. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57014. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57015. }
  57016. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57017. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57018. }
  57019. };
  57020. ShaderMaterial.prototype.bind = function (world, mesh) {
  57021. // Std values
  57022. this.bindOnlyWorldMatrix(world);
  57023. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57024. if (this._options.uniforms.indexOf("view") !== -1) {
  57025. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57026. }
  57027. if (this._options.uniforms.indexOf("projection") !== -1) {
  57028. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57029. }
  57030. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57031. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57032. }
  57033. // Bones
  57034. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57035. var name;
  57036. // Texture
  57037. for (name in this._textures) {
  57038. this._effect.setTexture(name, this._textures[name]);
  57039. }
  57040. // Texture arrays
  57041. for (name in this._textureArrays) {
  57042. this._effect.setTextureArray(name, this._textureArrays[name]);
  57043. }
  57044. // Int
  57045. for (name in this._ints) {
  57046. this._effect.setInt(name, this._ints[name]);
  57047. }
  57048. // Float
  57049. for (name in this._floats) {
  57050. this._effect.setFloat(name, this._floats[name]);
  57051. }
  57052. // Floats
  57053. for (name in this._floatsArrays) {
  57054. this._effect.setArray(name, this._floatsArrays[name]);
  57055. }
  57056. // Color3
  57057. for (name in this._colors3) {
  57058. this._effect.setColor3(name, this._colors3[name]);
  57059. }
  57060. for (name in this._colors3Arrays) {
  57061. this._effect.setArray3(name, this._colors3Arrays[name]);
  57062. }
  57063. // Color4
  57064. for (name in this._colors4) {
  57065. var color = this._colors4[name];
  57066. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57067. }
  57068. // Vector2
  57069. for (name in this._vectors2) {
  57070. this._effect.setVector2(name, this._vectors2[name]);
  57071. }
  57072. // Vector3
  57073. for (name in this._vectors3) {
  57074. this._effect.setVector3(name, this._vectors3[name]);
  57075. }
  57076. // Vector4
  57077. for (name in this._vectors4) {
  57078. this._effect.setVector4(name, this._vectors4[name]);
  57079. }
  57080. // Matrix
  57081. for (name in this._matrices) {
  57082. this._effect.setMatrix(name, this._matrices[name]);
  57083. }
  57084. // Matrix 3x3
  57085. for (name in this._matrices3x3) {
  57086. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57087. }
  57088. // Matrix 2x2
  57089. for (name in this._matrices2x2) {
  57090. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57091. }
  57092. // Vector2Array
  57093. for (name in this._vectors2Arrays) {
  57094. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57095. }
  57096. // Vector3Array
  57097. for (name in this._vectors3Arrays) {
  57098. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57099. }
  57100. }
  57101. this._afterBind(mesh);
  57102. };
  57103. ShaderMaterial.prototype.getActiveTextures = function () {
  57104. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57105. for (var name in this._textures) {
  57106. activeTextures.push(this._textures[name]);
  57107. }
  57108. for (var name in this._textureArrays) {
  57109. var array = this._textureArrays[name];
  57110. for (var index = 0; index < array.length; index++) {
  57111. activeTextures.push(array[index]);
  57112. }
  57113. }
  57114. return activeTextures;
  57115. };
  57116. ShaderMaterial.prototype.hasTexture = function (texture) {
  57117. if (_super.prototype.hasTexture.call(this, texture)) {
  57118. return true;
  57119. }
  57120. for (var name in this._textures) {
  57121. if (this._textures[name] === texture) {
  57122. return true;
  57123. }
  57124. }
  57125. for (var name in this._textureArrays) {
  57126. var array = this._textureArrays[name];
  57127. for (var index = 0; index < array.length; index++) {
  57128. if (array[index] === texture) {
  57129. return true;
  57130. }
  57131. }
  57132. }
  57133. return false;
  57134. };
  57135. ShaderMaterial.prototype.clone = function (name) {
  57136. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57137. return newShaderMaterial;
  57138. };
  57139. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57140. if (forceDisposeTextures) {
  57141. var name;
  57142. for (name in this._textures) {
  57143. this._textures[name].dispose();
  57144. }
  57145. for (name in this._textureArrays) {
  57146. var array = this._textureArrays[name];
  57147. for (var index = 0; index < array.length; index++) {
  57148. array[index].dispose();
  57149. }
  57150. }
  57151. }
  57152. this._textures = {};
  57153. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57154. };
  57155. ShaderMaterial.prototype.serialize = function () {
  57156. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57157. serializationObject.customType = "BABYLON.ShaderMaterial";
  57158. serializationObject.options = this._options;
  57159. serializationObject.shaderPath = this._shaderPath;
  57160. var name;
  57161. // Texture
  57162. serializationObject.textures = {};
  57163. for (name in this._textures) {
  57164. serializationObject.textures[name] = this._textures[name].serialize();
  57165. }
  57166. // Texture arrays
  57167. serializationObject.textureArrays = {};
  57168. for (name in this._textureArrays) {
  57169. serializationObject.textureArrays[name] = [];
  57170. var array = this._textureArrays[name];
  57171. for (var index = 0; index < array.length; index++) {
  57172. serializationObject.textureArrays[name].push(array[index].serialize());
  57173. }
  57174. }
  57175. // Float
  57176. serializationObject.floats = {};
  57177. for (name in this._floats) {
  57178. serializationObject.floats[name] = this._floats[name];
  57179. }
  57180. // Float s
  57181. serializationObject.FloatArrays = {};
  57182. for (name in this._floatsArrays) {
  57183. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57184. }
  57185. // Color3
  57186. serializationObject.colors3 = {};
  57187. for (name in this._colors3) {
  57188. serializationObject.colors3[name] = this._colors3[name].asArray();
  57189. }
  57190. // Color3 array
  57191. serializationObject.colors3Arrays = {};
  57192. for (name in this._colors3Arrays) {
  57193. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57194. }
  57195. // Color4
  57196. serializationObject.colors4 = {};
  57197. for (name in this._colors4) {
  57198. serializationObject.colors4[name] = this._colors4[name].asArray();
  57199. }
  57200. // Vector2
  57201. serializationObject.vectors2 = {};
  57202. for (name in this._vectors2) {
  57203. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57204. }
  57205. // Vector3
  57206. serializationObject.vectors3 = {};
  57207. for (name in this._vectors3) {
  57208. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57209. }
  57210. // Vector4
  57211. serializationObject.vectors4 = {};
  57212. for (name in this._vectors4) {
  57213. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57214. }
  57215. // Matrix
  57216. serializationObject.matrices = {};
  57217. for (name in this._matrices) {
  57218. serializationObject.matrices[name] = this._matrices[name].asArray();
  57219. }
  57220. // Matrix 3x3
  57221. serializationObject.matrices3x3 = {};
  57222. for (name in this._matrices3x3) {
  57223. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57224. }
  57225. // Matrix 2x2
  57226. serializationObject.matrices2x2 = {};
  57227. for (name in this._matrices2x2) {
  57228. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57229. }
  57230. // Vector2Array
  57231. serializationObject.vectors2Arrays = {};
  57232. for (name in this._vectors2Arrays) {
  57233. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57234. }
  57235. // Vector3Array
  57236. serializationObject.vectors3Arrays = {};
  57237. for (name in this._vectors3Arrays) {
  57238. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57239. }
  57240. return serializationObject;
  57241. };
  57242. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57243. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57244. var name;
  57245. // Texture
  57246. for (name in source.textures) {
  57247. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57248. }
  57249. // Texture arrays
  57250. for (name in source.textureArrays) {
  57251. var array = source.textureArrays[name];
  57252. var textureArray = new Array();
  57253. for (var index = 0; index < array.length; index++) {
  57254. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57255. }
  57256. material.setTextureArray(name, textureArray);
  57257. }
  57258. // Float
  57259. for (name in source.floats) {
  57260. material.setFloat(name, source.floats[name]);
  57261. }
  57262. // Float s
  57263. for (name in source.floatsArrays) {
  57264. material.setFloats(name, source.floatsArrays[name]);
  57265. }
  57266. // Color3
  57267. for (name in source.colors3) {
  57268. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57269. }
  57270. // Color3 arrays
  57271. for (name in source.colors3Arrays) {
  57272. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57273. if (i % 3 === 0) {
  57274. arr.push([num]);
  57275. }
  57276. else {
  57277. arr[arr.length - 1].push(num);
  57278. }
  57279. return arr;
  57280. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57281. material.setColor3Array(name, colors);
  57282. }
  57283. // Color4
  57284. for (name in source.colors4) {
  57285. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57286. }
  57287. // Vector2
  57288. for (name in source.vectors2) {
  57289. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57290. }
  57291. // Vector3
  57292. for (name in source.vectors3) {
  57293. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57294. }
  57295. // Vector4
  57296. for (name in source.vectors4) {
  57297. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57298. }
  57299. // Matrix
  57300. for (name in source.matrices) {
  57301. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57302. }
  57303. // Matrix 3x3
  57304. for (name in source.matrices3x3) {
  57305. material.setMatrix3x3(name, source.matrices3x3[name]);
  57306. }
  57307. // Matrix 2x2
  57308. for (name in source.matrices2x2) {
  57309. material.setMatrix2x2(name, source.matrices2x2[name]);
  57310. }
  57311. // Vector2Array
  57312. for (name in source.vectors2Arrays) {
  57313. material.setArray2(name, source.vectors2Arrays[name]);
  57314. }
  57315. // Vector3Array
  57316. for (name in source.vectors3Arrays) {
  57317. material.setArray3(name, source.vectors3Arrays[name]);
  57318. }
  57319. return material;
  57320. };
  57321. return ShaderMaterial;
  57322. }(BABYLON.Material));
  57323. BABYLON.ShaderMaterial = ShaderMaterial;
  57324. })(BABYLON || (BABYLON = {}));
  57325. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57326. var BABYLON;
  57327. (function (BABYLON) {
  57328. var GroundMesh = /** @class */ (function (_super) {
  57329. __extends(GroundMesh, _super);
  57330. function GroundMesh(name, scene) {
  57331. var _this = _super.call(this, name, scene) || this;
  57332. _this.generateOctree = false;
  57333. return _this;
  57334. }
  57335. GroundMesh.prototype.getClassName = function () {
  57336. return "GroundMesh";
  57337. };
  57338. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57339. get: function () {
  57340. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57341. },
  57342. enumerable: true,
  57343. configurable: true
  57344. });
  57345. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57346. get: function () {
  57347. return this._subdivisionsX;
  57348. },
  57349. enumerable: true,
  57350. configurable: true
  57351. });
  57352. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57353. get: function () {
  57354. return this._subdivisionsY;
  57355. },
  57356. enumerable: true,
  57357. configurable: true
  57358. });
  57359. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57360. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57361. this._subdivisionsX = chunksCount;
  57362. this._subdivisionsY = chunksCount;
  57363. this.subdivide(chunksCount);
  57364. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57365. };
  57366. /**
  57367. * Returns a height (y) value in the Worl system :
  57368. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57369. * Returns the ground y position if (x, z) are outside the ground surface.
  57370. */
  57371. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57372. var world = this.getWorldMatrix();
  57373. var invMat = BABYLON.Tmp.Matrix[5];
  57374. world.invertToRef(invMat);
  57375. var tmpVect = BABYLON.Tmp.Vector3[8];
  57376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57377. x = tmpVect.x;
  57378. z = tmpVect.z;
  57379. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57380. return this.position.y;
  57381. }
  57382. if (!this._heightQuads || this._heightQuads.length == 0) {
  57383. this._initHeightQuads();
  57384. this._computeHeightQuads();
  57385. }
  57386. var facet = this._getFacetAt(x, z);
  57387. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57388. // return y in the World system
  57389. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57390. return tmpVect.y;
  57391. };
  57392. /**
  57393. * Returns a normalized vector (Vector3) orthogonal to the ground
  57394. * at the ground coordinates (x, z) expressed in the World system.
  57395. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57396. */
  57397. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57398. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57399. this.getNormalAtCoordinatesToRef(x, z, normal);
  57400. return normal;
  57401. };
  57402. /**
  57403. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57404. * at the ground coordinates (x, z) expressed in the World system.
  57405. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57406. * Returns the GroundMesh.
  57407. */
  57408. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57409. var world = this.getWorldMatrix();
  57410. var tmpMat = BABYLON.Tmp.Matrix[5];
  57411. world.invertToRef(tmpMat);
  57412. var tmpVect = BABYLON.Tmp.Vector3[8];
  57413. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57414. x = tmpVect.x;
  57415. z = tmpVect.z;
  57416. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57417. return this;
  57418. }
  57419. if (!this._heightQuads || this._heightQuads.length == 0) {
  57420. this._initHeightQuads();
  57421. this._computeHeightQuads();
  57422. }
  57423. var facet = this._getFacetAt(x, z);
  57424. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57425. return this;
  57426. };
  57427. /**
  57428. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57429. * if the ground has been updated.
  57430. * This can be used in the render loop.
  57431. * Returns the GroundMesh.
  57432. */
  57433. GroundMesh.prototype.updateCoordinateHeights = function () {
  57434. if (!this._heightQuads || this._heightQuads.length == 0) {
  57435. this._initHeightQuads();
  57436. }
  57437. this._computeHeightQuads();
  57438. return this;
  57439. };
  57440. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57441. GroundMesh.prototype._getFacetAt = function (x, z) {
  57442. // retrieve col and row from x, z coordinates in the ground local system
  57443. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57444. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57445. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57446. var facet;
  57447. if (z < quad.slope.x * x + quad.slope.y) {
  57448. facet = quad.facet1;
  57449. }
  57450. else {
  57451. facet = quad.facet2;
  57452. }
  57453. return facet;
  57454. };
  57455. // Creates and populates the heightMap array with "facet" elements :
  57456. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57457. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57458. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57459. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57460. // Returns the GroundMesh.
  57461. GroundMesh.prototype._initHeightQuads = function () {
  57462. var subdivisionsX = this._subdivisionsX;
  57463. var subdivisionsY = this._subdivisionsY;
  57464. this._heightQuads = new Array();
  57465. for (var row = 0; row < subdivisionsY; row++) {
  57466. for (var col = 0; col < subdivisionsX; col++) {
  57467. 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) };
  57468. this._heightQuads[row * subdivisionsX + col] = quad;
  57469. }
  57470. }
  57471. return this;
  57472. };
  57473. // Compute each quad element values and update the the heightMap array :
  57474. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57475. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57476. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57477. // Returns the GroundMesh.
  57478. GroundMesh.prototype._computeHeightQuads = function () {
  57479. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57480. if (!positions) {
  57481. return this;
  57482. }
  57483. var v1 = BABYLON.Tmp.Vector3[3];
  57484. var v2 = BABYLON.Tmp.Vector3[2];
  57485. var v3 = BABYLON.Tmp.Vector3[1];
  57486. var v4 = BABYLON.Tmp.Vector3[0];
  57487. var v1v2 = BABYLON.Tmp.Vector3[4];
  57488. var v1v3 = BABYLON.Tmp.Vector3[5];
  57489. var v1v4 = BABYLON.Tmp.Vector3[6];
  57490. var norm1 = BABYLON.Tmp.Vector3[7];
  57491. var norm2 = BABYLON.Tmp.Vector3[8];
  57492. var i = 0;
  57493. var j = 0;
  57494. var k = 0;
  57495. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57496. var h = 0;
  57497. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57498. var d2 = 0;
  57499. var subdivisionsX = this._subdivisionsX;
  57500. var subdivisionsY = this._subdivisionsY;
  57501. for (var row = 0; row < subdivisionsY; row++) {
  57502. for (var col = 0; col < subdivisionsX; col++) {
  57503. i = col * 3;
  57504. j = row * (subdivisionsX + 1) * 3;
  57505. k = (row + 1) * (subdivisionsX + 1) * 3;
  57506. v1.x = positions[j + i];
  57507. v1.y = positions[j + i + 1];
  57508. v1.z = positions[j + i + 2];
  57509. v2.x = positions[j + i + 3];
  57510. v2.y = positions[j + i + 4];
  57511. v2.z = positions[j + i + 5];
  57512. v3.x = positions[k + i];
  57513. v3.y = positions[k + i + 1];
  57514. v3.z = positions[k + i + 2];
  57515. v4.x = positions[k + i + 3];
  57516. v4.y = positions[k + i + 4];
  57517. v4.z = positions[k + i + 5];
  57518. // 2D slope V1V4
  57519. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57520. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57521. // facet equations :
  57522. // we compute each facet normal vector
  57523. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57524. // we compute the value d by applying the equation to v1 which belongs to the plane
  57525. // then we store the facet equation in a Vector4
  57526. v2.subtractToRef(v1, v1v2);
  57527. v3.subtractToRef(v1, v1v3);
  57528. v4.subtractToRef(v1, v1v4);
  57529. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57530. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57531. norm1.normalize();
  57532. norm2.normalize();
  57533. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57534. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57535. var quad = this._heightQuads[row * subdivisionsX + col];
  57536. quad.slope.copyFromFloats(cd, h);
  57537. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57538. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57539. }
  57540. }
  57541. return this;
  57542. };
  57543. GroundMesh.prototype.serialize = function (serializationObject) {
  57544. _super.prototype.serialize.call(this, serializationObject);
  57545. serializationObject.subdivisionsX = this._subdivisionsX;
  57546. serializationObject.subdivisionsY = this._subdivisionsY;
  57547. serializationObject.minX = this._minX;
  57548. serializationObject.maxX = this._maxX;
  57549. serializationObject.minZ = this._minZ;
  57550. serializationObject.maxZ = this._maxZ;
  57551. serializationObject.width = this._width;
  57552. serializationObject.height = this._height;
  57553. };
  57554. GroundMesh.Parse = function (parsedMesh, scene) {
  57555. var result = new GroundMesh(parsedMesh.name, scene);
  57556. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57557. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57558. result._minX = parsedMesh.minX;
  57559. result._maxX = parsedMesh.maxX;
  57560. result._minZ = parsedMesh.minZ;
  57561. result._maxZ = parsedMesh.maxZ;
  57562. result._width = parsedMesh.width;
  57563. result._height = parsedMesh.height;
  57564. return result;
  57565. };
  57566. return GroundMesh;
  57567. }(BABYLON.Mesh));
  57568. BABYLON.GroundMesh = GroundMesh;
  57569. })(BABYLON || (BABYLON = {}));
  57570. //# sourceMappingURL=babylon.groundMesh.js.map
  57571. var BABYLON;
  57572. (function (BABYLON) {
  57573. /**
  57574. * Creates an instance based on a source mesh.
  57575. */
  57576. var InstancedMesh = /** @class */ (function (_super) {
  57577. __extends(InstancedMesh, _super);
  57578. function InstancedMesh(name, source) {
  57579. var _this = _super.call(this, name, source.getScene()) || this;
  57580. source.instances.push(_this);
  57581. _this._sourceMesh = source;
  57582. _this.position.copyFrom(source.position);
  57583. _this.rotation.copyFrom(source.rotation);
  57584. _this.scaling.copyFrom(source.scaling);
  57585. if (source.rotationQuaternion) {
  57586. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57587. }
  57588. _this.infiniteDistance = source.infiniteDistance;
  57589. _this.setPivotMatrix(source.getPivotMatrix());
  57590. _this.refreshBoundingInfo();
  57591. _this._syncSubMeshes();
  57592. return _this;
  57593. }
  57594. /**
  57595. * Returns the string "InstancedMesh".
  57596. */
  57597. InstancedMesh.prototype.getClassName = function () {
  57598. return "InstancedMesh";
  57599. };
  57600. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57601. // Methods
  57602. get: function () {
  57603. return this._sourceMesh.receiveShadows;
  57604. },
  57605. enumerable: true,
  57606. configurable: true
  57607. });
  57608. Object.defineProperty(InstancedMesh.prototype, "material", {
  57609. get: function () {
  57610. return this._sourceMesh.material;
  57611. },
  57612. enumerable: true,
  57613. configurable: true
  57614. });
  57615. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57616. get: function () {
  57617. return this._sourceMesh.visibility;
  57618. },
  57619. enumerable: true,
  57620. configurable: true
  57621. });
  57622. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57623. get: function () {
  57624. return this._sourceMesh.skeleton;
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57630. get: function () {
  57631. return this._sourceMesh.renderingGroupId;
  57632. },
  57633. set: function (value) {
  57634. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57635. return;
  57636. }
  57637. //no-op with warning
  57638. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57639. },
  57640. enumerable: true,
  57641. configurable: true
  57642. });
  57643. /**
  57644. * Returns the total number of vertices (integer).
  57645. */
  57646. InstancedMesh.prototype.getTotalVertices = function () {
  57647. return this._sourceMesh.getTotalVertices();
  57648. };
  57649. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57650. get: function () {
  57651. return this._sourceMesh;
  57652. },
  57653. enumerable: true,
  57654. configurable: true
  57655. });
  57656. /**
  57657. * Is this node ready to be used/rendered
  57658. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57659. * @return {boolean} is it ready
  57660. */
  57661. InstancedMesh.prototype.isReady = function (completeCheck) {
  57662. if (completeCheck === void 0) { completeCheck = false; }
  57663. return this._sourceMesh.isReady(completeCheck, true);
  57664. };
  57665. /**
  57666. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57667. */
  57668. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57669. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57670. };
  57671. /**
  57672. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57673. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57674. * The `data` are either a numeric array either a Float32Array.
  57675. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57676. * 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).
  57677. * Note that a new underlying VertexBuffer object is created each call.
  57678. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  57679. *
  57680. * Possible `kind` values :
  57681. * - BABYLON.VertexBuffer.PositionKind
  57682. * - BABYLON.VertexBuffer.UVKind
  57683. * - BABYLON.VertexBuffer.UV2Kind
  57684. * - BABYLON.VertexBuffer.UV3Kind
  57685. * - BABYLON.VertexBuffer.UV4Kind
  57686. * - BABYLON.VertexBuffer.UV5Kind
  57687. * - BABYLON.VertexBuffer.UV6Kind
  57688. * - BABYLON.VertexBuffer.ColorKind
  57689. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57690. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57691. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57692. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57693. *
  57694. * Returns the Mesh.
  57695. */
  57696. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  57697. if (this.sourceMesh) {
  57698. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  57699. }
  57700. return this.sourceMesh;
  57701. };
  57702. /**
  57703. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  57704. * If the mesh has no geometry, it is simply returned as it is.
  57705. * The `data` are either a numeric array either a Float32Array.
  57706. * No new underlying VertexBuffer object is created.
  57707. * 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.
  57708. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  57709. *
  57710. * Possible `kind` values :
  57711. * - BABYLON.VertexBuffer.PositionKind
  57712. * - BABYLON.VertexBuffer.UVKind
  57713. * - BABYLON.VertexBuffer.UV2Kind
  57714. * - BABYLON.VertexBuffer.UV3Kind
  57715. * - BABYLON.VertexBuffer.UV4Kind
  57716. * - BABYLON.VertexBuffer.UV5Kind
  57717. * - BABYLON.VertexBuffer.UV6Kind
  57718. * - BABYLON.VertexBuffer.ColorKind
  57719. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57720. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57721. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57722. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57723. *
  57724. * Returns the Mesh.
  57725. */
  57726. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  57727. if (this.sourceMesh) {
  57728. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  57729. }
  57730. return this.sourceMesh;
  57731. };
  57732. /**
  57733. * Sets the mesh indices.
  57734. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  57735. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  57736. * This method creates a new index buffer each call.
  57737. * Returns the Mesh.
  57738. */
  57739. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  57740. if (totalVertices === void 0) { totalVertices = null; }
  57741. if (this.sourceMesh) {
  57742. this.sourceMesh.setIndices(indices, totalVertices);
  57743. }
  57744. return this.sourceMesh;
  57745. };
  57746. /**
  57747. * Boolean : True if the mesh owns the requested kind of data.
  57748. */
  57749. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  57750. return this._sourceMesh.isVerticesDataPresent(kind);
  57751. };
  57752. /**
  57753. * Returns an array of indices (IndicesArray).
  57754. */
  57755. InstancedMesh.prototype.getIndices = function () {
  57756. return this._sourceMesh.getIndices();
  57757. };
  57758. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  57759. get: function () {
  57760. return this._sourceMesh._positions;
  57761. },
  57762. enumerable: true,
  57763. configurable: true
  57764. });
  57765. /**
  57766. * Sets a new updated BoundingInfo to the mesh.
  57767. * Returns the mesh.
  57768. */
  57769. InstancedMesh.prototype.refreshBoundingInfo = function () {
  57770. var meshBB = this._sourceMesh.getBoundingInfo();
  57771. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  57772. this._updateBoundingInfo();
  57773. return this;
  57774. };
  57775. InstancedMesh.prototype._preActivate = function () {
  57776. if (this._currentLOD) {
  57777. this._currentLOD._preActivate();
  57778. }
  57779. return this;
  57780. };
  57781. InstancedMesh.prototype._activate = function (renderId) {
  57782. if (this._currentLOD) {
  57783. this._currentLOD._registerInstanceForRenderId(this, renderId);
  57784. }
  57785. return this;
  57786. };
  57787. /**
  57788. * Returns the current associated LOD AbstractMesh.
  57789. */
  57790. InstancedMesh.prototype.getLOD = function (camera) {
  57791. if (!camera) {
  57792. return this;
  57793. }
  57794. var boundingInfo = this.getBoundingInfo();
  57795. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  57796. if (this._currentLOD === this.sourceMesh) {
  57797. return this;
  57798. }
  57799. return this._currentLOD;
  57800. };
  57801. InstancedMesh.prototype._syncSubMeshes = function () {
  57802. this.releaseSubMeshes();
  57803. if (this._sourceMesh.subMeshes) {
  57804. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  57805. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  57806. }
  57807. }
  57808. return this;
  57809. };
  57810. InstancedMesh.prototype._generatePointsArray = function () {
  57811. return this._sourceMesh._generatePointsArray();
  57812. };
  57813. /**
  57814. * Creates a new InstancedMesh from the current mesh.
  57815. * - name (string) : the cloned mesh name
  57816. * - newParent (optional Node) : the optional Node to parent the clone to.
  57817. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  57818. *
  57819. * Returns the clone.
  57820. */
  57821. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57822. var result = this._sourceMesh.createInstance(name);
  57823. // Deep copy
  57824. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  57825. // Bounding info
  57826. this.refreshBoundingInfo();
  57827. // Parent
  57828. if (newParent) {
  57829. result.parent = newParent;
  57830. }
  57831. if (!doNotCloneChildren) {
  57832. // Children
  57833. for (var index = 0; index < this.getScene().meshes.length; index++) {
  57834. var mesh = this.getScene().meshes[index];
  57835. if (mesh.parent === this) {
  57836. mesh.clone(mesh.name, result);
  57837. }
  57838. }
  57839. }
  57840. result.computeWorldMatrix(true);
  57841. return result;
  57842. };
  57843. /**
  57844. * Disposes the InstancedMesh.
  57845. * Returns nothing.
  57846. */
  57847. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  57848. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  57849. // Remove from mesh
  57850. var index = this._sourceMesh.instances.indexOf(this);
  57851. this._sourceMesh.instances.splice(index, 1);
  57852. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  57853. };
  57854. return InstancedMesh;
  57855. }(BABYLON.AbstractMesh));
  57856. BABYLON.InstancedMesh = InstancedMesh;
  57857. })(BABYLON || (BABYLON = {}));
  57858. //# sourceMappingURL=babylon.instancedMesh.js.map
  57859. var BABYLON;
  57860. (function (BABYLON) {
  57861. var LinesMesh = /** @class */ (function (_super) {
  57862. __extends(LinesMesh, _super);
  57863. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  57864. if (scene === void 0) { scene = null; }
  57865. if (parent === void 0) { parent = null; }
  57866. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  57867. _this.useVertexColor = useVertexColor;
  57868. _this.useVertexAlpha = useVertexAlpha;
  57869. _this.color = new BABYLON.Color3(1, 1, 1);
  57870. _this.alpha = 1;
  57871. if (source) {
  57872. _this.color = source.color.clone();
  57873. _this.alpha = source.alpha;
  57874. _this.useVertexColor = source.useVertexColor;
  57875. _this.useVertexAlpha = source.useVertexAlpha;
  57876. }
  57877. _this._intersectionThreshold = 0.1;
  57878. var defines = [];
  57879. var options = {
  57880. attributes: [BABYLON.VertexBuffer.PositionKind],
  57881. uniforms: ["world", "viewProjection"],
  57882. needAlphaBlending: true,
  57883. defines: defines
  57884. };
  57885. if (useVertexAlpha === false) {
  57886. options.needAlphaBlending = false;
  57887. }
  57888. if (!useVertexColor) {
  57889. options.uniforms.push("color");
  57890. }
  57891. else {
  57892. options.defines.push("#define VERTEXCOLOR");
  57893. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  57894. }
  57895. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  57896. return _this;
  57897. }
  57898. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  57899. /**
  57900. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57901. * This margin is expressed in world space coordinates, so its value may vary.
  57902. * Default value is 0.1
  57903. * @returns the intersection Threshold value.
  57904. */
  57905. get: function () {
  57906. return this._intersectionThreshold;
  57907. },
  57908. /**
  57909. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57910. * This margin is expressed in world space coordinates, so its value may vary.
  57911. * @param value the new threshold to apply
  57912. */
  57913. set: function (value) {
  57914. if (this._intersectionThreshold === value) {
  57915. return;
  57916. }
  57917. this._intersectionThreshold = value;
  57918. if (this.geometry) {
  57919. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  57920. }
  57921. },
  57922. enumerable: true,
  57923. configurable: true
  57924. });
  57925. /**
  57926. * Returns the string "LineMesh"
  57927. */
  57928. LinesMesh.prototype.getClassName = function () {
  57929. return "LinesMesh";
  57930. };
  57931. Object.defineProperty(LinesMesh.prototype, "material", {
  57932. /**
  57933. * @hidden
  57934. */
  57935. get: function () {
  57936. return this._colorShader;
  57937. },
  57938. /**
  57939. * @hidden
  57940. */
  57941. set: function (value) {
  57942. // Do nothing
  57943. },
  57944. enumerable: true,
  57945. configurable: true
  57946. });
  57947. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  57948. /**
  57949. * @hidden
  57950. */
  57951. get: function () {
  57952. return false;
  57953. },
  57954. enumerable: true,
  57955. configurable: true
  57956. });
  57957. LinesMesh.prototype.createInstance = function (name) {
  57958. throw new Error("LinesMeshes do not support createInstance.");
  57959. };
  57960. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  57961. if (!this._geometry) {
  57962. return this;
  57963. }
  57964. // VBOs
  57965. this._geometry._bind(this._colorShader.getEffect());
  57966. // Color
  57967. if (!this.useVertexColor) {
  57968. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  57969. }
  57970. return this;
  57971. };
  57972. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  57973. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  57974. return this;
  57975. }
  57976. var engine = this.getScene().getEngine();
  57977. // Draw order
  57978. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  57979. return this;
  57980. };
  57981. LinesMesh.prototype.dispose = function (doNotRecurse) {
  57982. this._colorShader.dispose();
  57983. _super.prototype.dispose.call(this, doNotRecurse);
  57984. };
  57985. /**
  57986. * Returns a new LineMesh object cloned from the current one.
  57987. */
  57988. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57989. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  57990. };
  57991. return LinesMesh;
  57992. }(BABYLON.Mesh));
  57993. BABYLON.LinesMesh = LinesMesh;
  57994. })(BABYLON || (BABYLON = {}));
  57995. //# sourceMappingURL=babylon.linesMesh.js.map
  57996. var BABYLON;
  57997. (function (BABYLON) {
  57998. /**
  57999. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58000. * The underlying implementation relies on an associative array to ensure the best performances.
  58001. * The value can be anything including 'null' but except 'undefined'
  58002. */
  58003. var StringDictionary = /** @class */ (function () {
  58004. function StringDictionary() {
  58005. this._count = 0;
  58006. this._data = {};
  58007. }
  58008. /**
  58009. * This will clear this dictionary and copy the content from the 'source' one.
  58010. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58011. * @param source the dictionary to take the content from and copy to this dictionary
  58012. */
  58013. StringDictionary.prototype.copyFrom = function (source) {
  58014. var _this = this;
  58015. this.clear();
  58016. source.forEach(function (t, v) { return _this.add(t, v); });
  58017. };
  58018. /**
  58019. * Get a value based from its key
  58020. * @param key the given key to get the matching value from
  58021. * @return the value if found, otherwise undefined is returned
  58022. */
  58023. StringDictionary.prototype.get = function (key) {
  58024. var val = this._data[key];
  58025. if (val !== undefined) {
  58026. return val;
  58027. }
  58028. return undefined;
  58029. };
  58030. /**
  58031. * Get a value from its key or add it if it doesn't exist.
  58032. * This method will ensure you that a given key/data will be present in the dictionary.
  58033. * @param key the given key to get the matching value from
  58034. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58035. * The factory will only be invoked if there's no data for the given key.
  58036. * @return the value corresponding to the key.
  58037. */
  58038. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58039. var val = this.get(key);
  58040. if (val !== undefined) {
  58041. return val;
  58042. }
  58043. val = factory(key);
  58044. if (val) {
  58045. this.add(key, val);
  58046. }
  58047. return val;
  58048. };
  58049. /**
  58050. * Get a value from its key if present in the dictionary otherwise add it
  58051. * @param key the key to get the value from
  58052. * @param val if there's no such key/value pair in the dictionary add it with this value
  58053. * @return the value corresponding to the key
  58054. */
  58055. StringDictionary.prototype.getOrAdd = function (key, val) {
  58056. var curVal = this.get(key);
  58057. if (curVal !== undefined) {
  58058. return curVal;
  58059. }
  58060. this.add(key, val);
  58061. return val;
  58062. };
  58063. /**
  58064. * Check if there's a given key in the dictionary
  58065. * @param key the key to check for
  58066. * @return true if the key is present, false otherwise
  58067. */
  58068. StringDictionary.prototype.contains = function (key) {
  58069. return this._data[key] !== undefined;
  58070. };
  58071. /**
  58072. * Add a new key and its corresponding value
  58073. * @param key the key to add
  58074. * @param value the value corresponding to the key
  58075. * @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
  58076. */
  58077. StringDictionary.prototype.add = function (key, value) {
  58078. if (this._data[key] !== undefined) {
  58079. return false;
  58080. }
  58081. this._data[key] = value;
  58082. ++this._count;
  58083. return true;
  58084. };
  58085. StringDictionary.prototype.set = function (key, value) {
  58086. if (this._data[key] === undefined) {
  58087. return false;
  58088. }
  58089. this._data[key] = value;
  58090. return true;
  58091. };
  58092. /**
  58093. * Get the element of the given key and remove it from the dictionary
  58094. * @param key
  58095. */
  58096. StringDictionary.prototype.getAndRemove = function (key) {
  58097. var val = this.get(key);
  58098. if (val !== undefined) {
  58099. delete this._data[key];
  58100. --this._count;
  58101. return val;
  58102. }
  58103. return null;
  58104. };
  58105. /**
  58106. * Remove a key/value from the dictionary.
  58107. * @param key the key to remove
  58108. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58109. */
  58110. StringDictionary.prototype.remove = function (key) {
  58111. if (this.contains(key)) {
  58112. delete this._data[key];
  58113. --this._count;
  58114. return true;
  58115. }
  58116. return false;
  58117. };
  58118. /**
  58119. * Clear the whole content of the dictionary
  58120. */
  58121. StringDictionary.prototype.clear = function () {
  58122. this._data = {};
  58123. this._count = 0;
  58124. };
  58125. Object.defineProperty(StringDictionary.prototype, "count", {
  58126. get: function () {
  58127. return this._count;
  58128. },
  58129. enumerable: true,
  58130. configurable: true
  58131. });
  58132. /**
  58133. * Execute a callback on each key/val of the dictionary.
  58134. * Note that you can remove any element in this dictionary in the callback implementation
  58135. * @param callback the callback to execute on a given key/value pair
  58136. */
  58137. StringDictionary.prototype.forEach = function (callback) {
  58138. for (var cur in this._data) {
  58139. var val = this._data[cur];
  58140. callback(cur, val);
  58141. }
  58142. };
  58143. /**
  58144. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58145. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58146. * Note that you can remove any element in this dictionary in the callback implementation
  58147. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58148. */
  58149. StringDictionary.prototype.first = function (callback) {
  58150. for (var cur in this._data) {
  58151. var val = this._data[cur];
  58152. var res = callback(cur, val);
  58153. if (res) {
  58154. return res;
  58155. }
  58156. }
  58157. return null;
  58158. };
  58159. return StringDictionary;
  58160. }());
  58161. BABYLON.StringDictionary = StringDictionary;
  58162. })(BABYLON || (BABYLON = {}));
  58163. //# sourceMappingURL=babylon.stringDictionary.js.map
  58164. var BABYLON;
  58165. (function (BABYLON) {
  58166. var Debug;
  58167. (function (Debug) {
  58168. /**
  58169. * Class used to render a debug view of a given skeleton
  58170. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58171. */
  58172. var SkeletonViewer = /** @class */ (function () {
  58173. /**
  58174. * Creates a new SkeletonViewer
  58175. * @param skeleton defines the skeleton to render
  58176. * @param mesh defines the mesh attached to the skeleton
  58177. * @param scene defines the hosting scene
  58178. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58179. * @param renderingGroupId defines the rendering group id to use with the viewer
  58180. */
  58181. function SkeletonViewer(
  58182. /** defines the skeleton to render */
  58183. skeleton,
  58184. /** defines the mesh attached to the skeleton */
  58185. mesh, scene,
  58186. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58187. autoUpdateBonesMatrices,
  58188. /** defines the rendering group id to use with the viewer */
  58189. renderingGroupId) {
  58190. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58191. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58192. this.skeleton = skeleton;
  58193. this.mesh = mesh;
  58194. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58195. this.renderingGroupId = renderingGroupId;
  58196. /** Gets or sets the color used to render the skeleton */
  58197. this.color = BABYLON.Color3.White();
  58198. this._debugLines = new Array();
  58199. this._isEnabled = false;
  58200. this._scene = scene;
  58201. this.update();
  58202. this._renderFunction = this.update.bind(this);
  58203. }
  58204. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58205. get: function () {
  58206. return this._isEnabled;
  58207. },
  58208. /** Gets or sets a boolean indicating if the viewer is enabled */
  58209. set: function (value) {
  58210. if (this._isEnabled === value) {
  58211. return;
  58212. }
  58213. this._isEnabled = value;
  58214. if (value) {
  58215. this._scene.registerBeforeRender(this._renderFunction);
  58216. }
  58217. else {
  58218. this._scene.unregisterBeforeRender(this._renderFunction);
  58219. }
  58220. },
  58221. enumerable: true,
  58222. configurable: true
  58223. });
  58224. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58225. if (x === void 0) { x = 0; }
  58226. if (y === void 0) { y = 0; }
  58227. if (z === void 0) { z = 0; }
  58228. var tmat = BABYLON.Tmp.Matrix[0];
  58229. var parentBone = bone.getParent();
  58230. tmat.copyFrom(bone.getLocalMatrix());
  58231. if (x !== 0 || y !== 0 || z !== 0) {
  58232. var tmat2 = BABYLON.Tmp.Matrix[1];
  58233. BABYLON.Matrix.IdentityToRef(tmat2);
  58234. tmat2.m[12] = x;
  58235. tmat2.m[13] = y;
  58236. tmat2.m[14] = z;
  58237. tmat2.multiplyToRef(tmat, tmat);
  58238. }
  58239. if (parentBone) {
  58240. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58241. }
  58242. tmat.multiplyToRef(meshMat, tmat);
  58243. position.x = tmat.m[12];
  58244. position.y = tmat.m[13];
  58245. position.z = tmat.m[14];
  58246. };
  58247. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58248. var len = bones.length;
  58249. var meshPos = this.mesh.position;
  58250. for (var i = 0; i < len; i++) {
  58251. var bone = bones[i];
  58252. var points = this._debugLines[i];
  58253. if (!points) {
  58254. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58255. this._debugLines[i] = points;
  58256. }
  58257. this._getBonePosition(points[0], bone, meshMat);
  58258. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58259. points[0].subtractInPlace(meshPos);
  58260. points[1].subtractInPlace(meshPos);
  58261. }
  58262. };
  58263. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58264. var len = bones.length;
  58265. var boneNum = 0;
  58266. var meshPos = this.mesh.position;
  58267. for (var i = len - 1; i >= 0; i--) {
  58268. var childBone = bones[i];
  58269. var parentBone = childBone.getParent();
  58270. if (!parentBone) {
  58271. continue;
  58272. }
  58273. var points = this._debugLines[boneNum];
  58274. if (!points) {
  58275. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58276. this._debugLines[boneNum] = points;
  58277. }
  58278. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58279. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58280. points[0].subtractInPlace(meshPos);
  58281. points[1].subtractInPlace(meshPos);
  58282. boneNum++;
  58283. }
  58284. };
  58285. /** Update the viewer to sync with current skeleton state */
  58286. SkeletonViewer.prototype.update = function () {
  58287. if (this.autoUpdateBonesMatrices) {
  58288. this.skeleton.computeAbsoluteTransforms();
  58289. }
  58290. if (this.skeleton.bones[0].length === undefined) {
  58291. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58292. }
  58293. else {
  58294. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58295. }
  58296. if (!this._debugMesh) {
  58297. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58298. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58299. }
  58300. else {
  58301. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58302. }
  58303. this._debugMesh.position.copyFrom(this.mesh.position);
  58304. this._debugMesh.color = this.color;
  58305. };
  58306. /** Release associated resources */
  58307. SkeletonViewer.prototype.dispose = function () {
  58308. if (this._debugMesh) {
  58309. this.isEnabled = false;
  58310. this._debugMesh.dispose();
  58311. this._debugMesh = null;
  58312. }
  58313. };
  58314. return SkeletonViewer;
  58315. }());
  58316. Debug.SkeletonViewer = SkeletonViewer;
  58317. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58318. })(BABYLON || (BABYLON = {}));
  58319. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58320. /**
  58321. * Module Debug contains the (visual) components to debug a scene correctly
  58322. */
  58323. var BABYLON;
  58324. (function (BABYLON) {
  58325. var Debug;
  58326. (function (Debug) {
  58327. /**
  58328. * The Axes viewer will show 3 axes in a specific point in space
  58329. */
  58330. var AxesViewer = /** @class */ (function () {
  58331. /**
  58332. * Creates a new AxesViewer
  58333. * @param scene defines the hosting scene
  58334. * @param scaleLines defines a number used to scale line length (1 by default)
  58335. */
  58336. function AxesViewer(scene, scaleLines) {
  58337. if (scaleLines === void 0) { scaleLines = 1; }
  58338. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58339. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58340. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58341. /**
  58342. * Gets or sets a number used to scale line length
  58343. */
  58344. this.scaleLines = 1;
  58345. this.scaleLines = scaleLines;
  58346. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58347. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58348. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58349. this._xmesh.renderingGroupId = 2;
  58350. this._ymesh.renderingGroupId = 2;
  58351. this._zmesh.renderingGroupId = 2;
  58352. this._xmesh.material.checkReadyOnlyOnce = true;
  58353. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58354. this._ymesh.material.checkReadyOnlyOnce = true;
  58355. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58356. this._zmesh.material.checkReadyOnlyOnce = true;
  58357. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58358. this.scene = scene;
  58359. }
  58360. /**
  58361. * Force the viewer to update
  58362. * @param position defines the position of the viewer
  58363. * @param xaxis defines the x axis of the viewer
  58364. * @param yaxis defines the y axis of the viewer
  58365. * @param zaxis defines the z axis of the viewer
  58366. */
  58367. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58368. var scaleLines = this.scaleLines;
  58369. if (this._xmesh) {
  58370. this._xmesh.position.copyFrom(position);
  58371. }
  58372. if (this._ymesh) {
  58373. this._ymesh.position.copyFrom(position);
  58374. }
  58375. if (this._zmesh) {
  58376. this._zmesh.position.copyFrom(position);
  58377. }
  58378. var point2 = this._xline[1];
  58379. point2.x = xaxis.x * scaleLines;
  58380. point2.y = xaxis.y * scaleLines;
  58381. point2.z = xaxis.z * scaleLines;
  58382. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58383. point2 = this._yline[1];
  58384. point2.x = yaxis.x * scaleLines;
  58385. point2.y = yaxis.y * scaleLines;
  58386. point2.z = yaxis.z * scaleLines;
  58387. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58388. point2 = this._zline[1];
  58389. point2.x = zaxis.x * scaleLines;
  58390. point2.y = zaxis.y * scaleLines;
  58391. point2.z = zaxis.z * scaleLines;
  58392. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58393. };
  58394. /** Releases resources */
  58395. AxesViewer.prototype.dispose = function () {
  58396. if (this._xmesh) {
  58397. this._xmesh.dispose();
  58398. }
  58399. if (this._ymesh) {
  58400. this._ymesh.dispose();
  58401. }
  58402. if (this._zmesh) {
  58403. this._zmesh.dispose();
  58404. }
  58405. this._xmesh = null;
  58406. this._ymesh = null;
  58407. this._zmesh = null;
  58408. this.scene = null;
  58409. };
  58410. return AxesViewer;
  58411. }());
  58412. Debug.AxesViewer = AxesViewer;
  58413. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58414. })(BABYLON || (BABYLON = {}));
  58415. //# sourceMappingURL=babylon.axesViewer.js.map
  58416. var BABYLON;
  58417. (function (BABYLON) {
  58418. var Debug;
  58419. (function (Debug) {
  58420. /**
  58421. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58422. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58423. */
  58424. var BoneAxesViewer = /** @class */ (function (_super) {
  58425. __extends(BoneAxesViewer, _super);
  58426. /**
  58427. * Creates a new BoneAxesViewer
  58428. * @param scene defines the hosting scene
  58429. * @param bone defines the target bone
  58430. * @param mesh defines the target mesh
  58431. * @param scaleLines defines a scaling factor for line length (1 by default)
  58432. */
  58433. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58434. if (scaleLines === void 0) { scaleLines = 1; }
  58435. var _this = _super.call(this, scene, scaleLines) || this;
  58436. /** Gets current position */
  58437. _this.pos = BABYLON.Vector3.Zero();
  58438. /** Gets direction of X axis */
  58439. _this.xaxis = BABYLON.Vector3.Zero();
  58440. /** Gets direction of Y axis */
  58441. _this.yaxis = BABYLON.Vector3.Zero();
  58442. /** Gets direction of Z axis */
  58443. _this.zaxis = BABYLON.Vector3.Zero();
  58444. _this.mesh = mesh;
  58445. _this.bone = bone;
  58446. return _this;
  58447. }
  58448. /**
  58449. * Force the viewer to update
  58450. */
  58451. BoneAxesViewer.prototype.update = function () {
  58452. if (!this.mesh || !this.bone) {
  58453. return;
  58454. }
  58455. var bone = this.bone;
  58456. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58457. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58458. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58459. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58460. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58461. };
  58462. /** Releases resources */
  58463. BoneAxesViewer.prototype.dispose = function () {
  58464. if (this.mesh) {
  58465. this.mesh = null;
  58466. this.bone = null;
  58467. _super.prototype.dispose.call(this);
  58468. }
  58469. };
  58470. return BoneAxesViewer;
  58471. }(Debug.AxesViewer));
  58472. Debug.BoneAxesViewer = BoneAxesViewer;
  58473. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58474. })(BABYLON || (BABYLON = {}));
  58475. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58476. var BABYLON;
  58477. (function (BABYLON) {
  58478. var RayHelper = /** @class */ (function () {
  58479. function RayHelper(ray) {
  58480. this.ray = ray;
  58481. }
  58482. RayHelper.CreateAndShow = function (ray, scene, color) {
  58483. var helper = new RayHelper(ray);
  58484. helper.show(scene, color);
  58485. return helper;
  58486. };
  58487. RayHelper.prototype.show = function (scene, color) {
  58488. if (!this._renderFunction && this.ray) {
  58489. var ray = this.ray;
  58490. this._renderFunction = this._render.bind(this);
  58491. this._scene = scene;
  58492. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58493. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58494. if (this._renderFunction) {
  58495. this._scene.registerBeforeRender(this._renderFunction);
  58496. }
  58497. }
  58498. if (color && this._renderLine) {
  58499. this._renderLine.color.copyFrom(color);
  58500. }
  58501. };
  58502. RayHelper.prototype.hide = function () {
  58503. if (this._renderFunction && this._scene) {
  58504. this._scene.unregisterBeforeRender(this._renderFunction);
  58505. this._scene = null;
  58506. this._renderFunction = null;
  58507. if (this._renderLine) {
  58508. this._renderLine.dispose();
  58509. this._renderLine = null;
  58510. }
  58511. this._renderPoints = [];
  58512. }
  58513. };
  58514. RayHelper.prototype._render = function () {
  58515. var ray = this.ray;
  58516. if (!ray) {
  58517. return;
  58518. }
  58519. var point = this._renderPoints[1];
  58520. var len = Math.min(ray.length, 1000000);
  58521. point.copyFrom(ray.direction);
  58522. point.scaleInPlace(len);
  58523. point.addInPlace(ray.origin);
  58524. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58525. };
  58526. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58527. this._attachedToMesh = mesh;
  58528. var ray = this.ray;
  58529. if (!ray) {
  58530. return;
  58531. }
  58532. if (!ray.direction) {
  58533. ray.direction = BABYLON.Vector3.Zero();
  58534. }
  58535. if (!ray.origin) {
  58536. ray.origin = BABYLON.Vector3.Zero();
  58537. }
  58538. if (length) {
  58539. ray.length = length;
  58540. }
  58541. if (!meshSpaceOrigin) {
  58542. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58543. }
  58544. if (!meshSpaceDirection) {
  58545. // -1 so that this will work with Mesh.lookAt
  58546. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58547. }
  58548. if (!this._meshSpaceDirection) {
  58549. this._meshSpaceDirection = meshSpaceDirection.clone();
  58550. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58551. }
  58552. else {
  58553. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58554. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58555. }
  58556. if (!this._updateToMeshFunction) {
  58557. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58558. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58559. }
  58560. this._updateToMesh();
  58561. };
  58562. RayHelper.prototype.detachFromMesh = function () {
  58563. if (this._attachedToMesh) {
  58564. if (this._updateToMeshFunction) {
  58565. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58566. }
  58567. this._attachedToMesh = null;
  58568. this._updateToMeshFunction = null;
  58569. }
  58570. };
  58571. RayHelper.prototype._updateToMesh = function () {
  58572. var ray = this.ray;
  58573. if (!this._attachedToMesh || !ray) {
  58574. return;
  58575. }
  58576. if (this._attachedToMesh._isDisposed) {
  58577. this.detachFromMesh();
  58578. return;
  58579. }
  58580. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58581. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58582. };
  58583. RayHelper.prototype.dispose = function () {
  58584. this.hide();
  58585. this.detachFromMesh();
  58586. this.ray = null;
  58587. };
  58588. return RayHelper;
  58589. }());
  58590. BABYLON.RayHelper = RayHelper;
  58591. })(BABYLON || (BABYLON = {}));
  58592. //# sourceMappingURL=babylon.rayHelper.js.map
  58593. var BABYLON;
  58594. (function (BABYLON) {
  58595. // load the inspector using require, if not present in the global namespace.
  58596. var DebugLayer = /** @class */ (function () {
  58597. function DebugLayer(scene) {
  58598. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58599. this.onPropertyChangedObservable = new BABYLON.Observable();
  58600. this._scene = scene;
  58601. }
  58602. /** Creates the inspector window. */
  58603. DebugLayer.prototype._createInspector = function (config) {
  58604. if (config === void 0) { config = {}; }
  58605. var popup = config.popup || false;
  58606. var initialTab = config.initialTab || 0;
  58607. var parentElement = config.parentElement || null;
  58608. if (!this._inspector) {
  58609. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58610. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58611. } // else nothing to do as instance is already created
  58612. };
  58613. DebugLayer.prototype.isVisible = function () {
  58614. if (!this._inspector) {
  58615. return false;
  58616. }
  58617. return true;
  58618. };
  58619. DebugLayer.prototype.hide = function () {
  58620. if (this._inspector) {
  58621. try {
  58622. this._inspector.dispose();
  58623. }
  58624. catch (e) {
  58625. // If the inspector has been removed directly from the inspector tool
  58626. }
  58627. this.onPropertyChangedObservable.clear();
  58628. this._inspector = null;
  58629. }
  58630. };
  58631. /**
  58632. *
  58633. * Launch the debugLayer.
  58634. *
  58635. * initialTab:
  58636. * | Value | Tab Name |
  58637. * | --- | --- |
  58638. * | 0 | Scene |
  58639. * | 1 | Console |
  58640. * | 2 | Stats |
  58641. * | 3 | Textures |
  58642. * | 4 | Mesh |
  58643. * | 5 | Light |
  58644. * | 6 | Material |
  58645. * | 7 | GLTF |
  58646. * | 8 | GUI |
  58647. * | 9 | Physics |
  58648. * | 10 | Camera |
  58649. * | 11 | Audio |
  58650. *
  58651. */
  58652. DebugLayer.prototype.show = function (config) {
  58653. if (config === void 0) { config = {}; }
  58654. if (typeof this.BJSINSPECTOR == 'undefined') {
  58655. // Load inspector and add it to the DOM
  58656. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58657. }
  58658. else {
  58659. // Otherwise creates the inspector
  58660. this._createInspector(config);
  58661. }
  58662. };
  58663. /**
  58664. * Gets the active tab
  58665. * @return the index of the active tab or -1 if the inspector is hidden
  58666. */
  58667. DebugLayer.prototype.getActiveTab = function () {
  58668. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  58669. };
  58670. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  58671. return DebugLayer;
  58672. }());
  58673. BABYLON.DebugLayer = DebugLayer;
  58674. })(BABYLON || (BABYLON = {}));
  58675. //# sourceMappingURL=babylon.debugLayer.js.map
  58676. var BABYLON;
  58677. (function (BABYLON) {
  58678. var Debug;
  58679. (function (Debug) {
  58680. /**
  58681. * Used to show the physics impostor around the specific mesh
  58682. */
  58683. var PhysicsViewer = /** @class */ (function () {
  58684. /**
  58685. * Creates a new PhysicsViewer
  58686. * @param scene defines the hosting scene
  58687. */
  58688. function PhysicsViewer(scene) {
  58689. /** @hidden */
  58690. this._impostors = [];
  58691. /** @hidden */
  58692. this._meshes = [];
  58693. /** @hidden */
  58694. this._numMeshes = 0;
  58695. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58696. var physicEngine = this._scene.getPhysicsEngine();
  58697. if (physicEngine) {
  58698. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  58699. }
  58700. }
  58701. /** @hidden */
  58702. PhysicsViewer.prototype._updateDebugMeshes = function () {
  58703. var plugin = this._physicsEnginePlugin;
  58704. for (var i = 0; i < this._numMeshes; i++) {
  58705. var impostor = this._impostors[i];
  58706. if (!impostor) {
  58707. continue;
  58708. }
  58709. if (impostor.isDisposed) {
  58710. this.hideImpostor(this._impostors[i--]);
  58711. }
  58712. else {
  58713. var mesh = this._meshes[i];
  58714. if (mesh && plugin) {
  58715. plugin.syncMeshWithImpostor(mesh, impostor);
  58716. }
  58717. }
  58718. }
  58719. };
  58720. /**
  58721. * Renders a specified physic impostor
  58722. * @param impostor defines the impostor to render
  58723. */
  58724. PhysicsViewer.prototype.showImpostor = function (impostor) {
  58725. if (!this._scene) {
  58726. return;
  58727. }
  58728. for (var i = 0; i < this._numMeshes; i++) {
  58729. if (this._impostors[i] == impostor) {
  58730. return;
  58731. }
  58732. }
  58733. var debugMesh = this._getDebugMesh(impostor, this._scene);
  58734. if (debugMesh) {
  58735. this._impostors[this._numMeshes] = impostor;
  58736. this._meshes[this._numMeshes] = debugMesh;
  58737. if (this._numMeshes === 0) {
  58738. this._renderFunction = this._updateDebugMeshes.bind(this);
  58739. this._scene.registerBeforeRender(this._renderFunction);
  58740. }
  58741. this._numMeshes++;
  58742. }
  58743. };
  58744. /**
  58745. * Hides a specified physic impostor
  58746. * @param impostor defines the impostor to hide
  58747. */
  58748. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  58749. if (!impostor || !this._scene) {
  58750. return;
  58751. }
  58752. var removed = false;
  58753. for (var i = 0; i < this._numMeshes; i++) {
  58754. if (this._impostors[i] == impostor) {
  58755. var mesh = this._meshes[i];
  58756. if (!mesh) {
  58757. continue;
  58758. }
  58759. this._scene.removeMesh(mesh);
  58760. mesh.dispose();
  58761. this._numMeshes--;
  58762. if (this._numMeshes > 0) {
  58763. this._meshes[i] = this._meshes[this._numMeshes];
  58764. this._impostors[i] = this._impostors[this._numMeshes];
  58765. this._meshes[this._numMeshes] = null;
  58766. this._impostors[this._numMeshes] = null;
  58767. }
  58768. else {
  58769. this._meshes[0] = null;
  58770. this._impostors[0] = null;
  58771. }
  58772. removed = true;
  58773. break;
  58774. }
  58775. }
  58776. if (removed && this._numMeshes === 0) {
  58777. this._scene.unregisterBeforeRender(this._renderFunction);
  58778. }
  58779. };
  58780. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  58781. if (!this._debugMaterial) {
  58782. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  58783. this._debugMaterial.wireframe = true;
  58784. }
  58785. return this._debugMaterial;
  58786. };
  58787. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  58788. if (!this._debugBoxMesh) {
  58789. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  58790. this._debugBoxMesh.renderingGroupId = 1;
  58791. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  58792. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  58793. scene.removeMesh(this._debugBoxMesh);
  58794. }
  58795. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  58796. };
  58797. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  58798. if (!this._debugSphereMesh) {
  58799. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  58800. this._debugSphereMesh.renderingGroupId = 1;
  58801. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  58802. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  58803. scene.removeMesh(this._debugSphereMesh);
  58804. }
  58805. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  58806. };
  58807. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  58808. var mesh = null;
  58809. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  58810. mesh = this._getDebugBoxMesh(scene);
  58811. impostor.getBoxSizeToRef(mesh.scaling);
  58812. }
  58813. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  58814. mesh = this._getDebugSphereMesh(scene);
  58815. var radius = impostor.getRadius();
  58816. mesh.scaling.x = radius * 2;
  58817. mesh.scaling.y = radius * 2;
  58818. mesh.scaling.z = radius * 2;
  58819. }
  58820. return mesh;
  58821. };
  58822. /** Releases all resources */
  58823. PhysicsViewer.prototype.dispose = function () {
  58824. for (var i = 0; i < this._numMeshes; i++) {
  58825. this.hideImpostor(this._impostors[i]);
  58826. }
  58827. if (this._debugBoxMesh) {
  58828. this._debugBoxMesh.dispose();
  58829. }
  58830. if (this._debugSphereMesh) {
  58831. this._debugSphereMesh.dispose();
  58832. }
  58833. if (this._debugMaterial) {
  58834. this._debugMaterial.dispose();
  58835. }
  58836. this._impostors.length = 0;
  58837. this._scene = null;
  58838. this._physicsEnginePlugin = null;
  58839. };
  58840. return PhysicsViewer;
  58841. }());
  58842. Debug.PhysicsViewer = PhysicsViewer;
  58843. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58844. })(BABYLON || (BABYLON = {}));
  58845. //# sourceMappingURL=babylon.physicsViewer.js.map
  58846. var BABYLON;
  58847. (function (BABYLON) {
  58848. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  58849. get: function () {
  58850. return this._forceShowBoundingBoxes || false;
  58851. },
  58852. set: function (value) {
  58853. this._forceShowBoundingBoxes = value;
  58854. // Lazyly creates a BB renderer if needed.
  58855. if (value) {
  58856. this.getBoundingBoxRenderer();
  58857. }
  58858. },
  58859. enumerable: true,
  58860. configurable: true
  58861. });
  58862. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  58863. if (!this._boundingBoxRenderer) {
  58864. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  58865. }
  58866. return this._boundingBoxRenderer;
  58867. };
  58868. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  58869. get: function () {
  58870. return this._showBoundingBox || false;
  58871. },
  58872. set: function (value) {
  58873. this._showBoundingBox = value;
  58874. // Lazyly creates a BB renderer if needed.
  58875. if (value) {
  58876. this.getScene().getBoundingBoxRenderer();
  58877. }
  58878. },
  58879. enumerable: true,
  58880. configurable: true
  58881. });
  58882. var BoundingBoxRenderer = /** @class */ (function () {
  58883. function BoundingBoxRenderer(scene) {
  58884. /**
  58885. * The component name helpfull to identify the component in the list of scene components.
  58886. */
  58887. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  58888. this.frontColor = new BABYLON.Color3(1, 1, 1);
  58889. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  58890. this.showBackLines = true;
  58891. this.renderList = new BABYLON.SmartArray(32);
  58892. this._vertexBuffers = {};
  58893. this.scene = scene;
  58894. scene._addComponent(this);
  58895. }
  58896. /**
  58897. * Registers the component in a given scene
  58898. */
  58899. BoundingBoxRenderer.prototype.register = function () {
  58900. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  58901. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  58902. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  58903. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  58904. };
  58905. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  58906. if (mesh.showSubMeshesBoundingBox) {
  58907. var boundingInfo = subMesh.getBoundingInfo();
  58908. if (boundingInfo !== null && boundingInfo !== undefined) {
  58909. this.renderList.push(boundingInfo.boundingBox);
  58910. }
  58911. }
  58912. };
  58913. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  58914. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  58915. var boundingInfo = sourceMesh.getBoundingInfo();
  58916. this.renderList.push(boundingInfo.boundingBox);
  58917. }
  58918. };
  58919. BoundingBoxRenderer.prototype._prepareRessources = function () {
  58920. if (this._colorShader) {
  58921. return;
  58922. }
  58923. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  58924. attributes: [BABYLON.VertexBuffer.PositionKind],
  58925. uniforms: ["world", "viewProjection", "color"]
  58926. });
  58927. var engine = this.scene.getEngine();
  58928. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  58929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  58930. this._createIndexBuffer();
  58931. };
  58932. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  58933. var engine = this.scene.getEngine();
  58934. 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]);
  58935. };
  58936. /**
  58937. * Rebuilds the elements related to this component in case of
  58938. * context lost for instance.
  58939. */
  58940. BoundingBoxRenderer.prototype.rebuild = function () {
  58941. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58942. if (vb) {
  58943. vb._rebuild();
  58944. }
  58945. this._createIndexBuffer();
  58946. };
  58947. BoundingBoxRenderer.prototype.reset = function () {
  58948. this.renderList.reset();
  58949. };
  58950. BoundingBoxRenderer.prototype.render = function () {
  58951. if (this.renderList.length === 0) {
  58952. return;
  58953. }
  58954. this._prepareRessources();
  58955. if (!this._colorShader.isReady()) {
  58956. return;
  58957. }
  58958. var engine = this.scene.getEngine();
  58959. engine.setDepthWrite(false);
  58960. this._colorShader._preBind();
  58961. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  58962. var boundingBox = this.renderList.data[boundingBoxIndex];
  58963. var min = boundingBox.minimum;
  58964. var max = boundingBox.maximum;
  58965. var diff = max.subtract(min);
  58966. var median = min.add(diff.scale(0.5));
  58967. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  58968. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  58969. .multiply(boundingBox.getWorldMatrix());
  58970. // VBOs
  58971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  58972. if (this.showBackLines) {
  58973. // Back
  58974. engine.setDepthFunctionToGreaterOrEqual();
  58975. this.scene.resetCachedMaterial();
  58976. this._colorShader.setColor4("color", this.backColor.toColor4());
  58977. this._colorShader.bind(worldMatrix);
  58978. // Draw order
  58979. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  58980. }
  58981. // Front
  58982. engine.setDepthFunctionToLess();
  58983. this.scene.resetCachedMaterial();
  58984. this._colorShader.setColor4("color", this.frontColor.toColor4());
  58985. this._colorShader.bind(worldMatrix);
  58986. // Draw order
  58987. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  58988. }
  58989. this._colorShader.unbind();
  58990. engine.setDepthFunctionToLessOrEqual();
  58991. engine.setDepthWrite(true);
  58992. };
  58993. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  58994. this._prepareRessources();
  58995. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  58996. return;
  58997. }
  58998. var engine = this.scene.getEngine();
  58999. engine.setDepthWrite(false);
  59000. engine.setColorWrite(false);
  59001. this._colorShader._preBind();
  59002. var boundingBox = mesh._boundingInfo.boundingBox;
  59003. var min = boundingBox.minimum;
  59004. var max = boundingBox.maximum;
  59005. var diff = max.subtract(min);
  59006. var median = min.add(diff.scale(0.5));
  59007. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59008. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59009. .multiply(boundingBox.getWorldMatrix());
  59010. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59011. engine.setDepthFunctionToLess();
  59012. this.scene.resetCachedMaterial();
  59013. this._colorShader.bind(worldMatrix);
  59014. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59015. this._colorShader.unbind();
  59016. engine.setDepthFunctionToLessOrEqual();
  59017. engine.setDepthWrite(true);
  59018. engine.setColorWrite(true);
  59019. };
  59020. BoundingBoxRenderer.prototype.dispose = function () {
  59021. if (!this._colorShader) {
  59022. return;
  59023. }
  59024. this.renderList.dispose();
  59025. this._colorShader.dispose();
  59026. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59027. if (buffer) {
  59028. buffer.dispose();
  59029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59030. }
  59031. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59032. };
  59033. return BoundingBoxRenderer;
  59034. }());
  59035. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59036. })(BABYLON || (BABYLON = {}));
  59037. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59038. var BABYLON;
  59039. (function (BABYLON) {
  59040. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59041. return this._gl.createTransformFeedback();
  59042. };
  59043. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59044. this._gl.deleteTransformFeedback(value);
  59045. };
  59046. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59047. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59048. };
  59049. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59050. if (usePoints === void 0) { usePoints = true; }
  59051. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59052. };
  59053. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59054. this._gl.endTransformFeedback();
  59055. };
  59056. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59057. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59058. };
  59059. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59060. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59061. };
  59062. })(BABYLON || (BABYLON = {}));
  59063. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59064. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59065. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59066. s = arguments[i];
  59067. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59068. t[p] = s[p];
  59069. }
  59070. return t;
  59071. };
  59072. var BABYLON;
  59073. (function (BABYLON) {
  59074. /**
  59075. * This represents a GPU particle system in Babylon
  59076. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59077. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59078. */
  59079. var GPUParticleSystem = /** @class */ (function () {
  59080. /**
  59081. * Instantiates a GPU particle system.
  59082. * 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.
  59083. * @param name The name of the particle system
  59084. * @param options The options used to create the system
  59085. * @param scene The scene the particle system belongs to
  59086. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59087. */
  59088. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59089. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59090. /**
  59091. * The emitter represents the Mesh or position we are attaching the particle system to.
  59092. */
  59093. this.emitter = null;
  59094. /**
  59095. * The rendering group used by the Particle system to chose when to render.
  59096. */
  59097. this.renderingGroupId = 0;
  59098. /**
  59099. * The layer mask we are rendering the particles through.
  59100. */
  59101. this.layerMask = 0x0FFFFFFF;
  59102. this._accumulatedCount = 0;
  59103. this._targetIndex = 0;
  59104. this._currentRenderId = -1;
  59105. this._started = false;
  59106. this._stopped = false;
  59107. this._timeDelta = 0;
  59108. this._attributesStrideSize = 21;
  59109. this._actualFrame = 0;
  59110. this._rawTextureWidth = 256;
  59111. /**
  59112. * List of animations used by the particle system.
  59113. */
  59114. this.animations = [];
  59115. /**
  59116. * An event triggered when the system is disposed.
  59117. */
  59118. this.onDisposeObservable = new BABYLON.Observable();
  59119. /**
  59120. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59121. */
  59122. this.updateSpeed = 0.01;
  59123. /**
  59124. * The amount of time the particle system is running (depends of the overall update speed).
  59125. */
  59126. this.targetStopDuration = 0;
  59127. /**
  59128. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59129. */
  59130. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59131. /**
  59132. * Minimum life time of emitting particles.
  59133. */
  59134. this.minLifeTime = 1;
  59135. /**
  59136. * Maximum life time of emitting particles.
  59137. */
  59138. this.maxLifeTime = 1;
  59139. /**
  59140. * Minimum Size of emitting particles.
  59141. */
  59142. this.minSize = 1;
  59143. /**
  59144. * Maximum Size of emitting particles.
  59145. */
  59146. this.maxSize = 1;
  59147. /**
  59148. * Minimum scale of emitting particles on X axis.
  59149. */
  59150. this.minScaleX = 1;
  59151. /**
  59152. * Maximum scale of emitting particles on X axis.
  59153. */
  59154. this.maxScaleX = 1;
  59155. /**
  59156. * Minimum scale of emitting particles on Y axis.
  59157. */
  59158. this.minScaleY = 1;
  59159. /**
  59160. * Maximum scale of emitting particles on Y axis.
  59161. */
  59162. this.maxScaleY = 1;
  59163. /**
  59164. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59165. */
  59166. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59167. /**
  59168. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59169. */
  59170. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59171. /**
  59172. * Color the particle will have at the end of its lifetime.
  59173. */
  59174. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59175. /**
  59176. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59177. */
  59178. this.emitRate = 100;
  59179. /**
  59180. * You can use gravity if you want to give an orientation to your particles.
  59181. */
  59182. this.gravity = BABYLON.Vector3.Zero();
  59183. /**
  59184. * Minimum power of emitting particles.
  59185. */
  59186. this.minEmitPower = 1;
  59187. /**
  59188. * Maximum power of emitting particles.
  59189. */
  59190. this.maxEmitPower = 1;
  59191. /**
  59192. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59193. */
  59194. this.minAngularSpeed = 0;
  59195. /**
  59196. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59197. */
  59198. this.maxAngularSpeed = 0;
  59199. /**
  59200. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59201. * to override the particles.
  59202. */
  59203. this.forceDepthWrite = false;
  59204. this._preWarmDone = false;
  59205. /** 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 */
  59206. this.preWarmCycles = 0;
  59207. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59208. this.preWarmStepOffset = 1;
  59209. /**
  59210. * Gets or sets the minimal initial rotation in radians.
  59211. */
  59212. this.minInitialRotation = 0;
  59213. /**
  59214. * Gets or sets the maximal initial rotation in radians.
  59215. */
  59216. this.maxInitialRotation = 0;
  59217. /**
  59218. * 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)
  59219. */
  59220. this.spriteCellChangeSpeed = 1;
  59221. /**
  59222. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59223. */
  59224. this.startSpriteCellID = 0;
  59225. /**
  59226. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59227. */
  59228. this.endSpriteCellID = 0;
  59229. /**
  59230. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59231. */
  59232. this.spriteCellWidth = 0;
  59233. /**
  59234. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59235. */
  59236. this.spriteCellHeight = 0;
  59237. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59238. this.translationPivot = new BABYLON.Vector2(0, 0);
  59239. /**
  59240. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59241. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59242. */
  59243. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59244. this._isBillboardBased = true;
  59245. this._colorGradients = null;
  59246. this._angularSpeedGradients = null;
  59247. this._sizeGradients = null;
  59248. this._velocityGradients = null;
  59249. this.id = name;
  59250. this.name = name;
  59251. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59252. this._engine = this._scene.getEngine();
  59253. if (!options.randomTextureSize) {
  59254. delete options.randomTextureSize;
  59255. }
  59256. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59257. var optionsAsNumber = options;
  59258. if (isFinite(optionsAsNumber)) {
  59259. fullOptions.capacity = optionsAsNumber;
  59260. }
  59261. this._capacity = fullOptions.capacity;
  59262. this._activeCount = fullOptions.capacity;
  59263. this._currentActiveCount = 0;
  59264. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59265. this._scene.particleSystems.push(this);
  59266. this._updateEffectOptions = {
  59267. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59268. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59269. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59270. "angleRange", "radiusRange", "cellInfos"],
  59271. uniformBuffersNames: [],
  59272. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  59273. defines: "",
  59274. fallbacks: null,
  59275. onCompiled: null,
  59276. onError: null,
  59277. indexParameters: null,
  59278. maxSimultaneousLights: 0,
  59279. transformFeedbackVaryings: []
  59280. };
  59281. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59282. // Random data
  59283. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59284. var d = [];
  59285. for (var i = 0; i < maxTextureSize; ++i) {
  59286. d.push(Math.random());
  59287. d.push(Math.random());
  59288. d.push(Math.random());
  59289. d.push(Math.random());
  59290. }
  59291. 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);
  59292. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59293. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59294. d = [];
  59295. for (var i = 0; i < maxTextureSize; ++i) {
  59296. d.push(Math.random());
  59297. d.push(Math.random());
  59298. d.push(Math.random());
  59299. d.push(Math.random());
  59300. }
  59301. 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);
  59302. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59303. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59304. this._randomTextureSize = maxTextureSize;
  59305. }
  59306. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59307. /**
  59308. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59309. */
  59310. get: function () {
  59311. if (!BABYLON.Engine.LastCreatedEngine) {
  59312. return false;
  59313. }
  59314. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59315. },
  59316. enumerable: true,
  59317. configurable: true
  59318. });
  59319. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59320. /**
  59321. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59322. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59323. */
  59324. get: function () {
  59325. if (this.particleEmitterType.direction1) {
  59326. return this.particleEmitterType.direction1;
  59327. }
  59328. return BABYLON.Vector3.Zero();
  59329. },
  59330. set: function (value) {
  59331. if (this.particleEmitterType.direction1) {
  59332. this.particleEmitterType.direction1 = value;
  59333. }
  59334. },
  59335. enumerable: true,
  59336. configurable: true
  59337. });
  59338. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59339. /**
  59340. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59341. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59342. */
  59343. get: function () {
  59344. if (this.particleEmitterType.direction2) {
  59345. return this.particleEmitterType.direction2;
  59346. }
  59347. return BABYLON.Vector3.Zero();
  59348. },
  59349. set: function (value) {
  59350. if (this.particleEmitterType.direction2) {
  59351. this.particleEmitterType.direction2 = value;
  59352. }
  59353. },
  59354. enumerable: true,
  59355. configurable: true
  59356. });
  59357. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59358. /**
  59359. * 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.
  59360. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59361. */
  59362. get: function () {
  59363. if (this.particleEmitterType.minEmitBox) {
  59364. return this.particleEmitterType.minEmitBox;
  59365. }
  59366. return BABYLON.Vector3.Zero();
  59367. },
  59368. set: function (value) {
  59369. if (this.particleEmitterType.minEmitBox) {
  59370. this.particleEmitterType.minEmitBox = value;
  59371. }
  59372. },
  59373. enumerable: true,
  59374. configurable: true
  59375. });
  59376. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59377. /**
  59378. * 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.
  59379. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59380. */
  59381. get: function () {
  59382. if (this.particleEmitterType.maxEmitBox) {
  59383. return this.particleEmitterType.maxEmitBox;
  59384. }
  59385. return BABYLON.Vector3.Zero();
  59386. },
  59387. set: function (value) {
  59388. if (this.particleEmitterType.maxEmitBox) {
  59389. this.particleEmitterType.maxEmitBox = value;
  59390. }
  59391. },
  59392. enumerable: true,
  59393. configurable: true
  59394. });
  59395. /**
  59396. * Gets the maximum number of particles active at the same time.
  59397. * @returns The max number of active particles.
  59398. */
  59399. GPUParticleSystem.prototype.getCapacity = function () {
  59400. return this._capacity;
  59401. };
  59402. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59403. /**
  59404. * Gets or set the number of active particles
  59405. */
  59406. get: function () {
  59407. return this._activeCount;
  59408. },
  59409. set: function (value) {
  59410. this._activeCount = Math.min(value, this._capacity);
  59411. },
  59412. enumerable: true,
  59413. configurable: true
  59414. });
  59415. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59416. /**
  59417. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59418. */
  59419. get: function () {
  59420. return this._isAnimationSheetEnabled;
  59421. },
  59422. enumerable: true,
  59423. configurable: true
  59424. });
  59425. /**
  59426. * Is this system ready to be used/rendered
  59427. * @return true if the system is ready
  59428. */
  59429. GPUParticleSystem.prototype.isReady = function () {
  59430. if (!this._updateEffect) {
  59431. this._recreateUpdateEffect();
  59432. this._recreateRenderEffect();
  59433. return false;
  59434. }
  59435. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59436. return false;
  59437. }
  59438. return true;
  59439. };
  59440. /**
  59441. * Gets Wether the system has been started.
  59442. * @returns True if it has been started, otherwise false.
  59443. */
  59444. GPUParticleSystem.prototype.isStarted = function () {
  59445. return this._started;
  59446. };
  59447. /**
  59448. * Starts the particle system and begins to emit
  59449. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59450. */
  59451. GPUParticleSystem.prototype.start = function (delay) {
  59452. var _this = this;
  59453. if (delay === void 0) { delay = 0; }
  59454. if (delay) {
  59455. setTimeout(function () {
  59456. _this.start(0);
  59457. }, delay);
  59458. return;
  59459. }
  59460. this._started = true;
  59461. this._stopped = false;
  59462. this._preWarmDone = false;
  59463. };
  59464. /**
  59465. * Stops the particle system.
  59466. */
  59467. GPUParticleSystem.prototype.stop = function () {
  59468. this._stopped = true;
  59469. };
  59470. /**
  59471. * Remove all active particles
  59472. */
  59473. GPUParticleSystem.prototype.reset = function () {
  59474. this._releaseBuffers();
  59475. this._releaseVAOs();
  59476. this._currentActiveCount = 0;
  59477. this._targetIndex = 0;
  59478. };
  59479. /**
  59480. * Returns the string "GPUParticleSystem"
  59481. * @returns a string containing the class name
  59482. */
  59483. GPUParticleSystem.prototype.getClassName = function () {
  59484. return "GPUParticleSystem";
  59485. };
  59486. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59487. /**
  59488. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59489. */
  59490. get: function () {
  59491. return this._isBillboardBased;
  59492. },
  59493. set: function (value) {
  59494. if (this._isBillboardBased === value) {
  59495. return;
  59496. }
  59497. this._isBillboardBased = value;
  59498. this._releaseBuffers();
  59499. },
  59500. enumerable: true,
  59501. configurable: true
  59502. });
  59503. /**
  59504. * Gets the current list of color gradients.
  59505. * You must use addColorGradient and removeColorGradient to udpate this list
  59506. * @returns the list of color gradients
  59507. */
  59508. GPUParticleSystem.prototype.getColorGradients = function () {
  59509. return this._colorGradients;
  59510. };
  59511. /**
  59512. * Gets the current list of size gradients.
  59513. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59514. * @returns the list of size gradients
  59515. */
  59516. GPUParticleSystem.prototype.getSizeGradients = function () {
  59517. return this._sizeGradients;
  59518. };
  59519. /**
  59520. * Gets the current list of angular speed gradients.
  59521. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59522. * @returns the list of angular speed gradients
  59523. */
  59524. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59525. return this._angularSpeedGradients;
  59526. };
  59527. /**
  59528. * Gets the current list of velocity gradients.
  59529. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59530. * @returns the list of angular speed gradients
  59531. */
  59532. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59533. return this._velocityGradients;
  59534. };
  59535. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59536. if (!gradients) {
  59537. return this;
  59538. }
  59539. var index = 0;
  59540. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59541. var valueGradient = gradients_1[_i];
  59542. if (valueGradient.gradient === gradient) {
  59543. gradients.splice(index, 1);
  59544. break;
  59545. }
  59546. index++;
  59547. }
  59548. if (texture) {
  59549. texture.dispose();
  59550. }
  59551. this._releaseBuffers();
  59552. return this;
  59553. };
  59554. /**
  59555. * Adds a new color gradient
  59556. * @param gradient defines the gradient to use (between 0 and 1)
  59557. * @param color defines the color to affect to the specified gradient
  59558. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59559. * @returns the current particle system
  59560. */
  59561. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59562. if (!this._colorGradients) {
  59563. this._colorGradients = [];
  59564. }
  59565. var colorGradient = new BABYLON.ColorGradient();
  59566. colorGradient.gradient = gradient;
  59567. colorGradient.color1 = color1;
  59568. this._colorGradients.push(colorGradient);
  59569. this._colorGradients.sort(function (a, b) {
  59570. if (a.gradient < b.gradient) {
  59571. return -1;
  59572. }
  59573. else if (a.gradient > b.gradient) {
  59574. return 1;
  59575. }
  59576. return 0;
  59577. });
  59578. if (this._colorGradientsTexture) {
  59579. this._colorGradientsTexture.dispose();
  59580. this._colorGradientsTexture = null;
  59581. }
  59582. this._releaseBuffers();
  59583. return this;
  59584. };
  59585. /**
  59586. * Remove a specific color gradient
  59587. * @param gradient defines the gradient to remove
  59588. * @returns the current particle system
  59589. */
  59590. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59591. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59592. this._colorGradientsTexture = null;
  59593. return this;
  59594. };
  59595. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59596. var valueGradient = new BABYLON.FactorGradient();
  59597. valueGradient.gradient = gradient;
  59598. valueGradient.factor1 = factor;
  59599. factorGradients.push(valueGradient);
  59600. factorGradients.sort(function (a, b) {
  59601. if (a.gradient < b.gradient) {
  59602. return -1;
  59603. }
  59604. else if (a.gradient > b.gradient) {
  59605. return 1;
  59606. }
  59607. return 0;
  59608. });
  59609. this._releaseBuffers();
  59610. };
  59611. /**
  59612. * Adds a new size gradient
  59613. * @param gradient defines the gradient to use (between 0 and 1)
  59614. * @param factor defines the size factor to affect to the specified gradient
  59615. * @returns the current particle system
  59616. */
  59617. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59618. if (!this._sizeGradients) {
  59619. this._sizeGradients = [];
  59620. }
  59621. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59622. if (this._sizeGradientsTexture) {
  59623. this._sizeGradientsTexture.dispose();
  59624. this._sizeGradientsTexture = null;
  59625. }
  59626. this._releaseBuffers();
  59627. return this;
  59628. };
  59629. /**
  59630. * Remove a specific size gradient
  59631. * @param gradient defines the gradient to remove
  59632. * @returns the current particle system
  59633. */
  59634. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59635. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59636. this._sizeGradientsTexture = null;
  59637. return this;
  59638. };
  59639. /**
  59640. * Adds a new angular speed gradient
  59641. * @param gradient defines the gradient to use (between 0 and 1)
  59642. * @param factor defines the size factor to affect to the specified gradient
  59643. * @returns the current particle system
  59644. */
  59645. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59646. if (!this._angularSpeedGradients) {
  59647. this._angularSpeedGradients = [];
  59648. }
  59649. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59650. if (this._angularSpeedGradientsTexture) {
  59651. this._angularSpeedGradientsTexture.dispose();
  59652. this._angularSpeedGradientsTexture = null;
  59653. }
  59654. this._releaseBuffers();
  59655. return this;
  59656. };
  59657. /**
  59658. * Remove a specific angular speed gradient
  59659. * @param gradient defines the gradient to remove
  59660. * @returns the current particle system
  59661. */
  59662. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59663. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  59664. this._angularSpeedGradientsTexture = null;
  59665. return this;
  59666. };
  59667. /**
  59668. * Adds a new velocity gradient
  59669. * @param gradient defines the gradient to use (between 0 and 1)
  59670. * @param factor defines the size factor to affect to the specified gradient
  59671. * @returns the current particle system
  59672. */
  59673. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  59674. if (!this._velocityGradients) {
  59675. this._velocityGradients = [];
  59676. }
  59677. this._addFactorGradient(this._velocityGradients, gradient, factor);
  59678. if (this._velocityGradientsTexture) {
  59679. this._velocityGradientsTexture.dispose();
  59680. this._velocityGradientsTexture = null;
  59681. }
  59682. this._releaseBuffers();
  59683. return this;
  59684. };
  59685. /**
  59686. * Remove a specific velocity gradient
  59687. * @param gradient defines the gradient to remove
  59688. * @returns the current particle system
  59689. */
  59690. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59691. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  59692. this._velocityGradientsTexture = null;
  59693. return this;
  59694. };
  59695. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  59696. var updateVertexBuffers = {};
  59697. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  59698. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  59699. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  59700. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  59701. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  59702. var offset = 12;
  59703. if (!this._colorGradientsTexture) {
  59704. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  59705. offset += 4;
  59706. }
  59707. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  59708. offset += 3;
  59709. if (!this._isBillboardBased) {
  59710. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  59711. offset += 3;
  59712. }
  59713. if (this._angularSpeedGradientsTexture) {
  59714. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  59715. offset += 1;
  59716. }
  59717. else {
  59718. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  59719. offset += 2;
  59720. }
  59721. if (this._isAnimationSheetEnabled) {
  59722. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  59723. offset += 1;
  59724. }
  59725. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  59726. this._engine.bindArrayBuffer(null);
  59727. return vao;
  59728. };
  59729. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  59730. var renderVertexBuffers = {};
  59731. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  59732. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  59733. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  59734. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  59735. var offset = 12;
  59736. if (!this._colorGradientsTexture) {
  59737. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  59738. offset += 4;
  59739. }
  59740. offset += 3; // Direction
  59741. if (!this._isBillboardBased) {
  59742. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  59743. offset += 3;
  59744. }
  59745. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  59746. if (this._angularSpeedGradientsTexture) {
  59747. offset++;
  59748. }
  59749. else {
  59750. offset += 2;
  59751. }
  59752. if (this._isAnimationSheetEnabled) {
  59753. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  59754. offset += 1;
  59755. }
  59756. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  59757. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  59758. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  59759. this._engine.bindArrayBuffer(null);
  59760. return vao;
  59761. };
  59762. GPUParticleSystem.prototype._initialize = function (force) {
  59763. if (force === void 0) { force = false; }
  59764. if (this._buffer0 && !force) {
  59765. return;
  59766. }
  59767. var engine = this._scene.getEngine();
  59768. var data = new Array();
  59769. if (!this.isBillboardBased) {
  59770. this._attributesStrideSize += 3;
  59771. }
  59772. if (this._colorGradientsTexture) {
  59773. this._attributesStrideSize -= 4;
  59774. }
  59775. if (this._angularSpeedGradientsTexture) {
  59776. this._attributesStrideSize -= 1;
  59777. }
  59778. if (this._isAnimationSheetEnabled) {
  59779. this._attributesStrideSize += 1;
  59780. }
  59781. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  59782. // position
  59783. data.push(0.0);
  59784. data.push(0.0);
  59785. data.push(0.0);
  59786. // Age and life
  59787. data.push(0.0); // create the particle as a dead one to create a new one at start
  59788. data.push(0.0);
  59789. // Seed
  59790. data.push(Math.random());
  59791. data.push(Math.random());
  59792. data.push(Math.random());
  59793. data.push(Math.random());
  59794. // Size
  59795. data.push(0.0);
  59796. data.push(0.0);
  59797. data.push(0.0);
  59798. if (!this._colorGradientsTexture) {
  59799. // color
  59800. data.push(0.0);
  59801. data.push(0.0);
  59802. data.push(0.0);
  59803. data.push(0.0);
  59804. }
  59805. // direction
  59806. data.push(0.0);
  59807. data.push(0.0);
  59808. data.push(0.0);
  59809. if (!this.isBillboardBased) {
  59810. // initialDirection
  59811. data.push(0.0);
  59812. data.push(0.0);
  59813. data.push(0.0);
  59814. }
  59815. // angle
  59816. data.push(0.0);
  59817. if (!this._angularSpeedGradientsTexture) {
  59818. data.push(0.0);
  59819. }
  59820. if (this._isAnimationSheetEnabled) {
  59821. data.push(0.0);
  59822. }
  59823. }
  59824. // Sprite data
  59825. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  59826. -0.5, 0.5, 0, 1,
  59827. -0.5, -0.5, 0, 0,
  59828. 0.5, -0.5, 1, 0]);
  59829. // Buffers
  59830. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  59831. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  59832. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  59833. // Update VAO
  59834. this._updateVAO = [];
  59835. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  59836. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  59837. // Render VAO
  59838. this._renderVAO = [];
  59839. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  59840. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  59841. // Links
  59842. this._sourceBuffer = this._buffer0;
  59843. this._targetBuffer = this._buffer1;
  59844. };
  59845. /** @hidden */
  59846. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  59847. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  59848. if (this._isBillboardBased) {
  59849. defines += "\n#define BILLBOARD";
  59850. }
  59851. if (this._colorGradientsTexture) {
  59852. defines += "\n#define COLORGRADIENTS";
  59853. }
  59854. if (this._sizeGradientsTexture) {
  59855. defines += "\n#define SIZEGRADIENTS";
  59856. }
  59857. if (this._angularSpeedGradientsTexture) {
  59858. defines += "\n#define ANGULARSPEEDGRADIENTS";
  59859. }
  59860. if (this._velocityGradientsTexture) {
  59861. defines += "\n#define VELOCITYGRADIENTS";
  59862. }
  59863. if (this.isAnimationSheetEnabled) {
  59864. defines += "\n#define ANIMATESHEET";
  59865. }
  59866. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  59867. return;
  59868. }
  59869. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  59870. if (!this._colorGradientsTexture) {
  59871. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  59872. }
  59873. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  59874. if (!this._isBillboardBased) {
  59875. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  59876. }
  59877. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  59878. if (this.isAnimationSheetEnabled) {
  59879. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  59880. }
  59881. this._updateEffectOptions.defines = defines;
  59882. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  59883. };
  59884. /** @hidden */
  59885. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  59886. var defines = "";
  59887. if (this._scene.clipPlane) {
  59888. defines = "\n#define CLIPPLANE";
  59889. }
  59890. if (this._isBillboardBased) {
  59891. defines += "\n#define BILLBOARD";
  59892. switch (this.billboardMode) {
  59893. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  59894. defines += "\n#define BILLBOARDY";
  59895. break;
  59896. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  59897. default:
  59898. break;
  59899. }
  59900. }
  59901. if (this._colorGradientsTexture) {
  59902. defines += "\n#define COLORGRADIENTS";
  59903. }
  59904. if (this.isAnimationSheetEnabled) {
  59905. defines += "\n#define ANIMATESHEET";
  59906. }
  59907. if (this._renderEffect && this._renderEffect.defines === defines) {
  59908. return;
  59909. }
  59910. 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);
  59911. };
  59912. /**
  59913. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59914. * @param preWarm defines if we are in the pre-warmimg phase
  59915. */
  59916. GPUParticleSystem.prototype.animate = function (preWarm) {
  59917. if (preWarm === void 0) { preWarm = false; }
  59918. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59919. this._actualFrame += this._timeDelta;
  59920. if (!this._stopped) {
  59921. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  59922. this.stop();
  59923. }
  59924. }
  59925. };
  59926. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  59927. var texture = this[textureName];
  59928. if (!factorGradients || !factorGradients.length || texture) {
  59929. return;
  59930. }
  59931. var data = new Float32Array(this._rawTextureWidth);
  59932. for (var x = 0; x < this._rawTextureWidth; x++) {
  59933. var ratio = x / this._rawTextureWidth;
  59934. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  59935. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59936. });
  59937. }
  59938. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59939. };
  59940. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  59941. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  59942. };
  59943. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  59944. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  59945. };
  59946. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  59947. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  59948. };
  59949. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  59950. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  59951. return;
  59952. }
  59953. var data = new Uint8Array(this._rawTextureWidth * 4);
  59954. var tmpColor = BABYLON.Tmp.Color4[0];
  59955. for (var x = 0; x < this._rawTextureWidth; x++) {
  59956. var ratio = x / this._rawTextureWidth;
  59957. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  59958. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  59959. data[x * 4] = tmpColor.r * 255;
  59960. data[x * 4 + 1] = tmpColor.g * 255;
  59961. data[x * 4 + 2] = tmpColor.b * 255;
  59962. data[x * 4 + 3] = tmpColor.a * 255;
  59963. });
  59964. }
  59965. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59966. };
  59967. /**
  59968. * Renders the particle system in its current state
  59969. * @param preWarm defines if the system should only update the particles but not render them
  59970. * @returns the current number of particles
  59971. */
  59972. GPUParticleSystem.prototype.render = function (preWarm) {
  59973. if (preWarm === void 0) { preWarm = false; }
  59974. if (!this._started) {
  59975. return 0;
  59976. }
  59977. this._createColorGradientTexture();
  59978. this._createSizeGradientTexture();
  59979. this._createAngularSpeedGradientTexture();
  59980. this._createVelocityGradientTexture();
  59981. this._recreateUpdateEffect();
  59982. this._recreateRenderEffect();
  59983. if (!this.isReady()) {
  59984. return 0;
  59985. }
  59986. if (!preWarm) {
  59987. if (!this._preWarmDone && this.preWarmCycles) {
  59988. for (var index = 0; index < this.preWarmCycles; index++) {
  59989. this.animate(true);
  59990. this.render(true);
  59991. }
  59992. this._preWarmDone = true;
  59993. }
  59994. if (this._currentRenderId === this._scene.getRenderId()) {
  59995. return 0;
  59996. }
  59997. this._currentRenderId = this._scene.getRenderId();
  59998. }
  59999. // Get everything ready to render
  60000. this._initialize();
  60001. this._accumulatedCount += this.emitRate * this._timeDelta;
  60002. if (this._accumulatedCount > 1) {
  60003. var intPart = this._accumulatedCount | 0;
  60004. this._accumulatedCount -= intPart;
  60005. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60006. }
  60007. if (!this._currentActiveCount) {
  60008. return 0;
  60009. }
  60010. // Enable update effect
  60011. this._engine.enableEffect(this._updateEffect);
  60012. this._engine.setState(false);
  60013. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60014. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60015. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60016. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60017. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60018. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60019. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60020. if (!this._colorGradientsTexture) {
  60021. this._updateEffect.setDirectColor4("color1", this.color1);
  60022. this._updateEffect.setDirectColor4("color2", this.color2);
  60023. }
  60024. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60025. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60026. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60027. this._updateEffect.setVector3("gravity", this.gravity);
  60028. if (this._sizeGradientsTexture) {
  60029. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60030. }
  60031. if (this._angularSpeedGradientsTexture) {
  60032. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60033. }
  60034. if (this._velocityGradientsTexture) {
  60035. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60036. }
  60037. if (this.particleEmitterType) {
  60038. this.particleEmitterType.applyToShader(this._updateEffect);
  60039. }
  60040. if (this._isAnimationSheetEnabled) {
  60041. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60042. }
  60043. var emitterWM;
  60044. if (this.emitter.position) {
  60045. var emitterMesh = this.emitter;
  60046. emitterWM = emitterMesh.getWorldMatrix();
  60047. }
  60048. else {
  60049. var emitterPosition = this.emitter;
  60050. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60051. }
  60052. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60053. // Bind source VAO
  60054. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60055. // Update
  60056. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60057. this._engine.setRasterizerState(false);
  60058. this._engine.beginTransformFeedback(true);
  60059. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60060. this._engine.endTransformFeedback();
  60061. this._engine.setRasterizerState(true);
  60062. this._engine.bindTransformFeedbackBuffer(null);
  60063. if (!preWarm) {
  60064. // Enable render effect
  60065. this._engine.enableEffect(this._renderEffect);
  60066. var viewMatrix = this._scene.getViewMatrix();
  60067. this._renderEffect.setMatrix("view", viewMatrix);
  60068. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60069. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60070. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60071. if (this._colorGradientsTexture) {
  60072. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60073. }
  60074. else {
  60075. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60076. }
  60077. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60078. var baseSize = this.particleTexture.getBaseSize();
  60079. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60080. }
  60081. if (this._isBillboardBased) {
  60082. var camera = this._scene.activeCamera;
  60083. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60084. }
  60085. if (this._scene.clipPlane) {
  60086. var clipPlane = this._scene.clipPlane;
  60087. var invView = viewMatrix.clone();
  60088. invView.invert();
  60089. this._renderEffect.setMatrix("invView", invView);
  60090. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60091. }
  60092. // Draw order
  60093. switch (this.blendMode) {
  60094. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60095. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60096. break;
  60097. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60098. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60099. break;
  60100. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60101. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60102. break;
  60103. }
  60104. if (this.forceDepthWrite) {
  60105. this._engine.setDepthWrite(true);
  60106. }
  60107. // Bind source VAO
  60108. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60109. // Render
  60110. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60111. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60112. }
  60113. // Switch VAOs
  60114. this._targetIndex++;
  60115. if (this._targetIndex === 2) {
  60116. this._targetIndex = 0;
  60117. }
  60118. // Switch buffers
  60119. var tmpBuffer = this._sourceBuffer;
  60120. this._sourceBuffer = this._targetBuffer;
  60121. this._targetBuffer = tmpBuffer;
  60122. return this._currentActiveCount;
  60123. };
  60124. /**
  60125. * Rebuilds the particle system
  60126. */
  60127. GPUParticleSystem.prototype.rebuild = function () {
  60128. this._initialize(true);
  60129. };
  60130. GPUParticleSystem.prototype._releaseBuffers = function () {
  60131. if (this._buffer0) {
  60132. this._buffer0.dispose();
  60133. this._buffer0 = null;
  60134. }
  60135. if (this._buffer1) {
  60136. this._buffer1.dispose();
  60137. this._buffer1 = null;
  60138. }
  60139. if (this._spriteBuffer) {
  60140. this._spriteBuffer.dispose();
  60141. this._spriteBuffer = null;
  60142. }
  60143. };
  60144. GPUParticleSystem.prototype._releaseVAOs = function () {
  60145. if (!this._updateVAO) {
  60146. return;
  60147. }
  60148. for (var index = 0; index < this._updateVAO.length; index++) {
  60149. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60150. }
  60151. this._updateVAO = [];
  60152. for (var index = 0; index < this._renderVAO.length; index++) {
  60153. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60154. }
  60155. this._renderVAO = [];
  60156. };
  60157. /**
  60158. * Disposes the particle system and free the associated resources
  60159. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60160. */
  60161. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60162. if (disposeTexture === void 0) { disposeTexture = true; }
  60163. var index = this._scene.particleSystems.indexOf(this);
  60164. if (index > -1) {
  60165. this._scene.particleSystems.splice(index, 1);
  60166. }
  60167. this._releaseBuffers();
  60168. this._releaseVAOs();
  60169. if (this._colorGradientsTexture) {
  60170. this._colorGradientsTexture.dispose();
  60171. this._colorGradientsTexture = null;
  60172. }
  60173. if (this._sizeGradientsTexture) {
  60174. this._sizeGradientsTexture.dispose();
  60175. this._sizeGradientsTexture = null;
  60176. }
  60177. if (this._angularSpeedGradientsTexture) {
  60178. this._angularSpeedGradientsTexture.dispose();
  60179. this._angularSpeedGradientsTexture = null;
  60180. }
  60181. if (this._velocityGradientsTexture) {
  60182. this._velocityGradientsTexture.dispose();
  60183. this._velocityGradientsTexture = null;
  60184. }
  60185. if (this._randomTexture) {
  60186. this._randomTexture.dispose();
  60187. this._randomTexture = null;
  60188. }
  60189. if (this._randomTexture2) {
  60190. this._randomTexture2.dispose();
  60191. this._randomTexture2 = null;
  60192. }
  60193. if (disposeTexture && this.particleTexture) {
  60194. this.particleTexture.dispose();
  60195. this.particleTexture = null;
  60196. }
  60197. // Callback
  60198. this.onDisposeObservable.notifyObservers(this);
  60199. this.onDisposeObservable.clear();
  60200. };
  60201. /**
  60202. * Clones the particle system.
  60203. * @param name The name of the cloned object
  60204. * @param newEmitter The new emitter to use
  60205. * @returns the cloned particle system
  60206. */
  60207. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60208. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60209. BABYLON.Tools.DeepCopy(this, result);
  60210. if (newEmitter === undefined) {
  60211. newEmitter = this.emitter;
  60212. }
  60213. result.emitter = newEmitter;
  60214. if (this.particleTexture) {
  60215. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60216. }
  60217. return result;
  60218. };
  60219. /**
  60220. * Serializes the particle system to a JSON object.
  60221. * @returns the JSON object
  60222. */
  60223. GPUParticleSystem.prototype.serialize = function () {
  60224. var serializationObject = {};
  60225. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60226. serializationObject.activeParticleCount = this.activeParticleCount;
  60227. return serializationObject;
  60228. };
  60229. /**
  60230. * Parses a JSON object to create a GPU particle system.
  60231. * @param parsedParticleSystem The JSON object to parse
  60232. * @param scene The scene to create the particle system in
  60233. * @param rootUrl The root url to use to load external dependencies like texture
  60234. * @returns the parsed GPU particle system
  60235. */
  60236. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60237. var name = parsedParticleSystem.name;
  60238. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60239. if (parsedParticleSystem.activeParticleCount) {
  60240. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60241. }
  60242. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60243. return particleSystem;
  60244. };
  60245. return GPUParticleSystem;
  60246. }());
  60247. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60248. })(BABYLON || (BABYLON = {}));
  60249. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60250. var BABYLON;
  60251. (function (BABYLON) {
  60252. /**
  60253. * Represents one particle of a solid particle system.
  60254. */
  60255. var SolidParticle = /** @class */ (function () {
  60256. /**
  60257. * Creates a Solid Particle object.
  60258. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60259. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60260. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60261. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60262. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60263. * @param shapeId (integer) is the model shape identifier in the SPS.
  60264. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60265. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60266. */
  60267. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60268. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60269. /**
  60270. * particle global index
  60271. */
  60272. this.idx = 0;
  60273. /**
  60274. * The color of the particle
  60275. */
  60276. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60277. /**
  60278. * The world space position of the particle.
  60279. */
  60280. this.position = BABYLON.Vector3.Zero();
  60281. /**
  60282. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60283. */
  60284. this.rotation = BABYLON.Vector3.Zero();
  60285. /**
  60286. * The scaling of the particle.
  60287. */
  60288. this.scaling = BABYLON.Vector3.One();
  60289. /**
  60290. * The uvs of the particle.
  60291. */
  60292. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60293. /**
  60294. * The current speed of the particle.
  60295. */
  60296. this.velocity = BABYLON.Vector3.Zero();
  60297. /**
  60298. * The pivot point in the particle local space.
  60299. */
  60300. this.pivot = BABYLON.Vector3.Zero();
  60301. /**
  60302. * Must the particle be translated from its pivot point in its local space ?
  60303. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60304. * Default : false
  60305. */
  60306. this.translateFromPivot = false;
  60307. /**
  60308. * Is the particle active or not ?
  60309. */
  60310. this.alive = true;
  60311. /**
  60312. * Is the particle visible or not ?
  60313. */
  60314. this.isVisible = true;
  60315. /**
  60316. * Index of this particle in the global "positions" array (Internal use)
  60317. */
  60318. this._pos = 0;
  60319. /**
  60320. * Index of this particle in the global "indices" array (Internal use)
  60321. */
  60322. this._ind = 0;
  60323. /**
  60324. * ModelShape id of this particle
  60325. */
  60326. this.shapeId = 0;
  60327. /**
  60328. * Index of the particle in its shape id (Internal use)
  60329. */
  60330. this.idxInShape = 0;
  60331. /**
  60332. * Still set as invisible in order to skip useless computations (Internal use)
  60333. */
  60334. this._stillInvisible = false;
  60335. /**
  60336. * Last computed particle rotation matrix
  60337. */
  60338. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60339. /**
  60340. * Parent particle Id, if any.
  60341. * Default null.
  60342. */
  60343. this.parentId = null;
  60344. /**
  60345. * Internal global position in the SPS.
  60346. */
  60347. this._globalPosition = BABYLON.Vector3.Zero();
  60348. this.idx = particleIndex;
  60349. this._pos = positionIndex;
  60350. this._ind = indiceIndex;
  60351. this._model = model;
  60352. this.shapeId = shapeId;
  60353. this.idxInShape = idxInShape;
  60354. this._sps = sps;
  60355. if (modelBoundingInfo) {
  60356. this._modelBoundingInfo = modelBoundingInfo;
  60357. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60358. }
  60359. }
  60360. Object.defineProperty(SolidParticle.prototype, "scale", {
  60361. /**
  60362. * Legacy support, changed scale to scaling
  60363. */
  60364. get: function () {
  60365. return this.scaling;
  60366. },
  60367. /**
  60368. * Legacy support, changed scale to scaling
  60369. */
  60370. set: function (scale) {
  60371. this.scaling = scale;
  60372. },
  60373. enumerable: true,
  60374. configurable: true
  60375. });
  60376. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60377. /**
  60378. * Legacy support, changed quaternion to rotationQuaternion
  60379. */
  60380. get: function () {
  60381. return this.rotationQuaternion;
  60382. },
  60383. /**
  60384. * Legacy support, changed quaternion to rotationQuaternion
  60385. */
  60386. set: function (q) {
  60387. this.rotationQuaternion = q;
  60388. },
  60389. enumerable: true,
  60390. configurable: true
  60391. });
  60392. /**
  60393. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60394. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60395. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60396. * @returns true if it intersects
  60397. */
  60398. SolidParticle.prototype.intersectsMesh = function (target) {
  60399. if (!this._boundingInfo || !target._boundingInfo) {
  60400. return false;
  60401. }
  60402. if (this._sps._bSphereOnly) {
  60403. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60404. }
  60405. return this._boundingInfo.intersects(target._boundingInfo, false);
  60406. };
  60407. return SolidParticle;
  60408. }());
  60409. BABYLON.SolidParticle = SolidParticle;
  60410. /**
  60411. * Represents the shape of the model used by one particle of a solid particle system.
  60412. * SPS internal tool, don't use it manually.
  60413. */
  60414. var ModelShape = /** @class */ (function () {
  60415. /**
  60416. * 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.
  60417. * SPS internal tool, don't use it manually.
  60418. * @hidden
  60419. */
  60420. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60421. /**
  60422. * length of the shape in the model indices array (internal use)
  60423. */
  60424. this._indicesLength = 0;
  60425. this.shapeID = id;
  60426. this._shape = shape;
  60427. this._indicesLength = indicesLength;
  60428. this._shapeUV = shapeUV;
  60429. this._positionFunction = posFunction;
  60430. this._vertexFunction = vtxFunction;
  60431. }
  60432. return ModelShape;
  60433. }());
  60434. BABYLON.ModelShape = ModelShape;
  60435. /**
  60436. * Represents a Depth Sorted Particle in the solid particle system.
  60437. */
  60438. var DepthSortedParticle = /** @class */ (function () {
  60439. function DepthSortedParticle() {
  60440. /**
  60441. * Index of the particle in the "indices" array
  60442. */
  60443. this.ind = 0;
  60444. /**
  60445. * Length of the particle shape in the "indices" array
  60446. */
  60447. this.indicesLength = 0;
  60448. /**
  60449. * Squared distance from the particle to the camera
  60450. */
  60451. this.sqDistance = 0.0;
  60452. }
  60453. return DepthSortedParticle;
  60454. }());
  60455. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60456. })(BABYLON || (BABYLON = {}));
  60457. //# sourceMappingURL=babylon.solidParticle.js.map
  60458. var BABYLON;
  60459. (function (BABYLON) {
  60460. /**
  60461. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60462. *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.
  60463. * The SPS is also a particle system. It provides some methods to manage the particles.
  60464. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60465. *
  60466. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60467. */
  60468. var SolidParticleSystem = /** @class */ (function () {
  60469. /**
  60470. * Creates a SPS (Solid Particle System) object.
  60471. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60472. * @param scene (Scene) is the scene in which the SPS is added.
  60473. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60474. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60475. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60476. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60477. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60478. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60479. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60480. */
  60481. function SolidParticleSystem(name, scene, options) {
  60482. /**
  60483. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60484. * Example : var p = SPS.particles[i];
  60485. */
  60486. this.particles = new Array();
  60487. /**
  60488. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60489. */
  60490. this.nbParticles = 0;
  60491. /**
  60492. * If the particles must ever face the camera (default false). Useful for planar particles.
  60493. */
  60494. this.billboard = false;
  60495. /**
  60496. * Recompute normals when adding a shape
  60497. */
  60498. this.recomputeNormals = true;
  60499. /**
  60500. * This a counter ofr your own usage. It's not set by any SPS functions.
  60501. */
  60502. this.counter = 0;
  60503. /**
  60504. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60505. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60506. */
  60507. this.vars = {};
  60508. /**
  60509. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60510. */
  60511. this._bSphereOnly = false;
  60512. /**
  60513. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60514. */
  60515. this._bSphereRadiusFactor = 1.0;
  60516. this._positions = new Array();
  60517. this._indices = new Array();
  60518. this._normals = new Array();
  60519. this._colors = new Array();
  60520. this._uvs = new Array();
  60521. this._index = 0; // indices index
  60522. this._updatable = true;
  60523. this._pickable = false;
  60524. this._isVisibilityBoxLocked = false;
  60525. this._alwaysVisible = false;
  60526. this._depthSort = false;
  60527. this._shapeCounter = 0;
  60528. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60529. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60530. this._computeParticleColor = true;
  60531. this._computeParticleTexture = true;
  60532. this._computeParticleRotation = true;
  60533. this._computeParticleVertex = false;
  60534. this._computeBoundingBox = false;
  60535. this._depthSortParticles = true;
  60536. this._cam_axisZ = BABYLON.Vector3.Zero();
  60537. this._cam_axisY = BABYLON.Vector3.Zero();
  60538. this._cam_axisX = BABYLON.Vector3.Zero();
  60539. this._axisZ = BABYLON.Axis.Z;
  60540. this._camDir = BABYLON.Vector3.Zero();
  60541. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60542. this._rotMatrix = new BABYLON.Matrix();
  60543. this._invertMatrix = new BABYLON.Matrix();
  60544. this._rotated = BABYLON.Vector3.Zero();
  60545. this._quaternion = new BABYLON.Quaternion();
  60546. this._vertex = BABYLON.Vector3.Zero();
  60547. this._normal = BABYLON.Vector3.Zero();
  60548. this._yaw = 0.0;
  60549. this._pitch = 0.0;
  60550. this._roll = 0.0;
  60551. this._halfroll = 0.0;
  60552. this._halfpitch = 0.0;
  60553. this._halfyaw = 0.0;
  60554. this._sinRoll = 0.0;
  60555. this._cosRoll = 0.0;
  60556. this._sinPitch = 0.0;
  60557. this._cosPitch = 0.0;
  60558. this._sinYaw = 0.0;
  60559. this._cosYaw = 0.0;
  60560. this._mustUnrotateFixedNormals = false;
  60561. this._minimum = BABYLON.Vector3.Zero();
  60562. this._maximum = BABYLON.Vector3.Zero();
  60563. this._minBbox = BABYLON.Vector3.Zero();
  60564. this._maxBbox = BABYLON.Vector3.Zero();
  60565. this._particlesIntersect = false;
  60566. this._depthSortFunction = function (p1, p2) {
  60567. return (p2.sqDistance - p1.sqDistance);
  60568. };
  60569. this._needs32Bits = false;
  60570. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60571. this._scaledPivot = BABYLON.Vector3.Zero();
  60572. this._particleHasParent = false;
  60573. this.name = name;
  60574. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60575. this._camera = scene.activeCamera;
  60576. this._pickable = options ? options.isPickable : false;
  60577. this._depthSort = options ? options.enableDepthSort : false;
  60578. this._particlesIntersect = options ? options.particleIntersection : false;
  60579. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60580. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60581. if (options && options.updatable !== undefined) {
  60582. this._updatable = options.updatable;
  60583. }
  60584. else {
  60585. this._updatable = true;
  60586. }
  60587. if (this._pickable) {
  60588. this.pickedParticles = [];
  60589. }
  60590. if (this._depthSort) {
  60591. this.depthSortedParticles = [];
  60592. }
  60593. }
  60594. /**
  60595. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60596. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60597. * @returns the created mesh
  60598. */
  60599. SolidParticleSystem.prototype.buildMesh = function () {
  60600. if (this.nbParticles === 0) {
  60601. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60602. this.addShape(triangle, 1);
  60603. triangle.dispose();
  60604. }
  60605. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60606. this._positions32 = new Float32Array(this._positions);
  60607. this._uvs32 = new Float32Array(this._uvs);
  60608. this._colors32 = new Float32Array(this._colors);
  60609. if (this.recomputeNormals) {
  60610. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60611. }
  60612. this._normals32 = new Float32Array(this._normals);
  60613. this._fixedNormal32 = new Float32Array(this._normals);
  60614. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60615. this._unrotateFixedNormals();
  60616. }
  60617. var vertexData = new BABYLON.VertexData();
  60618. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60619. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60620. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60621. if (this._uvs32.length > 0) {
  60622. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60623. }
  60624. if (this._colors32.length > 0) {
  60625. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60626. }
  60627. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60628. vertexData.applyToMesh(mesh, this._updatable);
  60629. this.mesh = mesh;
  60630. this.mesh.isPickable = this._pickable;
  60631. // free memory
  60632. if (!this._depthSort) {
  60633. this._indices = null;
  60634. }
  60635. this._positions = null;
  60636. this._normals = null;
  60637. this._uvs = null;
  60638. this._colors = null;
  60639. if (!this._updatable) {
  60640. this.particles.length = 0;
  60641. }
  60642. return mesh;
  60643. };
  60644. /**
  60645. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60646. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60647. * Thus the particles generated from `digest()` have their property `position` set yet.
  60648. * @param mesh ( Mesh ) is the mesh to be digested
  60649. * @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
  60650. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60651. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  60652. * @returns the current SPS
  60653. */
  60654. SolidParticleSystem.prototype.digest = function (mesh, options) {
  60655. var size = (options && options.facetNb) || 1;
  60656. var number = (options && options.number) || 0;
  60657. var delta = (options && options.delta) || 0;
  60658. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60659. var meshInd = mesh.getIndices();
  60660. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60661. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60662. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60663. var f = 0; // facet counter
  60664. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  60665. // compute size from number
  60666. if (number) {
  60667. number = (number > totalFacets) ? totalFacets : number;
  60668. size = Math.round(totalFacets / number);
  60669. delta = 0;
  60670. }
  60671. else {
  60672. size = (size > totalFacets) ? totalFacets : size;
  60673. }
  60674. var facetPos = []; // submesh positions
  60675. var facetInd = []; // submesh indices
  60676. var facetUV = []; // submesh UV
  60677. var facetCol = []; // submesh colors
  60678. var barycenter = BABYLON.Vector3.Zero();
  60679. var sizeO = size;
  60680. while (f < totalFacets) {
  60681. size = sizeO + Math.floor((1 + delta) * Math.random());
  60682. if (f > totalFacets - size) {
  60683. size = totalFacets - f;
  60684. }
  60685. // reset temp arrays
  60686. facetPos.length = 0;
  60687. facetInd.length = 0;
  60688. facetUV.length = 0;
  60689. facetCol.length = 0;
  60690. // iterate over "size" facets
  60691. var fi = 0;
  60692. for (var j = f * 3; j < (f + size) * 3; j++) {
  60693. facetInd.push(fi);
  60694. var i = meshInd[j];
  60695. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  60696. if (meshUV) {
  60697. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  60698. }
  60699. if (meshCol) {
  60700. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  60701. }
  60702. fi++;
  60703. }
  60704. // create a model shape for each single particle
  60705. var idx = this.nbParticles;
  60706. var shape = this._posToShape(facetPos);
  60707. var shapeUV = this._uvsToShapeUV(facetUV);
  60708. // compute the barycenter of the shape
  60709. var v;
  60710. for (v = 0; v < shape.length; v++) {
  60711. barycenter.addInPlace(shape[v]);
  60712. }
  60713. barycenter.scaleInPlace(1 / shape.length);
  60714. // shift the shape from its barycenter to the origin
  60715. for (v = 0; v < shape.length; v++) {
  60716. shape[v].subtractInPlace(barycenter);
  60717. }
  60718. var bInfo;
  60719. if (this._particlesIntersect) {
  60720. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  60721. }
  60722. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  60723. // add the particle in the SPS
  60724. var currentPos = this._positions.length;
  60725. var currentInd = this._indices.length;
  60726. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  60727. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  60728. // initialize the particle position
  60729. this.particles[this.nbParticles].position.addInPlace(barycenter);
  60730. this._index += shape.length;
  60731. idx++;
  60732. this.nbParticles++;
  60733. this._shapeCounter++;
  60734. f += size;
  60735. }
  60736. return this;
  60737. };
  60738. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  60739. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  60740. var index = 0;
  60741. var idx = 0;
  60742. for (var p = 0; p < this.particles.length; p++) {
  60743. this._particle = this.particles[p];
  60744. this._shape = this._particle._model._shape;
  60745. if (this._particle.rotationQuaternion) {
  60746. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  60747. }
  60748. else {
  60749. this._yaw = this._particle.rotation.y;
  60750. this._pitch = this._particle.rotation.x;
  60751. this._roll = this._particle.rotation.z;
  60752. this._quaternionRotationYPR();
  60753. }
  60754. this._quaternionToRotationMatrix();
  60755. this._rotMatrix.invertToRef(this._invertMatrix);
  60756. for (var pt = 0; pt < this._shape.length; pt++) {
  60757. idx = index + pt * 3;
  60758. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  60759. this._fixedNormal32[idx] = this._normal.x;
  60760. this._fixedNormal32[idx + 1] = this._normal.y;
  60761. this._fixedNormal32[idx + 2] = this._normal.z;
  60762. }
  60763. index = idx + 3;
  60764. }
  60765. };
  60766. //reset copy
  60767. SolidParticleSystem.prototype._resetCopy = function () {
  60768. this._copy.position.x = 0;
  60769. this._copy.position.y = 0;
  60770. this._copy.position.z = 0;
  60771. this._copy.rotation.x = 0;
  60772. this._copy.rotation.y = 0;
  60773. this._copy.rotation.z = 0;
  60774. this._copy.rotationQuaternion = null;
  60775. this._copy.scaling.x = 1.0;
  60776. this._copy.scaling.y = 1.0;
  60777. this._copy.scaling.z = 1.0;
  60778. this._copy.uvs.x = 0;
  60779. this._copy.uvs.y = 0;
  60780. this._copy.uvs.z = 1.0;
  60781. this._copy.uvs.w = 1.0;
  60782. this._copy.color = null;
  60783. this._copy.translateFromPivot = false;
  60784. };
  60785. // _meshBuilder : inserts the shape model in the global SPS mesh
  60786. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  60787. var i;
  60788. var u = 0;
  60789. var c = 0;
  60790. var n = 0;
  60791. this._resetCopy();
  60792. if (options && options.positionFunction) { // call to custom positionFunction
  60793. options.positionFunction(this._copy, idx, idxInShape);
  60794. this._mustUnrotateFixedNormals = true;
  60795. }
  60796. if (this._copy.rotationQuaternion) {
  60797. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  60798. }
  60799. else {
  60800. this._yaw = this._copy.rotation.y;
  60801. this._pitch = this._copy.rotation.x;
  60802. this._roll = this._copy.rotation.z;
  60803. this._quaternionRotationYPR();
  60804. }
  60805. this._quaternionToRotationMatrix();
  60806. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  60807. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  60808. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  60809. if (this._copy.translateFromPivot) {
  60810. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  60811. }
  60812. else {
  60813. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  60814. }
  60815. for (i = 0; i < shape.length; i++) {
  60816. this._vertex.x = shape[i].x;
  60817. this._vertex.y = shape[i].y;
  60818. this._vertex.z = shape[i].z;
  60819. if (options && options.vertexFunction) {
  60820. options.vertexFunction(this._copy, this._vertex, i);
  60821. }
  60822. this._vertex.x *= this._copy.scaling.x;
  60823. this._vertex.y *= this._copy.scaling.y;
  60824. this._vertex.z *= this._copy.scaling.z;
  60825. this._vertex.x -= this._scaledPivot.x;
  60826. this._vertex.y -= this._scaledPivot.y;
  60827. this._vertex.z -= this._scaledPivot.z;
  60828. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  60829. this._rotated.addInPlace(this._pivotBackTranslation);
  60830. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  60831. if (meshUV) {
  60832. 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);
  60833. u += 2;
  60834. }
  60835. if (this._copy.color) {
  60836. this._color = this._copy.color;
  60837. }
  60838. else if (meshCol && meshCol[c] !== undefined) {
  60839. this._color.r = meshCol[c];
  60840. this._color.g = meshCol[c + 1];
  60841. this._color.b = meshCol[c + 2];
  60842. this._color.a = meshCol[c + 3];
  60843. }
  60844. else {
  60845. this._color.r = 1.0;
  60846. this._color.g = 1.0;
  60847. this._color.b = 1.0;
  60848. this._color.a = 1.0;
  60849. }
  60850. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  60851. c += 4;
  60852. if (!this.recomputeNormals && meshNor) {
  60853. this._normal.x = meshNor[n];
  60854. this._normal.y = meshNor[n + 1];
  60855. this._normal.z = meshNor[n + 2];
  60856. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  60857. normals.push(this._normal.x, this._normal.y, this._normal.z);
  60858. n += 3;
  60859. }
  60860. }
  60861. for (i = 0; i < meshInd.length; i++) {
  60862. var current_ind = p + meshInd[i];
  60863. indices.push(current_ind);
  60864. if (current_ind > 65535) {
  60865. this._needs32Bits = true;
  60866. }
  60867. }
  60868. if (this._pickable) {
  60869. var nbfaces = meshInd.length / 3;
  60870. for (i = 0; i < nbfaces; i++) {
  60871. this.pickedParticles.push({ idx: idx, faceId: i });
  60872. }
  60873. }
  60874. if (this._depthSort) {
  60875. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  60876. }
  60877. return this._copy;
  60878. };
  60879. // returns a shape array from positions array
  60880. SolidParticleSystem.prototype._posToShape = function (positions) {
  60881. var shape = [];
  60882. for (var i = 0; i < positions.length; i += 3) {
  60883. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  60884. }
  60885. return shape;
  60886. };
  60887. // returns a shapeUV array from a Vector4 uvs
  60888. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  60889. var shapeUV = [];
  60890. if (uvs) {
  60891. for (var i = 0; i < uvs.length; i++)
  60892. shapeUV.push(uvs[i]);
  60893. }
  60894. return shapeUV;
  60895. };
  60896. // adds a new particle object in the particles array
  60897. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  60898. if (bInfo === void 0) { bInfo = null; }
  60899. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  60900. this.particles.push(sp);
  60901. return sp;
  60902. };
  60903. /**
  60904. * Adds some particles to the SPS from the model shape. Returns the shape id.
  60905. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  60906. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  60907. * @param nb (positive integer) the number of particles to be created from this model
  60908. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  60909. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  60910. * @returns the number of shapes in the system
  60911. */
  60912. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  60913. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60914. var meshInd = mesh.getIndices();
  60915. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60916. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60917. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60918. var bbInfo;
  60919. if (this._particlesIntersect) {
  60920. bbInfo = mesh.getBoundingInfo();
  60921. }
  60922. var shape = this._posToShape(meshPos);
  60923. var shapeUV = this._uvsToShapeUV(meshUV);
  60924. var posfunc = options ? options.positionFunction : null;
  60925. var vtxfunc = options ? options.vertexFunction : null;
  60926. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  60927. // particles
  60928. var sp;
  60929. var currentCopy;
  60930. var idx = this.nbParticles;
  60931. for (var i = 0; i < nb; i++) {
  60932. var currentPos = this._positions.length;
  60933. var currentInd = this._indices.length;
  60934. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  60935. if (this._updatable) {
  60936. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  60937. sp.position.copyFrom(currentCopy.position);
  60938. sp.rotation.copyFrom(currentCopy.rotation);
  60939. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  60940. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  60941. }
  60942. if (currentCopy.color && sp.color) {
  60943. sp.color.copyFrom(currentCopy.color);
  60944. }
  60945. sp.scaling.copyFrom(currentCopy.scaling);
  60946. sp.uvs.copyFrom(currentCopy.uvs);
  60947. }
  60948. this._index += shape.length;
  60949. idx++;
  60950. }
  60951. this.nbParticles += nb;
  60952. this._shapeCounter++;
  60953. return this._shapeCounter - 1;
  60954. };
  60955. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  60956. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  60957. this._resetCopy();
  60958. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  60959. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  60960. }
  60961. if (this._copy.rotationQuaternion) {
  60962. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  60963. }
  60964. else {
  60965. this._yaw = this._copy.rotation.y;
  60966. this._pitch = this._copy.rotation.x;
  60967. this._roll = this._copy.rotation.z;
  60968. this._quaternionRotationYPR();
  60969. }
  60970. this._quaternionToRotationMatrix();
  60971. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  60972. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  60973. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  60974. if (this._copy.translateFromPivot) {
  60975. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  60976. }
  60977. else {
  60978. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  60979. }
  60980. this._shape = particle._model._shape;
  60981. for (var pt = 0; pt < this._shape.length; pt++) {
  60982. this._vertex.x = this._shape[pt].x;
  60983. this._vertex.y = this._shape[pt].y;
  60984. this._vertex.z = this._shape[pt].z;
  60985. if (particle._model._vertexFunction) {
  60986. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  60987. }
  60988. this._vertex.x *= this._copy.scaling.x;
  60989. this._vertex.y *= this._copy.scaling.y;
  60990. this._vertex.z *= this._copy.scaling.z;
  60991. this._vertex.x -= this._scaledPivot.x;
  60992. this._vertex.y -= this._scaledPivot.y;
  60993. this._vertex.z -= this._scaledPivot.z;
  60994. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  60995. this._rotated.addInPlace(this._pivotBackTranslation);
  60996. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  60997. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  60998. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  60999. }
  61000. particle.position.x = 0.0;
  61001. particle.position.y = 0.0;
  61002. particle.position.z = 0.0;
  61003. particle.rotation.x = 0.0;
  61004. particle.rotation.y = 0.0;
  61005. particle.rotation.z = 0.0;
  61006. particle.rotationQuaternion = null;
  61007. particle.scaling.x = 1.0;
  61008. particle.scaling.y = 1.0;
  61009. particle.scaling.z = 1.0;
  61010. particle.uvs.x = 0.0;
  61011. particle.uvs.y = 0.0;
  61012. particle.uvs.z = 1.0;
  61013. particle.uvs.w = 1.0;
  61014. particle.pivot.x = 0.0;
  61015. particle.pivot.y = 0.0;
  61016. particle.pivot.z = 0.0;
  61017. particle.translateFromPivot = false;
  61018. particle.parentId = null;
  61019. };
  61020. /**
  61021. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61022. * @returns the SPS.
  61023. */
  61024. SolidParticleSystem.prototype.rebuildMesh = function () {
  61025. for (var p = 0; p < this.particles.length; p++) {
  61026. this._rebuildParticle(this.particles[p]);
  61027. }
  61028. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61029. return this;
  61030. };
  61031. /**
  61032. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61033. * This method calls `updateParticle()` for each particle of the SPS.
  61034. * For an animated SPS, it is usually called within the render loop.
  61035. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61036. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61037. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61038. * @returns the SPS.
  61039. */
  61040. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61041. if (start === void 0) { start = 0; }
  61042. if (end === void 0) { end = this.nbParticles - 1; }
  61043. if (update === void 0) { update = true; }
  61044. if (!this._updatable) {
  61045. return this;
  61046. }
  61047. // custom beforeUpdate
  61048. this.beforeUpdateParticles(start, end, update);
  61049. this._cam_axisX.x = 1.0;
  61050. this._cam_axisX.y = 0.0;
  61051. this._cam_axisX.z = 0.0;
  61052. this._cam_axisY.x = 0.0;
  61053. this._cam_axisY.y = 1.0;
  61054. this._cam_axisY.z = 0.0;
  61055. this._cam_axisZ.x = 0.0;
  61056. this._cam_axisZ.y = 0.0;
  61057. this._cam_axisZ.z = 1.0;
  61058. // cases when the World Matrix is to be computed first
  61059. if (this.billboard || this._depthSort) {
  61060. this.mesh.computeWorldMatrix(true);
  61061. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61062. }
  61063. // if the particles will always face the camera
  61064. if (this.billboard) {
  61065. // compute the camera position and un-rotate it by the current mesh rotation
  61066. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61067. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61068. this._cam_axisZ.normalize();
  61069. // same for camera up vector extracted from the cam view matrix
  61070. var view = this._camera.getViewMatrix(true);
  61071. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61072. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61073. this._cam_axisY.normalize();
  61074. this._cam_axisX.normalize();
  61075. }
  61076. // if depthSort, compute the camera global position in the mesh local system
  61077. if (this._depthSort) {
  61078. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61079. }
  61080. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61081. var idx = 0; // current position index in the global array positions32
  61082. var index = 0; // position start index in the global array positions32 of the current particle
  61083. var colidx = 0; // current color index in the global array colors32
  61084. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61085. var uvidx = 0; // current uv index in the global array uvs32
  61086. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61087. var pt = 0; // current index in the particle model shape
  61088. if (this.mesh.isFacetDataEnabled) {
  61089. this._computeBoundingBox = true;
  61090. }
  61091. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61092. if (this._computeBoundingBox) {
  61093. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61094. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61095. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61096. }
  61097. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61098. if (this.mesh._boundingInfo) {
  61099. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61100. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61101. }
  61102. }
  61103. }
  61104. // particle loop
  61105. index = this.particles[start]._pos;
  61106. var vpos = (index / 3) | 0;
  61107. colorIndex = vpos * 4;
  61108. uvIndex = vpos * 2;
  61109. for (var p = start; p <= end; p++) {
  61110. this._particle = this.particles[p];
  61111. this._shape = this._particle._model._shape;
  61112. this._shapeUV = this._particle._model._shapeUV;
  61113. // call to custom user function to update the particle properties
  61114. this.updateParticle(this._particle);
  61115. // camera-particle distance for depth sorting
  61116. if (this._depthSort && this._depthSortParticles) {
  61117. var dsp = this.depthSortedParticles[p];
  61118. dsp.ind = this._particle._ind;
  61119. dsp.indicesLength = this._particle._model._indicesLength;
  61120. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61121. }
  61122. // skip the computations for inactive or already invisible particles
  61123. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61124. // increment indexes for the next particle
  61125. pt = this._shape.length;
  61126. index += pt * 3;
  61127. colorIndex += pt * 4;
  61128. uvIndex += pt * 2;
  61129. continue;
  61130. }
  61131. if (this._particle.isVisible) {
  61132. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61133. this._particleHasParent = (this._particle.parentId !== null);
  61134. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61135. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61136. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61137. // particle rotation matrix
  61138. if (this.billboard) {
  61139. this._particle.rotation.x = 0.0;
  61140. this._particle.rotation.y = 0.0;
  61141. }
  61142. if (this._computeParticleRotation || this.billboard) {
  61143. if (this._particle.rotationQuaternion) {
  61144. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61145. }
  61146. else {
  61147. this._yaw = this._particle.rotation.y;
  61148. this._pitch = this._particle.rotation.x;
  61149. this._roll = this._particle.rotation.z;
  61150. this._quaternionRotationYPR();
  61151. }
  61152. this._quaternionToRotationMatrix();
  61153. }
  61154. if (this._particleHasParent) {
  61155. this._parent = this.particles[this._particle.parentId];
  61156. 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];
  61157. 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];
  61158. 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];
  61159. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61160. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61161. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61162. if (this._computeParticleRotation || this.billboard) {
  61163. 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];
  61164. 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];
  61165. 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];
  61166. 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];
  61167. 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];
  61168. 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];
  61169. 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];
  61170. 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];
  61171. 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];
  61172. }
  61173. }
  61174. else {
  61175. this._particle._globalPosition.x = this._particle.position.x;
  61176. this._particle._globalPosition.y = this._particle.position.y;
  61177. this._particle._globalPosition.z = this._particle.position.z;
  61178. if (this._computeParticleRotation || this.billboard) {
  61179. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61180. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61181. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61182. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61183. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61184. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61185. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61186. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61187. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61188. }
  61189. }
  61190. if (this._particle.translateFromPivot) {
  61191. this._pivotBackTranslation.x = 0.0;
  61192. this._pivotBackTranslation.y = 0.0;
  61193. this._pivotBackTranslation.z = 0.0;
  61194. }
  61195. else {
  61196. this._pivotBackTranslation.x = this._scaledPivot.x;
  61197. this._pivotBackTranslation.y = this._scaledPivot.y;
  61198. this._pivotBackTranslation.z = this._scaledPivot.z;
  61199. }
  61200. // particle vertex loop
  61201. for (pt = 0; pt < this._shape.length; pt++) {
  61202. idx = index + pt * 3;
  61203. colidx = colorIndex + pt * 4;
  61204. uvidx = uvIndex + pt * 2;
  61205. this._vertex.x = this._shape[pt].x;
  61206. this._vertex.y = this._shape[pt].y;
  61207. this._vertex.z = this._shape[pt].z;
  61208. if (this._computeParticleVertex) {
  61209. this.updateParticleVertex(this._particle, this._vertex, pt);
  61210. }
  61211. // positions
  61212. this._vertex.x *= this._particle.scaling.x;
  61213. this._vertex.y *= this._particle.scaling.y;
  61214. this._vertex.z *= this._particle.scaling.z;
  61215. this._vertex.x -= this._scaledPivot.x;
  61216. this._vertex.y -= this._scaledPivot.y;
  61217. this._vertex.z -= this._scaledPivot.z;
  61218. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61219. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61220. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61221. this._rotated.x += this._pivotBackTranslation.x;
  61222. this._rotated.y += this._pivotBackTranslation.y;
  61223. this._rotated.z += this._pivotBackTranslation.z;
  61224. 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;
  61225. 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;
  61226. 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;
  61227. if (this._computeBoundingBox) {
  61228. if (this._positions32[idx] < this._minimum.x) {
  61229. this._minimum.x = this._positions32[idx];
  61230. }
  61231. if (this._positions32[idx] > this._maximum.x) {
  61232. this._maximum.x = this._positions32[idx];
  61233. }
  61234. if (this._positions32[idx + 1] < this._minimum.y) {
  61235. this._minimum.y = this._positions32[idx + 1];
  61236. }
  61237. if (this._positions32[idx + 1] > this._maximum.y) {
  61238. this._maximum.y = this._positions32[idx + 1];
  61239. }
  61240. if (this._positions32[idx + 2] < this._minimum.z) {
  61241. this._minimum.z = this._positions32[idx + 2];
  61242. }
  61243. if (this._positions32[idx + 2] > this._maximum.z) {
  61244. this._maximum.z = this._positions32[idx + 2];
  61245. }
  61246. }
  61247. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61248. if (!this._computeParticleVertex) {
  61249. this._normal.x = this._fixedNormal32[idx];
  61250. this._normal.y = this._fixedNormal32[idx + 1];
  61251. this._normal.z = this._fixedNormal32[idx + 2];
  61252. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61253. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61254. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61255. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61256. 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;
  61257. 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;
  61258. }
  61259. if (this._computeParticleColor && this._particle.color) {
  61260. this._colors32[colidx] = this._particle.color.r;
  61261. this._colors32[colidx + 1] = this._particle.color.g;
  61262. this._colors32[colidx + 2] = this._particle.color.b;
  61263. this._colors32[colidx + 3] = this._particle.color.a;
  61264. }
  61265. if (this._computeParticleTexture) {
  61266. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61267. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61268. }
  61269. }
  61270. }
  61271. // particle just set invisible : scaled to zero and positioned at the origin
  61272. else {
  61273. this._particle._stillInvisible = true; // mark the particle as invisible
  61274. for (pt = 0; pt < this._shape.length; pt++) {
  61275. idx = index + pt * 3;
  61276. colidx = colorIndex + pt * 4;
  61277. uvidx = uvIndex + pt * 2;
  61278. this._positions32[idx] = 0.0;
  61279. this._positions32[idx + 1] = 0.0;
  61280. this._positions32[idx + 2] = 0.0;
  61281. this._normals32[idx] = 0.0;
  61282. this._normals32[idx + 1] = 0.0;
  61283. this._normals32[idx + 2] = 0.0;
  61284. if (this._computeParticleColor && this._particle.color) {
  61285. this._colors32[colidx] = this._particle.color.r;
  61286. this._colors32[colidx + 1] = this._particle.color.g;
  61287. this._colors32[colidx + 2] = this._particle.color.b;
  61288. this._colors32[colidx + 3] = this._particle.color.a;
  61289. }
  61290. if (this._computeParticleTexture) {
  61291. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61292. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61293. }
  61294. }
  61295. }
  61296. // if the particle intersections must be computed : update the bbInfo
  61297. if (this._particlesIntersect) {
  61298. var bInfo = this._particle._boundingInfo;
  61299. var bBox = bInfo.boundingBox;
  61300. var bSphere = bInfo.boundingSphere;
  61301. if (!this._bSphereOnly) {
  61302. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61303. for (var b = 0; b < bBox.vectors.length; b++) {
  61304. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61305. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61306. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61307. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61308. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61309. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61310. 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;
  61311. 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;
  61312. 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;
  61313. }
  61314. bBox._update(this.mesh._worldMatrix);
  61315. }
  61316. // place and scale the particle bouding sphere in the SPS local system, then update it
  61317. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61318. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61319. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61320. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61321. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61322. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61323. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61324. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61325. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61326. 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));
  61327. bSphere._update(this.mesh._worldMatrix);
  61328. }
  61329. // increment indexes for the next particle
  61330. index = idx + 3;
  61331. colorIndex = colidx + 4;
  61332. uvIndex = uvidx + 2;
  61333. }
  61334. // if the VBO must be updated
  61335. if (update) {
  61336. if (this._computeParticleColor) {
  61337. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61338. }
  61339. if (this._computeParticleTexture) {
  61340. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61341. }
  61342. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61343. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61344. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61345. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61346. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61347. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61348. for (var i = 0; i < this._normals32.length; i++) {
  61349. this._fixedNormal32[i] = this._normals32[i];
  61350. }
  61351. }
  61352. if (!this.mesh.areNormalsFrozen) {
  61353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61354. }
  61355. }
  61356. if (this._depthSort && this._depthSortParticles) {
  61357. this.depthSortedParticles.sort(this._depthSortFunction);
  61358. var dspl = this.depthSortedParticles.length;
  61359. var sorted = 0;
  61360. var lind = 0;
  61361. var sind = 0;
  61362. var sid = 0;
  61363. for (sorted = 0; sorted < dspl; sorted++) {
  61364. lind = this.depthSortedParticles[sorted].indicesLength;
  61365. sind = this.depthSortedParticles[sorted].ind;
  61366. for (var i = 0; i < lind; i++) {
  61367. this._indices32[sid] = this._indices[sind + i];
  61368. sid++;
  61369. }
  61370. }
  61371. this.mesh.updateIndices(this._indices32);
  61372. }
  61373. }
  61374. if (this._computeBoundingBox) {
  61375. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61376. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61377. }
  61378. this.afterUpdateParticles(start, end, update);
  61379. return this;
  61380. };
  61381. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61382. this._halfroll = this._roll * 0.5;
  61383. this._halfpitch = this._pitch * 0.5;
  61384. this._halfyaw = this._yaw * 0.5;
  61385. this._sinRoll = Math.sin(this._halfroll);
  61386. this._cosRoll = Math.cos(this._halfroll);
  61387. this._sinPitch = Math.sin(this._halfpitch);
  61388. this._cosPitch = Math.cos(this._halfpitch);
  61389. this._sinYaw = Math.sin(this._halfyaw);
  61390. this._cosYaw = Math.cos(this._halfyaw);
  61391. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61392. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61393. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61394. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61395. };
  61396. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61397. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61398. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61399. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61400. this._rotMatrix.m[3] = 0;
  61401. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61402. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61403. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61404. this._rotMatrix.m[7] = 0;
  61405. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61406. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61407. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61408. this._rotMatrix.m[11] = 0;
  61409. this._rotMatrix.m[12] = 0;
  61410. this._rotMatrix.m[13] = 0;
  61411. this._rotMatrix.m[14] = 0;
  61412. this._rotMatrix.m[15] = 1.0;
  61413. };
  61414. /**
  61415. * Disposes the SPS.
  61416. */
  61417. SolidParticleSystem.prototype.dispose = function () {
  61418. this.mesh.dispose();
  61419. this.vars = null;
  61420. // drop references to internal big arrays for the GC
  61421. this._positions = null;
  61422. this._indices = null;
  61423. this._normals = null;
  61424. this._uvs = null;
  61425. this._colors = null;
  61426. this._indices32 = null;
  61427. this._positions32 = null;
  61428. this._normals32 = null;
  61429. this._fixedNormal32 = null;
  61430. this._uvs32 = null;
  61431. this._colors32 = null;
  61432. this.pickedParticles = null;
  61433. };
  61434. /**
  61435. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61437. * @returns the SPS.
  61438. */
  61439. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61440. if (!this._isVisibilityBoxLocked) {
  61441. this.mesh.refreshBoundingInfo();
  61442. }
  61443. return this;
  61444. };
  61445. /**
  61446. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61447. * @param size the size (float) of the visibility box
  61448. * note : this doesn't lock the SPS mesh bounding box.
  61449. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61450. */
  61451. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61452. var vis = size / 2;
  61453. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61454. };
  61455. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61456. /**
  61457. * Gets whether the SPS as always visible or not
  61458. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61459. */
  61460. get: function () {
  61461. return this._alwaysVisible;
  61462. },
  61463. /**
  61464. * Sets the SPS as always visible or not
  61465. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61466. */
  61467. set: function (val) {
  61468. this._alwaysVisible = val;
  61469. this.mesh.alwaysSelectAsActiveMesh = val;
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61475. /**
  61476. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61477. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61478. */
  61479. get: function () {
  61480. return this._isVisibilityBoxLocked;
  61481. },
  61482. /**
  61483. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61484. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61485. */
  61486. set: function (val) {
  61487. this._isVisibilityBoxLocked = val;
  61488. var boundingInfo = this.mesh.getBoundingInfo();
  61489. boundingInfo.isLocked = val;
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61495. /**
  61496. * Gets if `setParticles()` computes the particle rotations or not.
  61497. * Default value : true. The SPS is faster when it's set to false.
  61498. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61499. */
  61500. get: function () {
  61501. return this._computeParticleRotation;
  61502. },
  61503. /**
  61504. * Tells to `setParticles()` to compute the particle rotations or not.
  61505. * Default value : true. The SPS is faster when it's set to false.
  61506. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61507. */
  61508. set: function (val) {
  61509. this._computeParticleRotation = val;
  61510. },
  61511. enumerable: true,
  61512. configurable: true
  61513. });
  61514. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61515. /**
  61516. * Gets if `setParticles()` computes the particle colors or not.
  61517. * Default value : true. The SPS is faster when it's set to false.
  61518. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61519. */
  61520. get: function () {
  61521. return this._computeParticleColor;
  61522. },
  61523. /**
  61524. * Tells to `setParticles()` to compute the particle colors or not.
  61525. * Default value : true. The SPS is faster when it's set to false.
  61526. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61527. */
  61528. set: function (val) {
  61529. this._computeParticleColor = val;
  61530. },
  61531. enumerable: true,
  61532. configurable: true
  61533. });
  61534. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61535. /**
  61536. * Gets if `setParticles()` computes the particle textures or not.
  61537. * Default value : true. The SPS is faster when it's set to false.
  61538. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61539. */
  61540. get: function () {
  61541. return this._computeParticleTexture;
  61542. },
  61543. set: function (val) {
  61544. this._computeParticleTexture = val;
  61545. },
  61546. enumerable: true,
  61547. configurable: true
  61548. });
  61549. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61550. /**
  61551. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61552. * Default value : false. The SPS is faster when it's set to false.
  61553. * Note : the particle custom vertex positions aren't stored values.
  61554. */
  61555. get: function () {
  61556. return this._computeParticleVertex;
  61557. },
  61558. /**
  61559. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61560. * Default value : false. The SPS is faster when it's set to false.
  61561. * Note : the particle custom vertex positions aren't stored values.
  61562. */
  61563. set: function (val) {
  61564. this._computeParticleVertex = val;
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61570. /**
  61571. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61572. */
  61573. get: function () {
  61574. return this._computeBoundingBox;
  61575. },
  61576. /**
  61577. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61578. */
  61579. set: function (val) {
  61580. this._computeBoundingBox = val;
  61581. },
  61582. enumerable: true,
  61583. configurable: true
  61584. });
  61585. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61586. /**
  61587. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61588. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61589. * Default : `true`
  61590. */
  61591. get: function () {
  61592. return this._depthSortParticles;
  61593. },
  61594. /**
  61595. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61596. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61597. * Default : `true`
  61598. */
  61599. set: function (val) {
  61600. this._depthSortParticles = val;
  61601. },
  61602. enumerable: true,
  61603. configurable: true
  61604. });
  61605. // =======================================================================
  61606. // Particle behavior logic
  61607. // these following methods may be overwritten by the user to fit his needs
  61608. /**
  61609. * This function does nothing. It may be overwritten to set all the particle first values.
  61610. * The SPS doesn't call this function, you may have to call it by your own.
  61611. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61612. */
  61613. SolidParticleSystem.prototype.initParticles = function () {
  61614. };
  61615. /**
  61616. * This function does nothing. It may be overwritten to recycle a particle.
  61617. * The SPS doesn't call this function, you may have to call it by your own.
  61618. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61619. * @param particle The particle to recycle
  61620. * @returns the recycled particle
  61621. */
  61622. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61623. return particle;
  61624. };
  61625. /**
  61626. * Updates a particle : this function should be overwritten by the user.
  61627. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61628. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61629. * @example : just set a particle position or velocity and recycle conditions
  61630. * @param particle The particle to update
  61631. * @returns the updated particle
  61632. */
  61633. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61634. return particle;
  61635. };
  61636. /**
  61637. * Updates a vertex of a particle : it can be overwritten by the user.
  61638. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61639. * @param particle the current particle
  61640. * @param vertex the current index of the current particle
  61641. * @param pt the index of the current vertex in the particle shape
  61642. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61643. * @example : just set a vertex particle position
  61644. * @returns the updated vertex
  61645. */
  61646. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61647. return vertex;
  61648. };
  61649. /**
  61650. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61651. * This does nothing and may be overwritten by the user.
  61652. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61653. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61654. * @param update the boolean update value actually passed to setParticles()
  61655. */
  61656. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  61657. };
  61658. /**
  61659. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  61660. * This will be passed three parameters.
  61661. * This does nothing and may be overwritten by the user.
  61662. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61663. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61664. * @param update the boolean update value actually passed to setParticles()
  61665. */
  61666. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  61667. };
  61668. return SolidParticleSystem;
  61669. }());
  61670. BABYLON.SolidParticleSystem = SolidParticleSystem;
  61671. })(BABYLON || (BABYLON = {}));
  61672. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  61673. var BABYLON;
  61674. (function (BABYLON) {
  61675. /**
  61676. * Class containing static functions to help procedurally build meshes
  61677. */
  61678. var MeshBuilder = /** @class */ (function () {
  61679. function MeshBuilder() {
  61680. }
  61681. MeshBuilder.updateSideOrientation = function (orientation) {
  61682. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61683. return BABYLON.Mesh.DOUBLESIDE;
  61684. }
  61685. if (orientation === undefined || orientation === null) {
  61686. return BABYLON.Mesh.FRONTSIDE;
  61687. }
  61688. return orientation;
  61689. };
  61690. /**
  61691. * Creates a box mesh
  61692. * * The parameter `size` sets the size (float) of each box side (default 1)
  61693. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61694. * * 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)
  61695. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61696. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61697. * * 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
  61698. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61699. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61700. * @param name defines the name of the mesh
  61701. * @param options defines the options used to create the mesh
  61702. * @param scene defines the hosting scene
  61703. * @returns the box mesh
  61704. */
  61705. MeshBuilder.CreateBox = function (name, options, scene) {
  61706. if (scene === void 0) { scene = null; }
  61707. var box = new BABYLON.Mesh(name, scene);
  61708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61709. box._originalBuilderSideOrientation = options.sideOrientation;
  61710. var vertexData = BABYLON.VertexData.CreateBox(options);
  61711. vertexData.applyToMesh(box, options.updatable);
  61712. return box;
  61713. };
  61714. /**
  61715. * Creates a sphere mesh
  61716. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61717. * * 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`)
  61718. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61719. * * 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
  61720. * * 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)
  61721. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61722. * * 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
  61723. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61724. * @param name defines the name of the mesh
  61725. * @param options defines the options used to create the mesh
  61726. * @param scene defines the hosting scene
  61727. * @returns the sphere mesh
  61728. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61729. */
  61730. MeshBuilder.CreateSphere = function (name, options, scene) {
  61731. var sphere = new BABYLON.Mesh(name, scene);
  61732. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61733. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61734. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61735. vertexData.applyToMesh(sphere, options.updatable);
  61736. return sphere;
  61737. };
  61738. /**
  61739. * Creates a plane polygonal mesh. By default, this is a disc
  61740. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61741. * * 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
  61742. * * 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
  61743. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61744. * * 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
  61745. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61746. * @param name defines the name of the mesh
  61747. * @param options defines the options used to create the mesh
  61748. * @param scene defines the hosting scene
  61749. * @returns the plane polygonal mesh
  61750. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61751. */
  61752. MeshBuilder.CreateDisc = function (name, options, scene) {
  61753. if (scene === void 0) { scene = null; }
  61754. var disc = new BABYLON.Mesh(name, scene);
  61755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61756. disc._originalBuilderSideOrientation = options.sideOrientation;
  61757. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61758. vertexData.applyToMesh(disc, options.updatable);
  61759. return disc;
  61760. };
  61761. /**
  61762. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61763. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61764. * * 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`)
  61765. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61766. * * 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
  61767. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61768. * * 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
  61769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61770. * @param name defines the name of the mesh
  61771. * @param options defines the options used to create the mesh
  61772. * @param scene defines the hosting scene
  61773. * @returns the icosahedron mesh
  61774. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61775. */
  61776. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61777. var sphere = new BABYLON.Mesh(name, scene);
  61778. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61779. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61780. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61781. vertexData.applyToMesh(sphere, options.updatable);
  61782. return sphere;
  61783. };
  61784. ;
  61785. /**
  61786. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61787. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61788. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61789. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61790. * * 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
  61791. * * 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
  61792. * * 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
  61793. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61794. * * 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
  61795. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61796. * * 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
  61797. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61798. * * 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
  61799. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61801. * @param name defines the name of the mesh
  61802. * @param options defines the options used to create the mesh
  61803. * @param scene defines the hosting scene
  61804. * @returns the ribbon mesh
  61805. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61806. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61807. */
  61808. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61809. if (scene === void 0) { scene = null; }
  61810. var pathArray = options.pathArray;
  61811. var closeArray = options.closeArray;
  61812. var closePath = options.closePath;
  61813. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61814. var instance = options.instance;
  61815. var updatable = options.updatable;
  61816. if (instance) { // existing ribbon instance update
  61817. // positionFunction : ribbon case
  61818. // only pathArray and sideOrientation parameters are taken into account for positions update
  61819. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61820. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61821. var positionFunction = function (positions) {
  61822. var minlg = pathArray[0].length;
  61823. var i = 0;
  61824. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61825. for (var si = 1; si <= ns; si++) {
  61826. for (var p = 0; p < pathArray.length; p++) {
  61827. var path = pathArray[p];
  61828. var l = path.length;
  61829. minlg = (minlg < l) ? minlg : l;
  61830. var j = 0;
  61831. while (j < minlg) {
  61832. positions[i] = path[j].x;
  61833. positions[i + 1] = path[j].y;
  61834. positions[i + 2] = path[j].z;
  61835. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61836. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61837. }
  61838. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61839. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61840. }
  61841. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61842. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61843. }
  61844. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61845. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61846. }
  61847. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61848. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61849. }
  61850. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61851. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61852. }
  61853. j++;
  61854. i += 3;
  61855. }
  61856. if (instance._closePath) {
  61857. positions[i] = path[0].x;
  61858. positions[i + 1] = path[0].y;
  61859. positions[i + 2] = path[0].z;
  61860. i += 3;
  61861. }
  61862. }
  61863. }
  61864. };
  61865. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61866. positionFunction(positions);
  61867. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61868. instance._boundingInfo.update(instance._worldMatrix);
  61869. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61870. if (options.colors) {
  61871. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61872. for (var c = 0; c < options.colors.length; c++) {
  61873. colors[c * 4] = options.colors[c].r;
  61874. colors[c * 4 + 1] = options.colors[c].g;
  61875. colors[c * 4 + 2] = options.colors[c].b;
  61876. colors[c * 4 + 3] = options.colors[c].a;
  61877. }
  61878. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61879. }
  61880. if (options.uvs) {
  61881. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61882. for (var i = 0; i < options.uvs.length; i++) {
  61883. uvs[i * 2] = options.uvs[i].x;
  61884. uvs[i * 2 + 1] = options.uvs[i].y;
  61885. }
  61886. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61887. }
  61888. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61889. var indices = instance.getIndices();
  61890. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61891. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61892. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61893. if (instance._closePath) {
  61894. var indexFirst = 0;
  61895. var indexLast = 0;
  61896. for (var p = 0; p < pathArray.length; p++) {
  61897. indexFirst = instance._idx[p] * 3;
  61898. if (p + 1 < pathArray.length) {
  61899. indexLast = (instance._idx[p + 1] - 1) * 3;
  61900. }
  61901. else {
  61902. indexLast = normals.length - 3;
  61903. }
  61904. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61905. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61906. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61907. normals[indexLast] = normals[indexFirst];
  61908. normals[indexLast + 1] = normals[indexFirst + 1];
  61909. normals[indexLast + 2] = normals[indexFirst + 2];
  61910. }
  61911. }
  61912. if (!(instance.areNormalsFrozen)) {
  61913. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61914. }
  61915. }
  61916. return instance;
  61917. }
  61918. else { // new ribbon creation
  61919. var ribbon = new BABYLON.Mesh(name, scene);
  61920. ribbon._originalBuilderSideOrientation = sideOrientation;
  61921. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61922. if (closePath) {
  61923. ribbon._idx = vertexData._idx;
  61924. }
  61925. ribbon._closePath = closePath;
  61926. ribbon._closeArray = closeArray;
  61927. vertexData.applyToMesh(ribbon, updatable);
  61928. return ribbon;
  61929. }
  61930. };
  61931. /**
  61932. * Creates a cylinder or a cone mesh
  61933. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61934. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61935. * * 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.
  61936. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61937. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61938. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61939. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61940. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61941. * * 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).
  61942. * * 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
  61943. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61944. * * 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
  61945. * * 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.
  61946. * * If `enclose` is false, a ring surface is one element.
  61947. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61948. * * 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
  61949. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61950. * * 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
  61951. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61952. * @param name defines the name of the mesh
  61953. * @param options defines the options used to create the mesh
  61954. * @param scene defines the hosting scene
  61955. * @returns the cylinder mesh
  61956. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61957. */
  61958. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61959. var cylinder = new BABYLON.Mesh(name, scene);
  61960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61961. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61962. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61963. vertexData.applyToMesh(cylinder, options.updatable);
  61964. return cylinder;
  61965. };
  61966. /**
  61967. * Creates a torus mesh
  61968. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61969. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61970. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61971. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61972. * * 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
  61973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61974. * @param name defines the name of the mesh
  61975. * @param options defines the options used to create the mesh
  61976. * @param scene defines the hosting scene
  61977. * @returns the torus mesh
  61978. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61979. */
  61980. MeshBuilder.CreateTorus = function (name, options, scene) {
  61981. var torus = new BABYLON.Mesh(name, scene);
  61982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61983. torus._originalBuilderSideOrientation = options.sideOrientation;
  61984. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61985. vertexData.applyToMesh(torus, options.updatable);
  61986. return torus;
  61987. };
  61988. /**
  61989. * Creates a torus knot mesh
  61990. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61991. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61992. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61993. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61994. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61995. * * 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
  61996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61997. * @param name defines the name of the mesh
  61998. * @param options defines the options used to create the mesh
  61999. * @param scene defines the hosting scene
  62000. * @returns the torus knot mesh
  62001. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62002. */
  62003. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62004. var torusKnot = new BABYLON.Mesh(name, scene);
  62005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62006. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62007. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62008. vertexData.applyToMesh(torusKnot, options.updatable);
  62009. return torusKnot;
  62010. };
  62011. /**
  62012. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62013. * * 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
  62014. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62015. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62016. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62017. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62018. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62019. * * 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
  62020. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62022. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62023. * @param name defines the name of the new line system
  62024. * @param options defines the options used to create the line system
  62025. * @param scene defines the hosting scene
  62026. * @returns a new line system mesh
  62027. */
  62028. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62029. var instance = options.instance;
  62030. var lines = options.lines;
  62031. var colors = options.colors;
  62032. if (instance) { // lines update
  62033. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62034. var vertexColor;
  62035. var lineColors;
  62036. if (colors) {
  62037. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62038. }
  62039. var i = 0;
  62040. var c = 0;
  62041. for (var l = 0; l < lines.length; l++) {
  62042. var points = lines[l];
  62043. for (var p = 0; p < points.length; p++) {
  62044. positions[i] = points[p].x;
  62045. positions[i + 1] = points[p].y;
  62046. positions[i + 2] = points[p].z;
  62047. if (colors && vertexColor) {
  62048. lineColors = colors[l];
  62049. vertexColor[c] = lineColors[p].r;
  62050. vertexColor[c + 1] = lineColors[p].g;
  62051. vertexColor[c + 2] = lineColors[p].b;
  62052. vertexColor[c + 3] = lineColors[p].a;
  62053. c += 4;
  62054. }
  62055. i += 3;
  62056. }
  62057. }
  62058. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62059. if (colors && vertexColor) {
  62060. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62061. }
  62062. return instance;
  62063. }
  62064. // line system creation
  62065. var useVertexColor = (colors) ? true : false;
  62066. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62067. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62068. vertexData.applyToMesh(lineSystem, options.updatable);
  62069. return lineSystem;
  62070. };
  62071. /**
  62072. * Creates a line mesh
  62073. * 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
  62074. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62075. * * The parameter `points` is an array successive Vector3
  62076. * * 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
  62077. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62078. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62079. * * When updating an instance, remember that only point positions can change, not the number of points
  62080. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62081. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62082. * @param name defines the name of the new line system
  62083. * @param options defines the options used to create the line system
  62084. * @param scene defines the hosting scene
  62085. * @returns a new line mesh
  62086. */
  62087. MeshBuilder.CreateLines = function (name, options, scene) {
  62088. if (scene === void 0) { scene = null; }
  62089. var colors = (options.colors) ? [options.colors] : null;
  62090. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62091. return lines;
  62092. };
  62093. /**
  62094. * Creates a dashed line mesh
  62095. * * 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
  62096. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62097. * * The parameter `points` is an array successive Vector3
  62098. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62099. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62100. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62101. * * 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
  62102. * * When updating an instance, remember that only point positions can change, not the number of points
  62103. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62104. * @param name defines the name of the mesh
  62105. * @param options defines the options used to create the mesh
  62106. * @param scene defines the hosting scene
  62107. * @returns the dashed line mesh
  62108. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62109. */
  62110. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62111. if (scene === void 0) { scene = null; }
  62112. var points = options.points;
  62113. var instance = options.instance;
  62114. var gapSize = options.gapSize || 1;
  62115. var dashSize = options.dashSize || 3;
  62116. if (instance) { // dashed lines update
  62117. var positionFunction = function (positions) {
  62118. var curvect = BABYLON.Vector3.Zero();
  62119. var nbSeg = positions.length / 6;
  62120. var lg = 0;
  62121. var nb = 0;
  62122. var shft = 0;
  62123. var dashshft = 0;
  62124. var curshft = 0;
  62125. var p = 0;
  62126. var i = 0;
  62127. var j = 0;
  62128. for (i = 0; i < points.length - 1; i++) {
  62129. points[i + 1].subtractToRef(points[i], curvect);
  62130. lg += curvect.length();
  62131. }
  62132. shft = lg / nbSeg;
  62133. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62134. for (i = 0; i < points.length - 1; i++) {
  62135. points[i + 1].subtractToRef(points[i], curvect);
  62136. nb = Math.floor(curvect.length() / shft);
  62137. curvect.normalize();
  62138. j = 0;
  62139. while (j < nb && p < positions.length) {
  62140. curshft = shft * j;
  62141. positions[p] = points[i].x + curshft * curvect.x;
  62142. positions[p + 1] = points[i].y + curshft * curvect.y;
  62143. positions[p + 2] = points[i].z + curshft * curvect.z;
  62144. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62145. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62146. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62147. p += 6;
  62148. j++;
  62149. }
  62150. }
  62151. while (p < positions.length) {
  62152. positions[p] = points[i].x;
  62153. positions[p + 1] = points[i].y;
  62154. positions[p + 2] = points[i].z;
  62155. p += 3;
  62156. }
  62157. };
  62158. instance.updateMeshPositions(positionFunction, false);
  62159. return instance;
  62160. }
  62161. // dashed lines creation
  62162. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62163. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62164. vertexData.applyToMesh(dashedLines, options.updatable);
  62165. dashedLines.dashSize = dashSize;
  62166. dashedLines.gapSize = gapSize;
  62167. return dashedLines;
  62168. };
  62169. /**
  62170. * 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.
  62171. * * 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.
  62172. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62173. * * 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.
  62174. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62175. * * 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
  62176. * * 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
  62177. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62179. * * 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
  62180. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62181. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62182. * @param name defines the name of the mesh
  62183. * @param options defines the options used to create the mesh
  62184. * @param scene defines the hosting scene
  62185. * @returns the extruded shape mesh
  62186. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62187. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62189. */
  62190. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62191. if (scene === void 0) { scene = null; }
  62192. var path = options.path;
  62193. var shape = options.shape;
  62194. var scale = options.scale || 1;
  62195. var rotation = options.rotation || 0;
  62196. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62197. var updatable = options.updatable;
  62198. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62199. var instance = options.instance || null;
  62200. var invertUV = options.invertUV || false;
  62201. 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);
  62202. };
  62203. /**
  62204. * Creates an custom extruded shape mesh.
  62205. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62206. * * 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.
  62207. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62208. * * 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
  62209. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62210. * * 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
  62211. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62212. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62213. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62214. * * 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
  62215. * * 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
  62216. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62217. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62218. * * 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
  62219. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62220. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62221. * @param name defines the name of the mesh
  62222. * @param options defines the options used to create the mesh
  62223. * @param scene defines the hosting scene
  62224. * @returns the custom extruded shape mesh
  62225. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62226. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62227. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62228. */
  62229. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62230. var path = options.path;
  62231. var shape = options.shape;
  62232. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62233. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62234. var ribbonCloseArray = options.ribbonCloseArray || false;
  62235. var ribbonClosePath = options.ribbonClosePath || false;
  62236. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62237. var updatable = options.updatable;
  62238. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62239. var instance = options.instance;
  62240. var invertUV = options.invertUV || false;
  62241. 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);
  62242. };
  62243. /**
  62244. * Creates lathe mesh.
  62245. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62246. * * 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
  62247. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62248. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62249. * * 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
  62250. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62251. * * 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
  62252. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62253. * * 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
  62254. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62256. * @param name defines the name of the mesh
  62257. * @param options defines the options used to create the mesh
  62258. * @param scene defines the hosting scene
  62259. * @returns the lathe mesh
  62260. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62261. */
  62262. MeshBuilder.CreateLathe = function (name, options, scene) {
  62263. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62264. var closed = (options.closed === undefined) ? true : options.closed;
  62265. var shape = options.shape;
  62266. var radius = options.radius || 1;
  62267. var tessellation = options.tessellation || 64;
  62268. var updatable = options.updatable;
  62269. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62270. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62271. var pi2 = Math.PI * 2;
  62272. var paths = new Array();
  62273. var invertUV = options.invertUV || false;
  62274. var i = 0;
  62275. var p = 0;
  62276. var step = pi2 / tessellation * arc;
  62277. var rotated;
  62278. var path = new Array();
  62279. for (i = 0; i <= tessellation; i++) {
  62280. var path = [];
  62281. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62282. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62283. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62284. }
  62285. for (p = 0; p < shape.length; p++) {
  62286. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62287. path.push(rotated);
  62288. }
  62289. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62290. 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));
  62291. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62292. }
  62293. paths.push(path);
  62294. }
  62295. // lathe ribbon
  62296. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62297. return lathe;
  62298. };
  62299. /**
  62300. * Creates a plane mesh
  62301. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62302. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62303. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62304. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62305. * * 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
  62306. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62307. * @param name defines the name of the mesh
  62308. * @param options defines the options used to create the mesh
  62309. * @param scene defines the hosting scene
  62310. * @returns the plane mesh
  62311. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62312. */
  62313. MeshBuilder.CreatePlane = function (name, options, scene) {
  62314. var plane = new BABYLON.Mesh(name, scene);
  62315. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62316. plane._originalBuilderSideOrientation = options.sideOrientation;
  62317. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62318. vertexData.applyToMesh(plane, options.updatable);
  62319. if (options.sourcePlane) {
  62320. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62321. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62322. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62323. plane.rotate(vectorProduct, product);
  62324. }
  62325. return plane;
  62326. };
  62327. /**
  62328. * Creates a ground mesh
  62329. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62330. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62332. * @param name defines the name of the mesh
  62333. * @param options defines the options used to create the mesh
  62334. * @param scene defines the hosting scene
  62335. * @returns the ground mesh
  62336. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62337. */
  62338. MeshBuilder.CreateGround = function (name, options, scene) {
  62339. var ground = new BABYLON.GroundMesh(name, scene);
  62340. ground._setReady(false);
  62341. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62342. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62343. ground._width = options.width || 1;
  62344. ground._height = options.height || 1;
  62345. ground._maxX = ground._width / 2;
  62346. ground._maxZ = ground._height / 2;
  62347. ground._minX = -ground._maxX;
  62348. ground._minZ = -ground._maxZ;
  62349. var vertexData = BABYLON.VertexData.CreateGround(options);
  62350. vertexData.applyToMesh(ground, options.updatable);
  62351. ground._setReady(true);
  62352. return ground;
  62353. };
  62354. /**
  62355. * Creates a tiled ground mesh
  62356. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62357. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62358. * * 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
  62359. * * 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
  62360. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62361. * @param name defines the name of the mesh
  62362. * @param options defines the options used to create the mesh
  62363. * @param scene defines the hosting scene
  62364. * @returns the tiled ground mesh
  62365. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62366. */
  62367. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62368. var tiledGround = new BABYLON.Mesh(name, scene);
  62369. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62370. vertexData.applyToMesh(tiledGround, options.updatable);
  62371. return tiledGround;
  62372. };
  62373. /**
  62374. * Creates a ground mesh from a height map
  62375. * * The parameter `url` sets the URL of the height map image resource.
  62376. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62377. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62378. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62379. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62380. * * 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.
  62381. * * 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).
  62382. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62383. * @param name defines the name of the mesh
  62384. * @param url defines the url to the height map
  62385. * @param options defines the options used to create the mesh
  62386. * @param scene defines the hosting scene
  62387. * @returns the ground mesh
  62388. * @see http://doc.babylonjs.com/babylon101/height_map
  62389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62390. */
  62391. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62392. var width = options.width || 10.0;
  62393. var height = options.height || 10.0;
  62394. var subdivisions = options.subdivisions || 1 | 0;
  62395. var minHeight = options.minHeight || 0.0;
  62396. var maxHeight = options.maxHeight || 1.0;
  62397. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62398. var updatable = options.updatable;
  62399. var onReady = options.onReady;
  62400. var ground = new BABYLON.GroundMesh(name, scene);
  62401. ground._subdivisionsX = subdivisions;
  62402. ground._subdivisionsY = subdivisions;
  62403. ground._width = width;
  62404. ground._height = height;
  62405. ground._maxX = ground._width / 2.0;
  62406. ground._maxZ = ground._height / 2.0;
  62407. ground._minX = -ground._maxX;
  62408. ground._minZ = -ground._maxZ;
  62409. ground._setReady(false);
  62410. var onload = function (img) {
  62411. // Getting height map data
  62412. var canvas = document.createElement("canvas");
  62413. var context = canvas.getContext("2d");
  62414. if (!context) {
  62415. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62416. }
  62417. if (scene.isDisposed) {
  62418. return;
  62419. }
  62420. var bufferWidth = img.width;
  62421. var bufferHeight = img.height;
  62422. canvas.width = bufferWidth;
  62423. canvas.height = bufferHeight;
  62424. context.drawImage(img, 0, 0);
  62425. // Create VertexData from map data
  62426. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62427. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62428. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62429. width: width, height: height,
  62430. subdivisions: subdivisions,
  62431. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62432. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62433. });
  62434. vertexData.applyToMesh(ground, updatable);
  62435. //execute ready callback, if set
  62436. if (onReady) {
  62437. onReady(ground);
  62438. }
  62439. ground._setReady(true);
  62440. };
  62441. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62442. return ground;
  62443. };
  62444. /**
  62445. * Creates a polygon mesh
  62446. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62447. * * 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
  62448. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62449. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62450. * * 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)
  62451. * * Remember you can only change the shape positions, not their number when updating a polygon
  62452. * @param name defines the name of the mesh
  62453. * @param options defines the options used to create the mesh
  62454. * @param scene defines the hosting scene
  62455. * @returns the polygon mesh
  62456. */
  62457. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62458. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62459. var shape = options.shape;
  62460. var holes = options.holes || [];
  62461. var depth = options.depth || 0;
  62462. var contours = [];
  62463. var hole = [];
  62464. for (var i = 0; i < shape.length; i++) {
  62465. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62466. }
  62467. var epsilon = 0.00000001;
  62468. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62469. contours.pop();
  62470. }
  62471. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62472. for (var hNb = 0; hNb < holes.length; hNb++) {
  62473. hole = [];
  62474. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62475. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62476. }
  62477. polygonTriangulation.addHole(hole);
  62478. }
  62479. var polygon = polygonTriangulation.build(options.updatable, depth);
  62480. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62481. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62482. vertexData.applyToMesh(polygon, options.updatable);
  62483. return polygon;
  62484. };
  62485. ;
  62486. /**
  62487. * Creates an extruded polygon mesh, with depth in the Y direction.
  62488. * * 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)
  62489. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62490. * @param name defines the name of the mesh
  62491. * @param options defines the options used to create the mesh
  62492. * @param scene defines the hosting scene
  62493. * @returns the polygon mesh
  62494. */
  62495. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62496. return MeshBuilder.CreatePolygon(name, options, scene);
  62497. };
  62498. ;
  62499. /**
  62500. * Creates a tube mesh.
  62501. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62502. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62503. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62504. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62505. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62506. * * 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)
  62507. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62508. * * 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
  62509. * * 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
  62510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62511. * * 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
  62512. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62513. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62514. * @param name defines the name of the mesh
  62515. * @param options defines the options used to create the mesh
  62516. * @param scene defines the hosting scene
  62517. * @returns the tube mesh
  62518. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62519. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62520. */
  62521. MeshBuilder.CreateTube = function (name, options, scene) {
  62522. var path = options.path;
  62523. var instance = options.instance;
  62524. var radius = 1.0;
  62525. if (instance) {
  62526. radius = instance.radius;
  62527. }
  62528. if (options.radius !== undefined) {
  62529. radius = options.radius;
  62530. }
  62531. ;
  62532. var tessellation = options.tessellation || 64 | 0;
  62533. var radiusFunction = options.radiusFunction || null;
  62534. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62535. var invertUV = options.invertUV || false;
  62536. var updatable = options.updatable;
  62537. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62538. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62539. // tube geometry
  62540. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62541. var tangents = path3D.getTangents();
  62542. var normals = path3D.getNormals();
  62543. var distances = path3D.getDistances();
  62544. var pi2 = Math.PI * 2;
  62545. var step = pi2 / tessellation * arc;
  62546. var returnRadius = function () { return radius; };
  62547. var radiusFunctionFinal = radiusFunction || returnRadius;
  62548. var circlePath;
  62549. var rad;
  62550. var normal;
  62551. var rotated;
  62552. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62553. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62554. for (var i = 0; i < path.length; i++) {
  62555. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62556. circlePath = Array(); // current circle array
  62557. normal = normals[i]; // current normal
  62558. for (var t = 0; t < tessellation; t++) {
  62559. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62560. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62561. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62562. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62563. circlePath[t] = rotated;
  62564. }
  62565. circlePaths[index] = circlePath;
  62566. index++;
  62567. }
  62568. // cap
  62569. var capPath = function (nbPoints, pathIndex) {
  62570. var pointCap = Array();
  62571. for (var i = 0; i < nbPoints; i++) {
  62572. pointCap.push(path[pathIndex]);
  62573. }
  62574. return pointCap;
  62575. };
  62576. switch (cap) {
  62577. case BABYLON.Mesh.NO_CAP:
  62578. break;
  62579. case BABYLON.Mesh.CAP_START:
  62580. circlePaths[0] = capPath(tessellation, 0);
  62581. circlePaths[1] = circlePaths[2].slice(0);
  62582. break;
  62583. case BABYLON.Mesh.CAP_END:
  62584. circlePaths[index] = circlePaths[index - 1].slice(0);
  62585. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62586. break;
  62587. case BABYLON.Mesh.CAP_ALL:
  62588. circlePaths[0] = capPath(tessellation, 0);
  62589. circlePaths[1] = circlePaths[2].slice(0);
  62590. circlePaths[index] = circlePaths[index - 1].slice(0);
  62591. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62592. break;
  62593. default:
  62594. break;
  62595. }
  62596. return circlePaths;
  62597. };
  62598. var path3D;
  62599. var pathArray;
  62600. if (instance) { // tube update
  62601. var arc = options.arc || instance.arc;
  62602. path3D = (instance.path3D).update(path);
  62603. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62604. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62605. instance.path3D = path3D;
  62606. instance.pathArray = pathArray;
  62607. instance.arc = arc;
  62608. instance.radius = radius;
  62609. return instance;
  62610. }
  62611. // tube creation
  62612. path3D = new BABYLON.Path3D(path);
  62613. var newPathArray = new Array();
  62614. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62615. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62616. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62617. tube.pathArray = pathArray;
  62618. tube.path3D = path3D;
  62619. tube.tessellation = tessellation;
  62620. tube.cap = cap;
  62621. tube.arc = options.arc;
  62622. tube.radius = radius;
  62623. return tube;
  62624. };
  62625. /**
  62626. * Creates a polyhedron mesh
  62627. * * 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
  62628. * * The parameter `size` (positive float, default 1) sets the polygon size
  62629. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62630. * * 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`
  62631. * * 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
  62632. * * 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)`)
  62633. * * 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
  62634. * * 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
  62635. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62636. * * 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
  62637. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62638. * @param name defines the name of the mesh
  62639. * @param options defines the options used to create the mesh
  62640. * @param scene defines the hosting scene
  62641. * @returns the polyhedron mesh
  62642. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62643. */
  62644. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62645. var polyhedron = new BABYLON.Mesh(name, scene);
  62646. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62647. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62648. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62649. vertexData.applyToMesh(polyhedron, options.updatable);
  62650. return polyhedron;
  62651. };
  62652. /**
  62653. * Creates a decal mesh.
  62654. * 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
  62655. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62656. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62657. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62658. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62659. * @param name defines the name of the mesh
  62660. * @param sourceMesh defines the mesh where the decal must be applied
  62661. * @param options defines the options used to create the mesh
  62662. * @param scene defines the hosting scene
  62663. * @returns the decal mesh
  62664. * @see http://doc.babylonjs.com/how_to/decals
  62665. */
  62666. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62667. var indices = sourceMesh.getIndices();
  62668. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62669. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62670. var position = options.position || BABYLON.Vector3.Zero();
  62671. var normal = options.normal || BABYLON.Vector3.Up();
  62672. var size = options.size || BABYLON.Vector3.One();
  62673. var angle = options.angle || 0;
  62674. // Getting correct rotation
  62675. if (!normal) {
  62676. var target = new BABYLON.Vector3(0, 0, 1);
  62677. var camera = sourceMesh.getScene().activeCamera;
  62678. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62679. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62680. }
  62681. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62682. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62683. var pitch = Math.atan2(normal.y, len);
  62684. // Matrix
  62685. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62686. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62687. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62688. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62689. var vertexData = new BABYLON.VertexData();
  62690. vertexData.indices = [];
  62691. vertexData.positions = [];
  62692. vertexData.normals = [];
  62693. vertexData.uvs = [];
  62694. var currentVertexDataIndex = 0;
  62695. var extractDecalVector3 = function (indexId) {
  62696. var result = new BABYLON.PositionNormalVertex();
  62697. if (!indices || !positions || !normals) {
  62698. return result;
  62699. }
  62700. var vertexId = indices[indexId];
  62701. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62702. // Send vector to decal local world
  62703. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62704. // Get normal
  62705. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62706. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62707. return result;
  62708. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62709. var clip = function (vertices, axis) {
  62710. if (vertices.length === 0) {
  62711. return vertices;
  62712. }
  62713. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62714. var clipVertices = function (v0, v1) {
  62715. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62716. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62717. };
  62718. var result = new Array();
  62719. for (var index = 0; index < vertices.length; index += 3) {
  62720. var v1Out;
  62721. var v2Out;
  62722. var v3Out;
  62723. var total = 0;
  62724. var nV1 = null;
  62725. var nV2 = null;
  62726. var nV3 = null;
  62727. var nV4 = null;
  62728. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62729. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62730. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62731. v1Out = d1 > 0;
  62732. v2Out = d2 > 0;
  62733. v3Out = d3 > 0;
  62734. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62735. switch (total) {
  62736. case 0:
  62737. result.push(vertices[index]);
  62738. result.push(vertices[index + 1]);
  62739. result.push(vertices[index + 2]);
  62740. break;
  62741. case 1:
  62742. if (v1Out) {
  62743. nV1 = vertices[index + 1];
  62744. nV2 = vertices[index + 2];
  62745. nV3 = clipVertices(vertices[index], nV1);
  62746. nV4 = clipVertices(vertices[index], nV2);
  62747. }
  62748. if (v2Out) {
  62749. nV1 = vertices[index];
  62750. nV2 = vertices[index + 2];
  62751. nV3 = clipVertices(vertices[index + 1], nV1);
  62752. nV4 = clipVertices(vertices[index + 1], nV2);
  62753. result.push(nV3);
  62754. result.push(nV2.clone());
  62755. result.push(nV1.clone());
  62756. result.push(nV2.clone());
  62757. result.push(nV3.clone());
  62758. result.push(nV4);
  62759. break;
  62760. }
  62761. if (v3Out) {
  62762. nV1 = vertices[index];
  62763. nV2 = vertices[index + 1];
  62764. nV3 = clipVertices(vertices[index + 2], nV1);
  62765. nV4 = clipVertices(vertices[index + 2], nV2);
  62766. }
  62767. if (nV1 && nV2 && nV3 && nV4) {
  62768. result.push(nV1.clone());
  62769. result.push(nV2.clone());
  62770. result.push(nV3);
  62771. result.push(nV4);
  62772. result.push(nV3.clone());
  62773. result.push(nV2.clone());
  62774. }
  62775. break;
  62776. case 2:
  62777. if (!v1Out) {
  62778. nV1 = vertices[index].clone();
  62779. nV2 = clipVertices(nV1, vertices[index + 1]);
  62780. nV3 = clipVertices(nV1, vertices[index + 2]);
  62781. result.push(nV1);
  62782. result.push(nV2);
  62783. result.push(nV3);
  62784. }
  62785. if (!v2Out) {
  62786. nV1 = vertices[index + 1].clone();
  62787. nV2 = clipVertices(nV1, vertices[index + 2]);
  62788. nV3 = clipVertices(nV1, vertices[index]);
  62789. result.push(nV1);
  62790. result.push(nV2);
  62791. result.push(nV3);
  62792. }
  62793. if (!v3Out) {
  62794. nV1 = vertices[index + 2].clone();
  62795. nV2 = clipVertices(nV1, vertices[index]);
  62796. nV3 = clipVertices(nV1, vertices[index + 1]);
  62797. result.push(nV1);
  62798. result.push(nV2);
  62799. result.push(nV3);
  62800. }
  62801. break;
  62802. case 3:
  62803. break;
  62804. }
  62805. }
  62806. return result;
  62807. };
  62808. for (var index = 0; index < indices.length; index += 3) {
  62809. var faceVertices = new Array();
  62810. faceVertices.push(extractDecalVector3(index));
  62811. faceVertices.push(extractDecalVector3(index + 1));
  62812. faceVertices.push(extractDecalVector3(index + 2));
  62813. // Clip
  62814. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62815. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62816. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62817. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62818. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62820. if (faceVertices.length === 0) {
  62821. continue;
  62822. }
  62823. // Add UVs and get back to world
  62824. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62825. var vertex = faceVertices[vIndex];
  62826. //TODO check for Int32Array | Uint32Array | Uint16Array
  62827. vertexData.indices.push(currentVertexDataIndex);
  62828. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62829. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62830. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62831. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62832. currentVertexDataIndex++;
  62833. }
  62834. }
  62835. // Return mesh
  62836. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62837. vertexData.applyToMesh(decal);
  62838. decal.position = position.clone();
  62839. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62840. return decal;
  62841. };
  62842. // Privates
  62843. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62844. // extrusion geometry
  62845. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62846. var tangents = path3D.getTangents();
  62847. var normals = path3D.getNormals();
  62848. var binormals = path3D.getBinormals();
  62849. var distances = path3D.getDistances();
  62850. var angle = 0;
  62851. var returnScale = function () { return scale !== null ? scale : 1; };
  62852. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62853. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62854. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62855. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62856. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62857. for (var i = 0; i < curve.length; i++) {
  62858. var shapePath = new Array();
  62859. var angleStep = rotate(i, distances[i]);
  62860. var scaleRatio = scl(i, distances[i]);
  62861. for (var p = 0; p < shape.length; p++) {
  62862. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62863. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62864. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62865. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62866. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62867. shapePath[p] = rotated;
  62868. }
  62869. shapePaths[index] = shapePath;
  62870. angle += angleStep;
  62871. index++;
  62872. }
  62873. // cap
  62874. var capPath = function (shapePath) {
  62875. var pointCap = Array();
  62876. var barycenter = BABYLON.Vector3.Zero();
  62877. var i;
  62878. for (i = 0; i < shapePath.length; i++) {
  62879. barycenter.addInPlace(shapePath[i]);
  62880. }
  62881. barycenter.scaleInPlace(1.0 / shapePath.length);
  62882. for (i = 0; i < shapePath.length; i++) {
  62883. pointCap.push(barycenter);
  62884. }
  62885. return pointCap;
  62886. };
  62887. switch (cap) {
  62888. case BABYLON.Mesh.NO_CAP:
  62889. break;
  62890. case BABYLON.Mesh.CAP_START:
  62891. shapePaths[0] = capPath(shapePaths[2]);
  62892. shapePaths[1] = shapePaths[2];
  62893. break;
  62894. case BABYLON.Mesh.CAP_END:
  62895. shapePaths[index] = shapePaths[index - 1];
  62896. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62897. break;
  62898. case BABYLON.Mesh.CAP_ALL:
  62899. shapePaths[0] = capPath(shapePaths[2]);
  62900. shapePaths[1] = shapePaths[2];
  62901. shapePaths[index] = shapePaths[index - 1];
  62902. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62903. break;
  62904. default:
  62905. break;
  62906. }
  62907. return shapePaths;
  62908. };
  62909. var path3D;
  62910. var pathArray;
  62911. if (instance) { // instance update
  62912. path3D = (instance.path3D).update(curve);
  62913. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62914. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62915. return instance;
  62916. }
  62917. // extruded shape creation
  62918. path3D = new BABYLON.Path3D(curve);
  62919. var newShapePaths = new Array();
  62920. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62921. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62922. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62923. extrudedGeneric.pathArray = pathArray;
  62924. extrudedGeneric.path3D = path3D;
  62925. extrudedGeneric.cap = cap;
  62926. return extrudedGeneric;
  62927. };
  62928. return MeshBuilder;
  62929. }());
  62930. BABYLON.MeshBuilder = MeshBuilder;
  62931. })(BABYLON || (BABYLON = {}));
  62932. //# sourceMappingURL=babylon.meshBuilder.js.map
  62933. var BABYLON;
  62934. (function (BABYLON) {
  62935. /**
  62936. * Draco compression (https://google.github.io/draco/)
  62937. *
  62938. * This class wraps the Draco module.
  62939. *
  62940. * **Encoder**
  62941. *
  62942. * The encoder is not currently implemented.
  62943. *
  62944. * **Decoder**
  62945. *
  62946. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62947. *
  62948. * To update the configuration, use the following code:
  62949. * ```javascript
  62950. * BABYLON.DracoCompression.Configuration = {
  62951. * decoder: {
  62952. * wasmUrl: "<url to the WebAssembly library>",
  62953. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62954. * fallbackUrl: "<url to the fallback JavaScript library>",
  62955. * }
  62956. * };
  62957. * ```
  62958. *
  62959. * 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.
  62960. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62961. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62962. *
  62963. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62964. * ```javascript
  62965. * var dracoCompression = new BABYLON.DracoCompression();
  62966. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62967. * [BABYLON.VertexBuffer.PositionKind]: 0
  62968. * });
  62969. * ```
  62970. *
  62971. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62972. */
  62973. var DracoCompression = /** @class */ (function () {
  62974. /**
  62975. * Constructor
  62976. */
  62977. function DracoCompression() {
  62978. }
  62979. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62980. /**
  62981. * Returns true if the decoder is available.
  62982. */
  62983. get: function () {
  62984. if (typeof DracoDecoderModule !== "undefined") {
  62985. return true;
  62986. }
  62987. var decoder = DracoCompression.Configuration.decoder;
  62988. if (decoder) {
  62989. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62990. return true;
  62991. }
  62992. if (decoder.fallbackUrl) {
  62993. return true;
  62994. }
  62995. }
  62996. return false;
  62997. },
  62998. enumerable: true,
  62999. configurable: true
  63000. });
  63001. /**
  63002. * Stop all async operations and release resources.
  63003. */
  63004. DracoCompression.prototype.dispose = function () {
  63005. };
  63006. /**
  63007. * Decode Draco compressed mesh data to vertex data.
  63008. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63009. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63010. * @returns A promise that resolves with the decoded vertex data
  63011. */
  63012. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63013. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63014. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63015. var module = wrappedModule.module;
  63016. var vertexData = new BABYLON.VertexData();
  63017. var buffer = new module.DecoderBuffer();
  63018. buffer.Init(dataView, dataView.byteLength);
  63019. var decoder = new module.Decoder();
  63020. var geometry;
  63021. var status;
  63022. try {
  63023. var type = decoder.GetEncodedGeometryType(buffer);
  63024. switch (type) {
  63025. case module.TRIANGULAR_MESH:
  63026. geometry = new module.Mesh();
  63027. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63028. break;
  63029. case module.POINT_CLOUD:
  63030. geometry = new module.PointCloud();
  63031. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63032. break;
  63033. default:
  63034. throw new Error("Invalid geometry type " + type);
  63035. }
  63036. if (!status.ok() || !geometry.ptr) {
  63037. throw new Error(status.error_msg());
  63038. }
  63039. var numPoints = geometry.num_points();
  63040. if (type === module.TRIANGULAR_MESH) {
  63041. var numFaces = geometry.num_faces();
  63042. var faceIndices = new module.DracoInt32Array();
  63043. try {
  63044. var indices = new Uint32Array(numFaces * 3);
  63045. for (var i = 0; i < numFaces; i++) {
  63046. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63047. var offset = i * 3;
  63048. indices[offset + 0] = faceIndices.GetValue(0);
  63049. indices[offset + 1] = faceIndices.GetValue(1);
  63050. indices[offset + 2] = faceIndices.GetValue(2);
  63051. }
  63052. vertexData.indices = indices;
  63053. }
  63054. finally {
  63055. module.destroy(faceIndices);
  63056. }
  63057. }
  63058. for (var kind in attributes) {
  63059. var uniqueId = attributes[kind];
  63060. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63061. var dracoData = new module.DracoFloat32Array();
  63062. try {
  63063. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63064. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63065. for (var i = 0; i < babylonData.length; i++) {
  63066. babylonData[i] = dracoData.GetValue(i);
  63067. }
  63068. vertexData.set(babylonData, kind);
  63069. }
  63070. finally {
  63071. module.destroy(dracoData);
  63072. }
  63073. }
  63074. }
  63075. finally {
  63076. if (geometry) {
  63077. module.destroy(geometry);
  63078. }
  63079. module.destroy(decoder);
  63080. module.destroy(buffer);
  63081. }
  63082. return vertexData;
  63083. });
  63084. };
  63085. DracoCompression._GetDecoderModule = function () {
  63086. if (!DracoCompression._DecoderModulePromise) {
  63087. var promise = null;
  63088. var config_1 = {};
  63089. if (typeof DracoDecoderModule !== "undefined") {
  63090. promise = Promise.resolve();
  63091. }
  63092. else {
  63093. var decoder = DracoCompression.Configuration.decoder;
  63094. if (decoder) {
  63095. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63096. promise = Promise.all([
  63097. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63098. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63099. config_1.wasmBinary = data;
  63100. })
  63101. ]);
  63102. }
  63103. else if (decoder.fallbackUrl) {
  63104. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63105. }
  63106. }
  63107. }
  63108. if (!promise) {
  63109. throw new Error("Draco decoder module is not available");
  63110. }
  63111. DracoCompression._DecoderModulePromise = promise.then(function () {
  63112. return new Promise(function (resolve) {
  63113. config_1.onModuleLoaded = function (decoderModule) {
  63114. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63115. resolve({ module: decoderModule });
  63116. };
  63117. DracoDecoderModule(config_1);
  63118. });
  63119. });
  63120. }
  63121. return DracoCompression._DecoderModulePromise;
  63122. };
  63123. DracoCompression._LoadScriptAsync = function (url) {
  63124. return new Promise(function (resolve, reject) {
  63125. BABYLON.Tools.LoadScript(url, function () {
  63126. resolve();
  63127. }, function (message) {
  63128. reject(new Error(message));
  63129. });
  63130. });
  63131. };
  63132. DracoCompression._LoadFileAsync = function (url) {
  63133. return new Promise(function (resolve, reject) {
  63134. BABYLON.Tools.LoadFile(url, function (data) {
  63135. resolve(data);
  63136. }, undefined, undefined, true, function (request, exception) {
  63137. reject(exception);
  63138. });
  63139. });
  63140. };
  63141. /**
  63142. * The configuration. Defaults to the following urls:
  63143. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63144. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63145. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63146. */
  63147. DracoCompression.Configuration = {
  63148. decoder: {
  63149. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63150. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63151. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63152. }
  63153. };
  63154. return DracoCompression;
  63155. }());
  63156. BABYLON.DracoCompression = DracoCompression;
  63157. })(BABYLON || (BABYLON = {}));
  63158. //# sourceMappingURL=babylon.dracoCompression.js.map
  63159. var BABYLON;
  63160. (function (BABYLON) {
  63161. var AudioEngine = /** @class */ (function () {
  63162. function AudioEngine() {
  63163. this._audioContext = null;
  63164. this._audioContextInitialized = false;
  63165. this.canUseWebAudio = false;
  63166. this.WarnedWebAudioUnsupported = false;
  63167. this.unlocked = false;
  63168. this.isMP3supported = false;
  63169. this.isOGGsupported = false;
  63170. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63171. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63172. this.canUseWebAudio = true;
  63173. }
  63174. var audioElem = document.createElement('audio');
  63175. try {
  63176. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63177. this.isMP3supported = true;
  63178. }
  63179. }
  63180. catch (e) {
  63181. // protect error during capability check.
  63182. }
  63183. try {
  63184. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63185. this.isOGGsupported = true;
  63186. }
  63187. }
  63188. catch (e) {
  63189. // protect error during capability check.
  63190. }
  63191. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63192. this._unlockiOSaudio();
  63193. }
  63194. else {
  63195. this.unlocked = true;
  63196. }
  63197. }
  63198. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63199. get: function () {
  63200. if (!this._audioContextInitialized) {
  63201. this._initializeAudioContext();
  63202. }
  63203. return this._audioContext;
  63204. },
  63205. enumerable: true,
  63206. configurable: true
  63207. });
  63208. AudioEngine.prototype._unlockiOSaudio = function () {
  63209. var _this = this;
  63210. var unlockaudio = function () {
  63211. if (!_this.audioContext) {
  63212. return;
  63213. }
  63214. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63215. var source = _this.audioContext.createBufferSource();
  63216. source.buffer = buffer;
  63217. source.connect(_this.audioContext.destination);
  63218. source.start(0);
  63219. setTimeout(function () {
  63220. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63221. _this.unlocked = true;
  63222. window.removeEventListener('touchend', unlockaudio, false);
  63223. if (_this.onAudioUnlocked) {
  63224. _this.onAudioUnlocked();
  63225. }
  63226. }
  63227. }, 0);
  63228. };
  63229. window.addEventListener('touchend', unlockaudio, false);
  63230. };
  63231. AudioEngine.prototype._initializeAudioContext = function () {
  63232. try {
  63233. if (this.canUseWebAudio) {
  63234. this._audioContext = new AudioContext();
  63235. // create a global volume gain node
  63236. this.masterGain = this._audioContext.createGain();
  63237. this.masterGain.gain.value = 1;
  63238. this.masterGain.connect(this._audioContext.destination);
  63239. this._audioContextInitialized = true;
  63240. }
  63241. }
  63242. catch (e) {
  63243. this.canUseWebAudio = false;
  63244. BABYLON.Tools.Error("Web Audio: " + e.message);
  63245. }
  63246. };
  63247. AudioEngine.prototype.dispose = function () {
  63248. if (this.canUseWebAudio && this._audioContextInitialized) {
  63249. if (this._connectedAnalyser && this._audioContext) {
  63250. this._connectedAnalyser.stopDebugCanvas();
  63251. this._connectedAnalyser.dispose();
  63252. this.masterGain.disconnect();
  63253. this.masterGain.connect(this._audioContext.destination);
  63254. this._connectedAnalyser = null;
  63255. }
  63256. this.masterGain.gain.value = 1;
  63257. }
  63258. this.WarnedWebAudioUnsupported = false;
  63259. };
  63260. AudioEngine.prototype.getGlobalVolume = function () {
  63261. if (this.canUseWebAudio && this._audioContextInitialized) {
  63262. return this.masterGain.gain.value;
  63263. }
  63264. else {
  63265. return -1;
  63266. }
  63267. };
  63268. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63269. if (this.canUseWebAudio && this._audioContextInitialized) {
  63270. this.masterGain.gain.value = newVolume;
  63271. }
  63272. };
  63273. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63274. if (this._connectedAnalyser) {
  63275. this._connectedAnalyser.stopDebugCanvas();
  63276. }
  63277. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63278. this._connectedAnalyser = analyser;
  63279. this.masterGain.disconnect();
  63280. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63281. }
  63282. };
  63283. return AudioEngine;
  63284. }());
  63285. BABYLON.AudioEngine = AudioEngine;
  63286. })(BABYLON || (BABYLON = {}));
  63287. //# sourceMappingURL=babylon.audioEngine.js.map
  63288. var BABYLON;
  63289. (function (BABYLON) {
  63290. var Sound = /** @class */ (function () {
  63291. /**
  63292. * Create a sound and attach it to a scene
  63293. * @param name Name of your sound
  63294. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63295. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63296. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63297. */
  63298. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63299. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63300. var _this = this;
  63301. this.autoplay = false;
  63302. this.loop = false;
  63303. this.useCustomAttenuation = false;
  63304. this.spatialSound = false;
  63305. this.refDistance = 1;
  63306. this.rolloffFactor = 1;
  63307. this.maxDistance = 100;
  63308. this.distanceModel = "linear";
  63309. this._panningModel = "equalpower";
  63310. this._playbackRate = 1;
  63311. this._streaming = false;
  63312. this._startTime = 0;
  63313. this._startOffset = 0;
  63314. this._position = BABYLON.Vector3.Zero();
  63315. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63316. this._volume = 1;
  63317. this._isReadyToPlay = false;
  63318. this.isPlaying = false;
  63319. this.isPaused = false;
  63320. this._isDirectional = false;
  63321. // Used if you'd like to create a directional sound.
  63322. // If not set, the sound will be omnidirectional
  63323. this._coneInnerAngle = 360;
  63324. this._coneOuterAngle = 360;
  63325. this._coneOuterGain = 0;
  63326. this._isOutputConnected = false;
  63327. this._urlType = "Unknown";
  63328. this.name = name;
  63329. this._scene = scene;
  63330. this._readyToPlayCallback = readyToPlayCallback;
  63331. // Default custom attenuation function is a linear attenuation
  63332. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63333. if (currentDistance < maxDistance) {
  63334. return currentVolume * (1 - currentDistance / maxDistance);
  63335. }
  63336. else {
  63337. return 0;
  63338. }
  63339. };
  63340. if (options) {
  63341. this.autoplay = options.autoplay || false;
  63342. this.loop = options.loop || false;
  63343. // if volume === 0, we need another way to check this option
  63344. if (options.volume !== undefined) {
  63345. this._volume = options.volume;
  63346. }
  63347. this.spatialSound = options.spatialSound || false;
  63348. this.maxDistance = options.maxDistance || 100;
  63349. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63350. this.rolloffFactor = options.rolloffFactor || 1;
  63351. this.refDistance = options.refDistance || 1;
  63352. this.distanceModel = options.distanceModel || "linear";
  63353. this._playbackRate = options.playbackRate || 1;
  63354. this._streaming = options.streaming || false;
  63355. }
  63356. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63357. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63358. this._soundGain.gain.value = this._volume;
  63359. this._inputAudioNode = this._soundGain;
  63360. this._ouputAudioNode = this._soundGain;
  63361. if (this.spatialSound) {
  63362. this._createSpatialParameters();
  63363. }
  63364. this._scene.mainSoundTrack.AddSound(this);
  63365. var validParameter = true;
  63366. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63367. if (urlOrArrayBuffer) {
  63368. try {
  63369. if (typeof (urlOrArrayBuffer) === "string") {
  63370. this._urlType = "String";
  63371. }
  63372. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63373. this._urlType = "ArrayBuffer";
  63374. }
  63375. else if (urlOrArrayBuffer instanceof MediaStream) {
  63376. this._urlType = "MediaStream";
  63377. }
  63378. else if (Array.isArray(urlOrArrayBuffer)) {
  63379. this._urlType = "Array";
  63380. }
  63381. var urls = [];
  63382. var codecSupportedFound = false;
  63383. switch (this._urlType) {
  63384. case "MediaStream":
  63385. this._streaming = true;
  63386. this._isReadyToPlay = true;
  63387. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63388. if (this.autoplay) {
  63389. this.play();
  63390. }
  63391. if (this._readyToPlayCallback) {
  63392. this._readyToPlayCallback();
  63393. }
  63394. break;
  63395. case "ArrayBuffer":
  63396. if (urlOrArrayBuffer.byteLength > 0) {
  63397. codecSupportedFound = true;
  63398. this._soundLoaded(urlOrArrayBuffer);
  63399. }
  63400. break;
  63401. case "String":
  63402. urls.push(urlOrArrayBuffer);
  63403. case "Array":
  63404. if (urls.length === 0)
  63405. urls = urlOrArrayBuffer;
  63406. // If we found a supported format, we load it immediately and stop the loop
  63407. for (var i = 0; i < urls.length; i++) {
  63408. var url = urls[i];
  63409. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63410. codecSupportedFound = true;
  63411. }
  63412. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63413. codecSupportedFound = true;
  63414. }
  63415. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63416. codecSupportedFound = true;
  63417. }
  63418. if (url.indexOf("blob:") !== -1) {
  63419. codecSupportedFound = true;
  63420. }
  63421. if (codecSupportedFound) {
  63422. // Loading sound using XHR2
  63423. if (!this._streaming) {
  63424. this._scene._loadFile(url, function (data) {
  63425. _this._soundLoaded(data);
  63426. }, undefined, true, true, function (exception) {
  63427. if (exception) {
  63428. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63429. }
  63430. BABYLON.Tools.Error("Sound creation aborted.");
  63431. _this._scene.mainSoundTrack.RemoveSound(_this);
  63432. });
  63433. }
  63434. // Streaming sound using HTML5 Audio tag
  63435. else {
  63436. this._htmlAudioElement = new Audio(url);
  63437. this._htmlAudioElement.controls = false;
  63438. this._htmlAudioElement.loop = this.loop;
  63439. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63440. this._htmlAudioElement.preload = "auto";
  63441. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63442. _this._isReadyToPlay = true;
  63443. if (_this.autoplay) {
  63444. _this.play();
  63445. }
  63446. if (_this._readyToPlayCallback) {
  63447. _this._readyToPlayCallback();
  63448. }
  63449. });
  63450. document.body.appendChild(this._htmlAudioElement);
  63451. }
  63452. break;
  63453. }
  63454. }
  63455. break;
  63456. default:
  63457. validParameter = false;
  63458. break;
  63459. }
  63460. if (!validParameter) {
  63461. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63462. }
  63463. else {
  63464. if (!codecSupportedFound) {
  63465. this._isReadyToPlay = true;
  63466. // Simulating a ready to play event to avoid breaking code path
  63467. if (this._readyToPlayCallback) {
  63468. window.setTimeout(function () {
  63469. if (_this._readyToPlayCallback) {
  63470. _this._readyToPlayCallback();
  63471. }
  63472. }, 1000);
  63473. }
  63474. }
  63475. }
  63476. }
  63477. catch (ex) {
  63478. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63479. this._scene.mainSoundTrack.RemoveSound(this);
  63480. }
  63481. }
  63482. }
  63483. else {
  63484. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63485. this._scene.mainSoundTrack.AddSound(this);
  63486. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63487. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63488. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63489. }
  63490. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63491. if (this._readyToPlayCallback) {
  63492. window.setTimeout(function () {
  63493. if (_this._readyToPlayCallback) {
  63494. _this._readyToPlayCallback();
  63495. }
  63496. }, 1000);
  63497. }
  63498. }
  63499. }
  63500. Sound.prototype.dispose = function () {
  63501. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63502. if (this.isPlaying) {
  63503. this.stop();
  63504. }
  63505. this._isReadyToPlay = false;
  63506. if (this.soundTrackId === -1) {
  63507. this._scene.mainSoundTrack.RemoveSound(this);
  63508. }
  63509. else {
  63510. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63511. }
  63512. if (this._soundGain) {
  63513. this._soundGain.disconnect();
  63514. this._soundGain = null;
  63515. }
  63516. if (this._soundPanner) {
  63517. this._soundPanner.disconnect();
  63518. this._soundPanner = null;
  63519. }
  63520. if (this._soundSource) {
  63521. this._soundSource.disconnect();
  63522. this._soundSource = null;
  63523. }
  63524. this._audioBuffer = null;
  63525. if (this._htmlAudioElement) {
  63526. this._htmlAudioElement.pause();
  63527. this._htmlAudioElement.src = "";
  63528. document.body.removeChild(this._htmlAudioElement);
  63529. }
  63530. if (this._streamingSource) {
  63531. this._streamingSource.disconnect();
  63532. }
  63533. if (this._connectedMesh && this._registerFunc) {
  63534. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63535. this._connectedMesh = null;
  63536. }
  63537. }
  63538. };
  63539. Sound.prototype.isReady = function () {
  63540. return this._isReadyToPlay;
  63541. };
  63542. Sound.prototype._soundLoaded = function (audioData) {
  63543. var _this = this;
  63544. if (!BABYLON.Engine.audioEngine.audioContext) {
  63545. return;
  63546. }
  63547. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63548. _this._audioBuffer = buffer;
  63549. _this._isReadyToPlay = true;
  63550. if (_this.autoplay) {
  63551. _this.play();
  63552. }
  63553. if (_this._readyToPlayCallback) {
  63554. _this._readyToPlayCallback();
  63555. }
  63556. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63557. };
  63558. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63559. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63560. this._audioBuffer = audioBuffer;
  63561. this._isReadyToPlay = true;
  63562. }
  63563. };
  63564. Sound.prototype.updateOptions = function (options) {
  63565. if (options) {
  63566. this.loop = options.loop || this.loop;
  63567. this.maxDistance = options.maxDistance || this.maxDistance;
  63568. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63569. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63570. this.refDistance = options.refDistance || this.refDistance;
  63571. this.distanceModel = options.distanceModel || this.distanceModel;
  63572. this._playbackRate = options.playbackRate || this._playbackRate;
  63573. this._updateSpatialParameters();
  63574. if (this.isPlaying) {
  63575. if (this._streaming && this._htmlAudioElement) {
  63576. this._htmlAudioElement.playbackRate = this._playbackRate;
  63577. }
  63578. else {
  63579. if (this._soundSource) {
  63580. this._soundSource.playbackRate.value = this._playbackRate;
  63581. }
  63582. }
  63583. }
  63584. }
  63585. };
  63586. Sound.prototype._createSpatialParameters = function () {
  63587. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63588. if (this._scene.headphone) {
  63589. this._panningModel = "HRTF";
  63590. }
  63591. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63592. this._updateSpatialParameters();
  63593. this._soundPanner.connect(this._ouputAudioNode);
  63594. this._inputAudioNode = this._soundPanner;
  63595. }
  63596. };
  63597. Sound.prototype._updateSpatialParameters = function () {
  63598. if (this.spatialSound && this._soundPanner) {
  63599. if (this.useCustomAttenuation) {
  63600. // Tricks to disable in a way embedded Web Audio attenuation
  63601. this._soundPanner.distanceModel = "linear";
  63602. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63603. this._soundPanner.refDistance = 1;
  63604. this._soundPanner.rolloffFactor = 1;
  63605. this._soundPanner.panningModel = this._panningModel;
  63606. }
  63607. else {
  63608. this._soundPanner.distanceModel = this.distanceModel;
  63609. this._soundPanner.maxDistance = this.maxDistance;
  63610. this._soundPanner.refDistance = this.refDistance;
  63611. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63612. this._soundPanner.panningModel = this._panningModel;
  63613. }
  63614. }
  63615. };
  63616. Sound.prototype.switchPanningModelToHRTF = function () {
  63617. this._panningModel = "HRTF";
  63618. this._switchPanningModel();
  63619. };
  63620. Sound.prototype.switchPanningModelToEqualPower = function () {
  63621. this._panningModel = "equalpower";
  63622. this._switchPanningModel();
  63623. };
  63624. Sound.prototype._switchPanningModel = function () {
  63625. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63626. this._soundPanner.panningModel = this._panningModel;
  63627. }
  63628. };
  63629. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63630. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63631. if (this._isOutputConnected) {
  63632. this._ouputAudioNode.disconnect();
  63633. }
  63634. this._ouputAudioNode.connect(soundTrackAudioNode);
  63635. this._isOutputConnected = true;
  63636. }
  63637. };
  63638. /**
  63639. * Transform this sound into a directional source
  63640. * @param coneInnerAngle Size of the inner cone in degree
  63641. * @param coneOuterAngle Size of the outer cone in degree
  63642. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63643. */
  63644. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63645. if (coneOuterAngle < coneInnerAngle) {
  63646. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63647. return;
  63648. }
  63649. this._coneInnerAngle = coneInnerAngle;
  63650. this._coneOuterAngle = coneOuterAngle;
  63651. this._coneOuterGain = coneOuterGain;
  63652. this._isDirectional = true;
  63653. if (this.isPlaying && this.loop) {
  63654. this.stop();
  63655. this.play();
  63656. }
  63657. };
  63658. Sound.prototype.setPosition = function (newPosition) {
  63659. this._position = newPosition;
  63660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63661. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63662. }
  63663. };
  63664. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63665. this._localDirection = newLocalDirection;
  63666. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63667. this._updateDirection();
  63668. }
  63669. };
  63670. Sound.prototype._updateDirection = function () {
  63671. if (!this._connectedMesh || !this._soundPanner) {
  63672. return;
  63673. }
  63674. var mat = this._connectedMesh.getWorldMatrix();
  63675. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63676. direction.normalize();
  63677. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63678. };
  63679. Sound.prototype.updateDistanceFromListener = function () {
  63680. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63681. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63682. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63683. }
  63684. };
  63685. Sound.prototype.setAttenuationFunction = function (callback) {
  63686. this._customAttenuationFunction = callback;
  63687. };
  63688. /**
  63689. * Play the sound
  63690. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63691. * @param offset (optional) Start the sound setting it at a specific time
  63692. */
  63693. Sound.prototype.play = function (time, offset) {
  63694. var _this = this;
  63695. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63696. try {
  63697. if (this._startOffset < 0) {
  63698. time = -this._startOffset;
  63699. this._startOffset = 0;
  63700. }
  63701. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63702. if (!this._soundSource || !this._streamingSource) {
  63703. if (this.spatialSound && this._soundPanner) {
  63704. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63705. if (this._isDirectional) {
  63706. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63707. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63708. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63709. if (this._connectedMesh) {
  63710. this._updateDirection();
  63711. }
  63712. else {
  63713. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63714. }
  63715. }
  63716. }
  63717. }
  63718. if (this._streaming) {
  63719. if (!this._streamingSource) {
  63720. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63721. this._htmlAudioElement.onended = function () { _this._onended(); };
  63722. this._htmlAudioElement.playbackRate = this._playbackRate;
  63723. }
  63724. this._streamingSource.disconnect();
  63725. this._streamingSource.connect(this._inputAudioNode);
  63726. if (this._htmlAudioElement) {
  63727. this._htmlAudioElement.play();
  63728. }
  63729. }
  63730. else {
  63731. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63732. this._soundSource.buffer = this._audioBuffer;
  63733. this._soundSource.connect(this._inputAudioNode);
  63734. this._soundSource.loop = this.loop;
  63735. this._soundSource.playbackRate.value = this._playbackRate;
  63736. this._soundSource.onended = function () { _this._onended(); };
  63737. if (this._soundSource.buffer) {
  63738. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63739. }
  63740. }
  63741. this._startTime = startTime;
  63742. this.isPlaying = true;
  63743. this.isPaused = false;
  63744. }
  63745. catch (ex) {
  63746. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63747. }
  63748. }
  63749. };
  63750. Sound.prototype._onended = function () {
  63751. this.isPlaying = false;
  63752. if (this.onended) {
  63753. this.onended();
  63754. }
  63755. };
  63756. /**
  63757. * Stop the sound
  63758. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63759. */
  63760. Sound.prototype.stop = function (time) {
  63761. if (this.isPlaying) {
  63762. if (this._streaming) {
  63763. if (this._htmlAudioElement) {
  63764. this._htmlAudioElement.pause();
  63765. // Test needed for Firefox or it will generate an Invalid State Error
  63766. if (this._htmlAudioElement.currentTime > 0) {
  63767. this._htmlAudioElement.currentTime = 0;
  63768. }
  63769. }
  63770. else {
  63771. this._streamingSource.disconnect();
  63772. }
  63773. }
  63774. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63775. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63776. this._soundSource.stop(stopTime);
  63777. this._soundSource.onended = function () { };
  63778. if (!this.isPaused) {
  63779. this._startOffset = 0;
  63780. }
  63781. }
  63782. this.isPlaying = false;
  63783. }
  63784. };
  63785. Sound.prototype.pause = function () {
  63786. if (this.isPlaying) {
  63787. this.isPaused = true;
  63788. if (this._streaming) {
  63789. if (this._htmlAudioElement) {
  63790. this._htmlAudioElement.pause();
  63791. }
  63792. else {
  63793. this._streamingSource.disconnect();
  63794. }
  63795. }
  63796. else if (BABYLON.Engine.audioEngine.audioContext) {
  63797. this.stop(0);
  63798. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63799. }
  63800. }
  63801. };
  63802. Sound.prototype.setVolume = function (newVolume, time) {
  63803. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63804. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63805. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63806. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63807. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63808. }
  63809. else {
  63810. this._soundGain.gain.value = newVolume;
  63811. }
  63812. }
  63813. this._volume = newVolume;
  63814. };
  63815. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63816. this._playbackRate = newPlaybackRate;
  63817. if (this.isPlaying) {
  63818. if (this._streaming && this._htmlAudioElement) {
  63819. this._htmlAudioElement.playbackRate = this._playbackRate;
  63820. }
  63821. else if (this._soundSource) {
  63822. this._soundSource.playbackRate.value = this._playbackRate;
  63823. }
  63824. }
  63825. };
  63826. Sound.prototype.getVolume = function () {
  63827. return this._volume;
  63828. };
  63829. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63830. var _this = this;
  63831. if (this._connectedMesh && this._registerFunc) {
  63832. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63833. this._registerFunc = null;
  63834. }
  63835. this._connectedMesh = meshToConnectTo;
  63836. if (!this.spatialSound) {
  63837. this.spatialSound = true;
  63838. this._createSpatialParameters();
  63839. if (this.isPlaying && this.loop) {
  63840. this.stop();
  63841. this.play();
  63842. }
  63843. }
  63844. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63845. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63846. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63847. };
  63848. Sound.prototype.detachFromMesh = function () {
  63849. if (this._connectedMesh && this._registerFunc) {
  63850. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63851. this._registerFunc = null;
  63852. this._connectedMesh = null;
  63853. }
  63854. };
  63855. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63856. if (!node.getBoundingInfo) {
  63857. return;
  63858. }
  63859. var mesh = node;
  63860. var boundingInfo = mesh.getBoundingInfo();
  63861. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63862. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63863. this._updateDirection();
  63864. }
  63865. };
  63866. Sound.prototype.clone = function () {
  63867. var _this = this;
  63868. if (!this._streaming) {
  63869. var setBufferAndRun = function () {
  63870. if (_this._isReadyToPlay) {
  63871. clonedSound._audioBuffer = _this.getAudioBuffer();
  63872. clonedSound._isReadyToPlay = true;
  63873. if (clonedSound.autoplay) {
  63874. clonedSound.play();
  63875. }
  63876. }
  63877. else {
  63878. window.setTimeout(setBufferAndRun, 300);
  63879. }
  63880. };
  63881. var currentOptions = {
  63882. autoplay: this.autoplay, loop: this.loop,
  63883. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63884. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63885. refDistance: this.refDistance, distanceModel: this.distanceModel
  63886. };
  63887. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63888. if (this.useCustomAttenuation) {
  63889. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63890. }
  63891. clonedSound.setPosition(this._position);
  63892. clonedSound.setPlaybackRate(this._playbackRate);
  63893. setBufferAndRun();
  63894. return clonedSound;
  63895. }
  63896. // Can't clone a streaming sound
  63897. else {
  63898. return null;
  63899. }
  63900. };
  63901. Sound.prototype.getAudioBuffer = function () {
  63902. return this._audioBuffer;
  63903. };
  63904. Sound.prototype.serialize = function () {
  63905. var serializationObject = {
  63906. name: this.name,
  63907. url: this.name,
  63908. autoplay: this.autoplay,
  63909. loop: this.loop,
  63910. volume: this._volume,
  63911. spatialSound: this.spatialSound,
  63912. maxDistance: this.maxDistance,
  63913. rolloffFactor: this.rolloffFactor,
  63914. refDistance: this.refDistance,
  63915. distanceModel: this.distanceModel,
  63916. playbackRate: this._playbackRate,
  63917. panningModel: this._panningModel,
  63918. soundTrackId: this.soundTrackId
  63919. };
  63920. if (this.spatialSound) {
  63921. if (this._connectedMesh)
  63922. serializationObject.connectedMeshId = this._connectedMesh.id;
  63923. serializationObject.position = this._position.asArray();
  63924. serializationObject.refDistance = this.refDistance;
  63925. serializationObject.distanceModel = this.distanceModel;
  63926. serializationObject.isDirectional = this._isDirectional;
  63927. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63928. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63929. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63930. serializationObject.coneOuterGain = this._coneOuterGain;
  63931. }
  63932. return serializationObject;
  63933. };
  63934. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63935. var soundName = parsedSound.name;
  63936. var soundUrl;
  63937. if (parsedSound.url) {
  63938. soundUrl = rootUrl + parsedSound.url;
  63939. }
  63940. else {
  63941. soundUrl = rootUrl + soundName;
  63942. }
  63943. var options = {
  63944. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63945. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63946. rolloffFactor: parsedSound.rolloffFactor,
  63947. refDistance: parsedSound.refDistance,
  63948. distanceModel: parsedSound.distanceModel,
  63949. playbackRate: parsedSound.playbackRate
  63950. };
  63951. var newSound;
  63952. if (!sourceSound) {
  63953. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63954. scene._addPendingData(newSound);
  63955. }
  63956. else {
  63957. var setBufferAndRun = function () {
  63958. if (sourceSound._isReadyToPlay) {
  63959. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63960. newSound._isReadyToPlay = true;
  63961. if (newSound.autoplay) {
  63962. newSound.play();
  63963. }
  63964. }
  63965. else {
  63966. window.setTimeout(setBufferAndRun, 300);
  63967. }
  63968. };
  63969. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63970. setBufferAndRun();
  63971. }
  63972. if (parsedSound.position) {
  63973. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63974. newSound.setPosition(soundPosition);
  63975. }
  63976. if (parsedSound.isDirectional) {
  63977. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63978. if (parsedSound.localDirectionToMesh) {
  63979. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63980. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63981. }
  63982. }
  63983. if (parsedSound.connectedMeshId) {
  63984. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63985. if (connectedMesh) {
  63986. newSound.attachToMesh(connectedMesh);
  63987. }
  63988. }
  63989. return newSound;
  63990. };
  63991. return Sound;
  63992. }());
  63993. BABYLON.Sound = Sound;
  63994. })(BABYLON || (BABYLON = {}));
  63995. //# sourceMappingURL=babylon.sound.js.map
  63996. var BABYLON;
  63997. (function (BABYLON) {
  63998. var SoundTrack = /** @class */ (function () {
  63999. function SoundTrack(scene, options) {
  64000. this.id = -1;
  64001. this._isMainTrack = false;
  64002. this._isInitialized = false;
  64003. this._scene = scene;
  64004. this.soundCollection = new Array();
  64005. this._options = options;
  64006. if (!this._isMainTrack) {
  64007. this._scene.soundTracks.push(this);
  64008. this.id = this._scene.soundTracks.length - 1;
  64009. }
  64010. }
  64011. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64012. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64013. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64014. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64015. if (this._options) {
  64016. if (this._options.volume) {
  64017. this._outputAudioNode.gain.value = this._options.volume;
  64018. }
  64019. if (this._options.mainTrack) {
  64020. this._isMainTrack = this._options.mainTrack;
  64021. }
  64022. }
  64023. this._isInitialized = true;
  64024. }
  64025. };
  64026. SoundTrack.prototype.dispose = function () {
  64027. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64028. if (this._connectedAnalyser) {
  64029. this._connectedAnalyser.stopDebugCanvas();
  64030. }
  64031. while (this.soundCollection.length) {
  64032. this.soundCollection[0].dispose();
  64033. }
  64034. if (this._outputAudioNode) {
  64035. this._outputAudioNode.disconnect();
  64036. }
  64037. this._outputAudioNode = null;
  64038. }
  64039. };
  64040. SoundTrack.prototype.AddSound = function (sound) {
  64041. if (!this._isInitialized) {
  64042. this._initializeSoundTrackAudioGraph();
  64043. }
  64044. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64045. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64046. }
  64047. if (sound.soundTrackId) {
  64048. if (sound.soundTrackId === -1) {
  64049. this._scene.mainSoundTrack.RemoveSound(sound);
  64050. }
  64051. else {
  64052. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64053. }
  64054. }
  64055. this.soundCollection.push(sound);
  64056. sound.soundTrackId = this.id;
  64057. };
  64058. SoundTrack.prototype.RemoveSound = function (sound) {
  64059. var index = this.soundCollection.indexOf(sound);
  64060. if (index !== -1) {
  64061. this.soundCollection.splice(index, 1);
  64062. }
  64063. };
  64064. SoundTrack.prototype.setVolume = function (newVolume) {
  64065. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64066. this._outputAudioNode.gain.value = newVolume;
  64067. }
  64068. };
  64069. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64071. for (var i = 0; i < this.soundCollection.length; i++) {
  64072. this.soundCollection[i].switchPanningModelToHRTF();
  64073. }
  64074. }
  64075. };
  64076. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64077. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64078. for (var i = 0; i < this.soundCollection.length; i++) {
  64079. this.soundCollection[i].switchPanningModelToEqualPower();
  64080. }
  64081. }
  64082. };
  64083. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64084. if (this._connectedAnalyser) {
  64085. this._connectedAnalyser.stopDebugCanvas();
  64086. }
  64087. this._connectedAnalyser = analyser;
  64088. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64089. this._outputAudioNode.disconnect();
  64090. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64091. }
  64092. };
  64093. return SoundTrack;
  64094. }());
  64095. BABYLON.SoundTrack = SoundTrack;
  64096. })(BABYLON || (BABYLON = {}));
  64097. //# sourceMappingURL=babylon.soundtrack.js.map
  64098. var BABYLON;
  64099. (function (BABYLON) {
  64100. /**
  64101. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64102. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64103. */
  64104. var Analyser = /** @class */ (function () {
  64105. /**
  64106. * Creates a new analyser
  64107. * @param scene defines hosting scene
  64108. */
  64109. function Analyser(scene) {
  64110. /**
  64111. * Gets or sets the smoothing
  64112. * @ignorenaming
  64113. */
  64114. this.SMOOTHING = 0.75;
  64115. /**
  64116. * Gets or sets the FFT table size
  64117. * @ignorenaming
  64118. */
  64119. this.FFT_SIZE = 512;
  64120. /**
  64121. * Gets or sets the bar graph amplitude
  64122. * @ignorenaming
  64123. */
  64124. this.BARGRAPHAMPLITUDE = 256;
  64125. /**
  64126. * Gets or sets the position of the debug canvas
  64127. * @ignorenaming
  64128. */
  64129. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64130. /**
  64131. * Gets or sets the debug canvas size
  64132. * @ignorenaming
  64133. */
  64134. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64135. this._scene = scene;
  64136. this._audioEngine = BABYLON.Engine.audioEngine;
  64137. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64138. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64139. this._webAudioAnalyser.minDecibels = -140;
  64140. this._webAudioAnalyser.maxDecibels = 0;
  64141. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64142. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64143. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64144. }
  64145. }
  64146. /**
  64147. * Get the number of data values you will have to play with for the visualization
  64148. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64149. * @returns a number
  64150. */
  64151. Analyser.prototype.getFrequencyBinCount = function () {
  64152. if (this._audioEngine.canUseWebAudio) {
  64153. return this._webAudioAnalyser.frequencyBinCount;
  64154. }
  64155. else {
  64156. return 0;
  64157. }
  64158. };
  64159. /**
  64160. * Gets the current frequency data as a byte array
  64161. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64162. * @returns a Uint8Array
  64163. */
  64164. Analyser.prototype.getByteFrequencyData = function () {
  64165. if (this._audioEngine.canUseWebAudio) {
  64166. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64167. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64168. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64169. }
  64170. return this._byteFreqs;
  64171. };
  64172. /**
  64173. * Gets the current waveform as a byte array
  64174. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64175. * @returns a Uint8Array
  64176. */
  64177. Analyser.prototype.getByteTimeDomainData = function () {
  64178. if (this._audioEngine.canUseWebAudio) {
  64179. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64180. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64181. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64182. }
  64183. return this._byteTime;
  64184. };
  64185. /**
  64186. * Gets the current frequency data as a float array
  64187. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64188. * @returns a Float32Array
  64189. */
  64190. Analyser.prototype.getFloatFrequencyData = function () {
  64191. if (this._audioEngine.canUseWebAudio) {
  64192. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64193. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64194. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64195. }
  64196. return this._floatFreqs;
  64197. };
  64198. /**
  64199. * Renders the debug canvas
  64200. */
  64201. Analyser.prototype.drawDebugCanvas = function () {
  64202. var _this = this;
  64203. if (this._audioEngine.canUseWebAudio) {
  64204. if (!this._debugCanvas) {
  64205. this._debugCanvas = document.createElement("canvas");
  64206. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64207. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64208. this._debugCanvas.style.position = "absolute";
  64209. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64210. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64211. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64212. document.body.appendChild(this._debugCanvas);
  64213. this._registerFunc = function () {
  64214. _this.drawDebugCanvas();
  64215. };
  64216. this._scene.registerBeforeRender(this._registerFunc);
  64217. }
  64218. if (this._registerFunc && this._debugCanvasContext) {
  64219. var workingArray = this.getByteFrequencyData();
  64220. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64221. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64222. // Draw the frequency domain chart.
  64223. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64224. var value = workingArray[i];
  64225. var percent = value / this.BARGRAPHAMPLITUDE;
  64226. var height = this.DEBUGCANVASSIZE.height * percent;
  64227. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64228. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64229. var hue = i / this.getFrequencyBinCount() * 360;
  64230. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64231. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64232. }
  64233. }
  64234. }
  64235. };
  64236. /**
  64237. * Stops rendering the debug canvas and removes it
  64238. */
  64239. Analyser.prototype.stopDebugCanvas = function () {
  64240. if (this._debugCanvas) {
  64241. if (this._registerFunc) {
  64242. this._scene.unregisterBeforeRender(this._registerFunc);
  64243. this._registerFunc = null;
  64244. }
  64245. document.body.removeChild(this._debugCanvas);
  64246. this._debugCanvas = null;
  64247. this._debugCanvasContext = null;
  64248. }
  64249. };
  64250. /**
  64251. * Connects two audio nodes
  64252. * @param inputAudioNode defines first node to connect
  64253. * @param outputAudioNode defines second node to connect
  64254. */
  64255. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64256. if (this._audioEngine.canUseWebAudio) {
  64257. inputAudioNode.connect(this._webAudioAnalyser);
  64258. this._webAudioAnalyser.connect(outputAudioNode);
  64259. }
  64260. };
  64261. /**
  64262. * Releases all associated resources
  64263. */
  64264. Analyser.prototype.dispose = function () {
  64265. if (this._audioEngine.canUseWebAudio) {
  64266. this._webAudioAnalyser.disconnect();
  64267. }
  64268. };
  64269. return Analyser;
  64270. }());
  64271. BABYLON.Analyser = Analyser;
  64272. })(BABYLON || (BABYLON = {}));
  64273. //# sourceMappingURL=babylon.analyser.js.map
  64274. var BABYLON;
  64275. (function (BABYLON) {
  64276. var CubeTexture = /** @class */ (function (_super) {
  64277. __extends(CubeTexture, _super);
  64278. /**
  64279. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64280. * as prefiltered data.
  64281. * @param rootUrl defines the url of the texture or the root name of the six images
  64282. * @param scene defines the scene the texture is attached to
  64283. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64284. * @param noMipmap defines if mipmaps should be created or not
  64285. * @param files defines the six files to load for the different faces
  64286. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64287. * @param onError defines a callback triggered in case of error during load
  64288. * @param format defines the internal format to use for the texture once loaded
  64289. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64290. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64291. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64292. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64293. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64294. * @return the cube texture
  64295. */
  64296. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64297. if (extensions === void 0) { extensions = null; }
  64298. if (noMipmap === void 0) { noMipmap = false; }
  64299. if (files === void 0) { files = null; }
  64300. if (onLoad === void 0) { onLoad = null; }
  64301. if (onError === void 0) { onError = null; }
  64302. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64303. if (prefiltered === void 0) { prefiltered = false; }
  64304. if (forcedExtension === void 0) { forcedExtension = null; }
  64305. if (createPolynomials === void 0) { createPolynomials = false; }
  64306. if (lodScale === void 0) { lodScale = 0.8; }
  64307. if (lodOffset === void 0) { lodOffset = 0; }
  64308. var _this = _super.call(this, scene) || this;
  64309. /**
  64310. * Gets or sets the center of the bounding box associated with the cube texture
  64311. * It must define where the camera used to render the texture was set
  64312. */
  64313. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64314. _this._rotationY = 0;
  64315. /** @hidden */
  64316. _this._prefiltered = false;
  64317. _this.name = rootUrl;
  64318. _this.url = rootUrl;
  64319. _this._noMipmap = noMipmap;
  64320. _this.hasAlpha = false;
  64321. _this._format = format;
  64322. _this.isCube = true;
  64323. _this._textureMatrix = BABYLON.Matrix.Identity();
  64324. _this._createPolynomials = createPolynomials;
  64325. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64326. if (!rootUrl && !files) {
  64327. return _this;
  64328. }
  64329. var lastDot = rootUrl.lastIndexOf(".");
  64330. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64331. var isDDS = (extension === ".dds");
  64332. var isEnv = (extension === ".env");
  64333. if (isEnv) {
  64334. _this.gammaSpace = false;
  64335. _this._prefiltered = false;
  64336. }
  64337. else {
  64338. _this._prefiltered = prefiltered;
  64339. if (prefiltered) {
  64340. _this.gammaSpace = false;
  64341. }
  64342. }
  64343. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64344. if (!files) {
  64345. if (!isEnv && !isDDS && !extensions) {
  64346. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64347. }
  64348. files = [];
  64349. if (extensions) {
  64350. for (var index = 0; index < extensions.length; index++) {
  64351. files.push(rootUrl + extensions[index]);
  64352. }
  64353. }
  64354. }
  64355. _this._files = files;
  64356. if (!_this._texture) {
  64357. if (!scene.useDelayedTextureLoading) {
  64358. if (prefiltered) {
  64359. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64360. }
  64361. else {
  64362. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64363. }
  64364. }
  64365. else {
  64366. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64367. }
  64368. }
  64369. else if (onLoad) {
  64370. if (_this._texture.isReady) {
  64371. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64372. }
  64373. else {
  64374. _this._texture.onLoadedObservable.add(onLoad);
  64375. }
  64376. }
  64377. return _this;
  64378. }
  64379. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64380. get: function () {
  64381. return this._boundingBoxSize;
  64382. },
  64383. /**
  64384. * Gets or sets the size of the bounding box associated with the cube texture
  64385. * When defined, the cubemap will switch to local mode
  64386. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64387. * @example https://www.babylonjs-playground.com/#RNASML
  64388. */
  64389. set: function (value) {
  64390. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64391. return;
  64392. }
  64393. this._boundingBoxSize = value;
  64394. var scene = this.getScene();
  64395. if (scene) {
  64396. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64397. }
  64398. },
  64399. enumerable: true,
  64400. configurable: true
  64401. });
  64402. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64403. /**
  64404. * Gets texture matrix rotation angle around Y axis radians.
  64405. */
  64406. get: function () {
  64407. return this._rotationY;
  64408. },
  64409. /**
  64410. * Sets texture matrix rotation angle around Y axis in radians.
  64411. */
  64412. set: function (value) {
  64413. this._rotationY = value;
  64414. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64420. var rootUrlKey = "";
  64421. files.forEach(function (url) { return rootUrlKey += url; });
  64422. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64423. };
  64424. /**
  64425. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64426. * @param url defines the url of the prefiltered texture
  64427. * @param scene defines the scene the texture is attached to
  64428. * @param forcedExtension defines the extension of the file if different from the url
  64429. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64430. * @return the prefiltered texture
  64431. */
  64432. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64433. if (forcedExtension === void 0) { forcedExtension = null; }
  64434. if (createPolynomials === void 0) { createPolynomials = true; }
  64435. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64436. };
  64437. // Methods
  64438. CubeTexture.prototype.delayLoad = function () {
  64439. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64440. return;
  64441. }
  64442. var scene = this.getScene();
  64443. if (!scene) {
  64444. return;
  64445. }
  64446. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64447. this._texture = this._getFromCache(this.url, this._noMipmap);
  64448. if (!this._texture) {
  64449. if (this._prefiltered) {
  64450. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64451. }
  64452. else {
  64453. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64454. }
  64455. }
  64456. };
  64457. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64458. return this._textureMatrix;
  64459. };
  64460. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64461. this._textureMatrix = value;
  64462. };
  64463. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64464. var texture = BABYLON.SerializationHelper.Parse(function () {
  64465. var prefiltered = false;
  64466. if (parsedTexture.prefiltered) {
  64467. prefiltered = parsedTexture.prefiltered;
  64468. }
  64469. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64470. }, parsedTexture, scene);
  64471. // Local Cubemaps
  64472. if (parsedTexture.boundingBoxPosition) {
  64473. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64474. }
  64475. if (parsedTexture.boundingBoxSize) {
  64476. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64477. }
  64478. // Animations
  64479. if (parsedTexture.animations) {
  64480. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64481. var parsedAnimation = parsedTexture.animations[animationIndex];
  64482. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64483. }
  64484. }
  64485. return texture;
  64486. };
  64487. CubeTexture.prototype.clone = function () {
  64488. var _this = this;
  64489. return BABYLON.SerializationHelper.Clone(function () {
  64490. var scene = _this.getScene();
  64491. if (!scene) {
  64492. return _this;
  64493. }
  64494. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64495. }, this);
  64496. };
  64497. __decorate([
  64498. BABYLON.serialize("rotationY")
  64499. ], CubeTexture.prototype, "_rotationY", void 0);
  64500. return CubeTexture;
  64501. }(BABYLON.BaseTexture));
  64502. BABYLON.CubeTexture = CubeTexture;
  64503. })(BABYLON || (BABYLON = {}));
  64504. //# sourceMappingURL=babylon.cubeTexture.js.map
  64505. var BABYLON;
  64506. (function (BABYLON) {
  64507. /**
  64508. * Raw cube texture where the raw buffers are passed in
  64509. */
  64510. var RawCubeTexture = /** @class */ (function (_super) {
  64511. __extends(RawCubeTexture, _super);
  64512. /**
  64513. * Creates a cube texture where the raw buffers are passed in.
  64514. * @param scene defines the scene the texture is attached to
  64515. * @param data defines the array of data to use to create each face
  64516. * @param size defines the size of the textures
  64517. * @param format defines the format of the data
  64518. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64519. * @param generateMipMaps defines if the engine should generate the mip levels
  64520. * @param invertY defines if data must be stored with Y axis inverted
  64521. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64522. * @param compression defines the compression used (null by default)
  64523. */
  64524. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64525. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64526. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64527. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64528. if (invertY === void 0) { invertY = false; }
  64529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64530. if (compression === void 0) { compression = null; }
  64531. var _this = _super.call(this, "", scene) || this;
  64532. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64533. return _this;
  64534. }
  64535. /**
  64536. * Updates the raw cube texture.
  64537. * @param data defines the data to store
  64538. * @param format defines the data format
  64539. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64540. * @param invertY defines if data must be stored with Y axis inverted
  64541. * @param compression defines the compression used (null by default)
  64542. * @param level defines which level of the texture to update
  64543. */
  64544. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64545. if (compression === void 0) { compression = null; }
  64546. if (level === void 0) { level = 0; }
  64547. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64548. };
  64549. /**
  64550. * Updates a raw cube texture with RGBD encoded data.
  64551. * @param data defines the array of data [mipmap][face] to use to create each face
  64552. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64553. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64554. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64555. * @returns a promsie that resolves when the operation is complete
  64556. */
  64557. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64558. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64559. if (lodScale === void 0) { lodScale = 0.8; }
  64560. if (lodOffset === void 0) { lodOffset = 0; }
  64561. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64562. };
  64563. /**
  64564. * Clones the raw cube texture.
  64565. * @return a new cube texture
  64566. */
  64567. RawCubeTexture.prototype.clone = function () {
  64568. var _this = this;
  64569. return BABYLON.SerializationHelper.Clone(function () {
  64570. var scene = _this.getScene();
  64571. var internalTexture = _this._texture;
  64572. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64573. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64574. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64575. }
  64576. return texture;
  64577. }, this);
  64578. };
  64579. /** @hidden */
  64580. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64581. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64582. internalTexture._bufferViewArrayArray = data;
  64583. internalTexture._lodGenerationScale = lodScale;
  64584. internalTexture._lodGenerationOffset = lodOffset;
  64585. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64586. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64587. internalTexture.isReady = true;
  64588. });
  64589. };
  64590. return RawCubeTexture;
  64591. }(BABYLON.CubeTexture));
  64592. BABYLON.RawCubeTexture = RawCubeTexture;
  64593. })(BABYLON || (BABYLON = {}));
  64594. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64595. var BABYLON;
  64596. (function (BABYLON) {
  64597. var RenderTargetTexture = /** @class */ (function (_super) {
  64598. __extends(RenderTargetTexture, _super);
  64599. /**
  64600. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64601. * or used a shadow, depth texture...
  64602. * @param name The friendly name of the texture
  64603. * @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)
  64604. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64605. * @param generateMipMaps True if mip maps need to be generated after render.
  64606. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64607. * @param type The type of the buffer in the RTT (int, half float, float...)
  64608. * @param isCube True if a cube texture needs to be created
  64609. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64610. * @param generateDepthBuffer True to generate a depth buffer
  64611. * @param generateStencilBuffer True to generate a stencil buffer
  64612. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64613. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64614. */
  64615. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64616. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64617. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64618. if (isCube === void 0) { isCube = false; }
  64619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64620. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64621. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64622. if (isMulti === void 0) { isMulti = false; }
  64623. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64624. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64625. _this.isCube = isCube;
  64626. /**
  64627. * Use this list to define the list of mesh you want to render.
  64628. */
  64629. _this.renderList = new Array();
  64630. _this.renderParticles = true;
  64631. _this.renderSprites = false;
  64632. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64633. _this.ignoreCameraViewport = false;
  64634. // Events
  64635. /**
  64636. * An event triggered when the texture is unbind.
  64637. */
  64638. _this.onBeforeBindObservable = new BABYLON.Observable();
  64639. /**
  64640. * An event triggered when the texture is unbind.
  64641. */
  64642. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64643. /**
  64644. * An event triggered before rendering the texture
  64645. */
  64646. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64647. /**
  64648. * An event triggered after rendering the texture
  64649. */
  64650. _this.onAfterRenderObservable = new BABYLON.Observable();
  64651. /**
  64652. * An event triggered after the texture clear
  64653. */
  64654. _this.onClearObservable = new BABYLON.Observable();
  64655. _this._currentRefreshId = -1;
  64656. _this._refreshRate = 1;
  64657. _this._samples = 1;
  64658. /**
  64659. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64660. * It must define where the camera used to render the texture is set
  64661. */
  64662. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64663. scene = _this.getScene();
  64664. if (!scene) {
  64665. return _this;
  64666. }
  64667. _this._engine = scene.getEngine();
  64668. _this.name = name;
  64669. _this.isRenderTarget = true;
  64670. _this._initialSizeParameter = size;
  64671. _this._processSizeParameter(size);
  64672. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64673. });
  64674. _this._generateMipMaps = generateMipMaps ? true : false;
  64675. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64676. // Rendering groups
  64677. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64678. _this._renderingManager._useSceneAutoClearSetup = true;
  64679. if (isMulti) {
  64680. return _this;
  64681. }
  64682. _this._renderTargetOptions = {
  64683. generateMipMaps: generateMipMaps,
  64684. type: type,
  64685. format: format,
  64686. samplingMode: samplingMode,
  64687. generateDepthBuffer: generateDepthBuffer,
  64688. generateStencilBuffer: generateStencilBuffer
  64689. };
  64690. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  64691. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64692. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64693. }
  64694. if (isCube) {
  64695. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  64696. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  64697. _this._textureMatrix = BABYLON.Matrix.Identity();
  64698. }
  64699. else {
  64700. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  64701. }
  64702. return _this;
  64703. }
  64704. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  64705. get: function () {
  64706. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  64707. },
  64708. enumerable: true,
  64709. configurable: true
  64710. });
  64711. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  64712. get: function () {
  64713. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  64714. },
  64715. enumerable: true,
  64716. configurable: true
  64717. });
  64718. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64719. get: function () {
  64720. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64721. },
  64722. enumerable: true,
  64723. configurable: true
  64724. });
  64725. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64726. set: function (callback) {
  64727. if (this._onAfterUnbindObserver) {
  64728. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64729. }
  64730. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64731. },
  64732. enumerable: true,
  64733. configurable: true
  64734. });
  64735. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64736. set: function (callback) {
  64737. if (this._onBeforeRenderObserver) {
  64738. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64739. }
  64740. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64741. },
  64742. enumerable: true,
  64743. configurable: true
  64744. });
  64745. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64746. set: function (callback) {
  64747. if (this._onAfterRenderObserver) {
  64748. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64749. }
  64750. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64756. set: function (callback) {
  64757. if (this._onClearObserver) {
  64758. this.onClearObservable.remove(this._onClearObserver);
  64759. }
  64760. this._onClearObserver = this.onClearObservable.add(callback);
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64766. get: function () {
  64767. return this._renderTargetOptions;
  64768. },
  64769. enumerable: true,
  64770. configurable: true
  64771. });
  64772. RenderTargetTexture.prototype._onRatioRescale = function () {
  64773. if (this._sizeRatio) {
  64774. this.resize(this._initialSizeParameter);
  64775. }
  64776. };
  64777. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64778. get: function () {
  64779. return this._boundingBoxSize;
  64780. },
  64781. /**
  64782. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64783. * When defined, the cubemap will switch to local mode
  64784. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64785. * @example https://www.babylonjs-playground.com/#RNASML
  64786. */
  64787. set: function (value) {
  64788. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64789. return;
  64790. }
  64791. this._boundingBoxSize = value;
  64792. var scene = this.getScene();
  64793. if (scene) {
  64794. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64795. }
  64796. },
  64797. enumerable: true,
  64798. configurable: true
  64799. });
  64800. /**
  64801. * Creates a depth stencil texture.
  64802. * This is only available in WebGL 2 or with the depth texture extension available.
  64803. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64804. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64805. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64806. */
  64807. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64808. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64809. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64810. if (generateStencil === void 0) { generateStencil = false; }
  64811. if (!this.getScene()) {
  64812. return;
  64813. }
  64814. var engine = this.getScene().getEngine();
  64815. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64816. bilinearFiltering: bilinearFiltering,
  64817. comparisonFunction: comparisonFunction,
  64818. generateStencil: generateStencil,
  64819. isCube: this.isCube
  64820. });
  64821. engine.setFrameBufferDepthStencilTexture(this);
  64822. };
  64823. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64824. if (size.ratio) {
  64825. this._sizeRatio = size.ratio;
  64826. this._size = {
  64827. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64828. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64829. };
  64830. }
  64831. else {
  64832. this._size = size;
  64833. }
  64834. };
  64835. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64836. get: function () {
  64837. return this._samples;
  64838. },
  64839. set: function (value) {
  64840. if (this._samples === value) {
  64841. return;
  64842. }
  64843. var scene = this.getScene();
  64844. if (!scene) {
  64845. return;
  64846. }
  64847. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64848. },
  64849. enumerable: true,
  64850. configurable: true
  64851. });
  64852. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64853. this._currentRefreshId = -1;
  64854. };
  64855. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64856. get: function () {
  64857. return this._refreshRate;
  64858. },
  64859. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64860. set: function (value) {
  64861. this._refreshRate = value;
  64862. this.resetRefreshCounter();
  64863. },
  64864. enumerable: true,
  64865. configurable: true
  64866. });
  64867. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64868. if (!this._postProcessManager) {
  64869. var scene = this.getScene();
  64870. if (!scene) {
  64871. return;
  64872. }
  64873. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64874. this._postProcesses = new Array();
  64875. }
  64876. this._postProcesses.push(postProcess);
  64877. this._postProcesses[0].autoClear = false;
  64878. };
  64879. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64880. if (!this._postProcesses) {
  64881. return;
  64882. }
  64883. if (dispose) {
  64884. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64885. var postProcess = _a[_i];
  64886. postProcess.dispose();
  64887. }
  64888. }
  64889. this._postProcesses = [];
  64890. };
  64891. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64892. if (!this._postProcesses) {
  64893. return;
  64894. }
  64895. var index = this._postProcesses.indexOf(postProcess);
  64896. if (index === -1) {
  64897. return;
  64898. }
  64899. this._postProcesses.splice(index, 1);
  64900. if (this._postProcesses.length > 0) {
  64901. this._postProcesses[0].autoClear = false;
  64902. }
  64903. };
  64904. RenderTargetTexture.prototype._shouldRender = function () {
  64905. if (this._currentRefreshId === -1) { // At least render once
  64906. this._currentRefreshId = 1;
  64907. return true;
  64908. }
  64909. if (this.refreshRate === this._currentRefreshId) {
  64910. this._currentRefreshId = 1;
  64911. return true;
  64912. }
  64913. this._currentRefreshId++;
  64914. return false;
  64915. };
  64916. RenderTargetTexture.prototype.getRenderSize = function () {
  64917. if (this._size.width) {
  64918. return this._size.width;
  64919. }
  64920. return this._size;
  64921. };
  64922. RenderTargetTexture.prototype.getRenderWidth = function () {
  64923. if (this._size.width) {
  64924. return this._size.width;
  64925. }
  64926. return this._size;
  64927. };
  64928. RenderTargetTexture.prototype.getRenderHeight = function () {
  64929. if (this._size.width) {
  64930. return this._size.height;
  64931. }
  64932. return this._size;
  64933. };
  64934. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64935. get: function () {
  64936. return true;
  64937. },
  64938. enumerable: true,
  64939. configurable: true
  64940. });
  64941. RenderTargetTexture.prototype.scale = function (ratio) {
  64942. var newSize = this.getRenderSize() * ratio;
  64943. this.resize(newSize);
  64944. };
  64945. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64946. if (this.isCube) {
  64947. return this._textureMatrix;
  64948. }
  64949. return _super.prototype.getReflectionTextureMatrix.call(this);
  64950. };
  64951. RenderTargetTexture.prototype.resize = function (size) {
  64952. this.releaseInternalTexture();
  64953. var scene = this.getScene();
  64954. if (!scene) {
  64955. return;
  64956. }
  64957. this._processSizeParameter(size);
  64958. if (this.isCube) {
  64959. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64960. }
  64961. else {
  64962. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64963. }
  64964. };
  64965. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64966. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64967. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64968. var scene = this.getScene();
  64969. if (!scene) {
  64970. return;
  64971. }
  64972. var engine = scene.getEngine();
  64973. if (this.useCameraPostProcesses !== undefined) {
  64974. useCameraPostProcess = this.useCameraPostProcesses;
  64975. }
  64976. if (this._waitingRenderList) {
  64977. this.renderList = [];
  64978. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64979. var id = this._waitingRenderList[index];
  64980. var mesh_1 = scene.getMeshByID(id);
  64981. if (mesh_1) {
  64982. this.renderList.push(mesh_1);
  64983. }
  64984. }
  64985. delete this._waitingRenderList;
  64986. }
  64987. // Is predicate defined?
  64988. if (this.renderListPredicate) {
  64989. if (this.renderList) {
  64990. this.renderList.splice(0); // Clear previous renderList
  64991. }
  64992. else {
  64993. this.renderList = [];
  64994. }
  64995. var scene = this.getScene();
  64996. if (!scene) {
  64997. return;
  64998. }
  64999. var sceneMeshes = scene.meshes;
  65000. for (var index = 0; index < sceneMeshes.length; index++) {
  65001. var mesh = sceneMeshes[index];
  65002. if (this.renderListPredicate(mesh)) {
  65003. this.renderList.push(mesh);
  65004. }
  65005. }
  65006. }
  65007. this.onBeforeBindObservable.notifyObservers(this);
  65008. // Set custom projection.
  65009. // Needs to be before binding to prevent changing the aspect ratio.
  65010. var camera;
  65011. if (this.activeCamera) {
  65012. camera = this.activeCamera;
  65013. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65014. if (this.activeCamera !== scene.activeCamera) {
  65015. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65016. }
  65017. }
  65018. else {
  65019. camera = scene.activeCamera;
  65020. if (camera) {
  65021. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65022. }
  65023. }
  65024. // Prepare renderingManager
  65025. this._renderingManager.reset();
  65026. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65027. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65028. var sceneRenderId = scene.getRenderId();
  65029. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65030. var mesh = currentRenderList[meshIndex];
  65031. if (mesh) {
  65032. if (!mesh.isReady(this.refreshRate === 0)) {
  65033. this.resetRefreshCounter();
  65034. continue;
  65035. }
  65036. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65037. var isMasked = void 0;
  65038. if (!this.renderList && camera) {
  65039. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65040. }
  65041. else {
  65042. isMasked = false;
  65043. }
  65044. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65045. mesh._activate(sceneRenderId);
  65046. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65047. var subMesh = mesh.subMeshes[subIndex];
  65048. scene._activeIndices.addCount(subMesh.indexCount, false);
  65049. this._renderingManager.dispatch(subMesh, mesh);
  65050. }
  65051. }
  65052. }
  65053. }
  65054. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65055. var particleSystem = scene.particleSystems[particleIndex];
  65056. var emitter = particleSystem.emitter;
  65057. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65058. continue;
  65059. }
  65060. if (currentRenderList.indexOf(emitter) >= 0) {
  65061. this._renderingManager.dispatchParticles(particleSystem);
  65062. }
  65063. }
  65064. if (this.isCube) {
  65065. for (var face = 0; face < 6; face++) {
  65066. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65067. scene.incrementRenderId();
  65068. scene.resetCachedMaterial();
  65069. }
  65070. }
  65071. else {
  65072. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65073. }
  65074. this.onAfterUnbindObservable.notifyObservers(this);
  65075. if (scene.activeCamera) {
  65076. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65077. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65078. }
  65079. engine.setViewport(scene.activeCamera.viewport);
  65080. }
  65081. scene.resetCachedMaterial();
  65082. };
  65083. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65084. var minimum = 128;
  65085. var x = renderDimension * scale;
  65086. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65087. // Ensure we don't exceed the render dimension (while staying POT)
  65088. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65089. };
  65090. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65091. var _this = this;
  65092. if (!this._texture) {
  65093. return;
  65094. }
  65095. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65096. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65097. });
  65098. };
  65099. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65100. var scene = this.getScene();
  65101. if (!scene) {
  65102. return;
  65103. }
  65104. var engine = scene.getEngine();
  65105. if (!this._texture) {
  65106. return;
  65107. }
  65108. // Bind
  65109. if (this._postProcessManager) {
  65110. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65111. }
  65112. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65113. if (this._texture) {
  65114. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65115. }
  65116. }
  65117. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65118. // Clear
  65119. if (this.onClearObservable.hasObservers()) {
  65120. this.onClearObservable.notifyObservers(engine);
  65121. }
  65122. else {
  65123. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65124. }
  65125. if (!this._doNotChangeAspectRatio) {
  65126. scene.updateTransformMatrix(true);
  65127. }
  65128. // Render
  65129. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65130. if (this._postProcessManager) {
  65131. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65132. }
  65133. else if (useCameraPostProcess) {
  65134. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65135. }
  65136. if (!this._doNotChangeAspectRatio) {
  65137. scene.updateTransformMatrix(true);
  65138. }
  65139. // Dump ?
  65140. if (dumpForDebug) {
  65141. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65142. }
  65143. // Unbind
  65144. if (!this.isCube || faceIndex === 5) {
  65145. if (this.isCube) {
  65146. if (faceIndex === 5) {
  65147. engine.generateMipMapsForCubemap(this._texture);
  65148. }
  65149. }
  65150. this.unbindFrameBuffer(engine, faceIndex);
  65151. }
  65152. else {
  65153. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65154. }
  65155. };
  65156. /**
  65157. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65158. * This allowed control for front to back rendering or reversly depending of the special needs.
  65159. *
  65160. * @param renderingGroupId The rendering group id corresponding to its index
  65161. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65162. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65163. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65164. */
  65165. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65166. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65167. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65168. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65169. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65170. };
  65171. /**
  65172. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65173. *
  65174. * @param renderingGroupId The rendering group id corresponding to its index
  65175. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65176. */
  65177. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65178. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65179. this._renderingManager._useSceneAutoClearSetup = false;
  65180. };
  65181. RenderTargetTexture.prototype.clone = function () {
  65182. var textureSize = this.getSize();
  65183. 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);
  65184. // Base texture
  65185. newTexture.hasAlpha = this.hasAlpha;
  65186. newTexture.level = this.level;
  65187. // RenderTarget Texture
  65188. newTexture.coordinatesMode = this.coordinatesMode;
  65189. if (this.renderList) {
  65190. newTexture.renderList = this.renderList.slice(0);
  65191. }
  65192. return newTexture;
  65193. };
  65194. RenderTargetTexture.prototype.serialize = function () {
  65195. if (!this.name) {
  65196. return null;
  65197. }
  65198. var serializationObject = _super.prototype.serialize.call(this);
  65199. serializationObject.renderTargetSize = this.getRenderSize();
  65200. serializationObject.renderList = [];
  65201. if (this.renderList) {
  65202. for (var index = 0; index < this.renderList.length; index++) {
  65203. serializationObject.renderList.push(this.renderList[index].id);
  65204. }
  65205. }
  65206. return serializationObject;
  65207. };
  65208. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65209. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65210. var objBuffer = this.getInternalTexture();
  65211. var scene = this.getScene();
  65212. if (objBuffer && scene) {
  65213. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65214. }
  65215. };
  65216. RenderTargetTexture.prototype.dispose = function () {
  65217. if (this._postProcessManager) {
  65218. this._postProcessManager.dispose();
  65219. this._postProcessManager = null;
  65220. }
  65221. this.clearPostProcesses(true);
  65222. if (this._resizeObserver) {
  65223. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65224. this._resizeObserver = null;
  65225. }
  65226. this.renderList = null;
  65227. // Remove from custom render targets
  65228. var scene = this.getScene();
  65229. if (!scene) {
  65230. return;
  65231. }
  65232. var index = scene.customRenderTargets.indexOf(this);
  65233. if (index >= 0) {
  65234. scene.customRenderTargets.splice(index, 1);
  65235. }
  65236. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65237. var camera = _a[_i];
  65238. index = camera.customRenderTargets.indexOf(this);
  65239. if (index >= 0) {
  65240. camera.customRenderTargets.splice(index, 1);
  65241. }
  65242. }
  65243. _super.prototype.dispose.call(this);
  65244. };
  65245. RenderTargetTexture.prototype._rebuild = function () {
  65246. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65247. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65248. }
  65249. if (this._postProcessManager) {
  65250. this._postProcessManager._rebuild();
  65251. }
  65252. };
  65253. /**
  65254. * Clear the info related to rendering groups preventing retention point in material dispose.
  65255. */
  65256. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65257. if (this._renderingManager) {
  65258. this._renderingManager.freeRenderingGroups();
  65259. }
  65260. };
  65261. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65262. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65263. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65264. return RenderTargetTexture;
  65265. }(BABYLON.Texture));
  65266. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65267. })(BABYLON || (BABYLON = {}));
  65268. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65269. var BABYLON;
  65270. (function (BABYLON) {
  65271. ;
  65272. var MultiRenderTarget = /** @class */ (function (_super) {
  65273. __extends(MultiRenderTarget, _super);
  65274. function MultiRenderTarget(name, size, count, scene, options) {
  65275. var _this = this;
  65276. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65277. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65278. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65279. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65280. _this._engine = scene.getEngine();
  65281. if (!_this.isSupported) {
  65282. _this.dispose();
  65283. return;
  65284. }
  65285. var types = [];
  65286. var samplingModes = [];
  65287. for (var i = 0; i < count; i++) {
  65288. if (options && options.types && options.types[i] !== undefined) {
  65289. types.push(options.types[i]);
  65290. }
  65291. else {
  65292. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65293. }
  65294. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65295. samplingModes.push(options.samplingModes[i]);
  65296. }
  65297. else {
  65298. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65299. }
  65300. }
  65301. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65302. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65303. _this._size = size;
  65304. _this._multiRenderTargetOptions = {
  65305. samplingModes: samplingModes,
  65306. generateMipMaps: generateMipMaps,
  65307. generateDepthBuffer: generateDepthBuffer,
  65308. generateStencilBuffer: generateStencilBuffer,
  65309. generateDepthTexture: generateDepthTexture,
  65310. types: types,
  65311. textureCount: count
  65312. };
  65313. _this._createInternalTextures();
  65314. _this._createTextures();
  65315. return _this;
  65316. }
  65317. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65318. get: function () {
  65319. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65320. },
  65321. enumerable: true,
  65322. configurable: true
  65323. });
  65324. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65325. get: function () {
  65326. return this._textures;
  65327. },
  65328. enumerable: true,
  65329. configurable: true
  65330. });
  65331. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65332. get: function () {
  65333. return this._textures[this._textures.length - 1];
  65334. },
  65335. enumerable: true,
  65336. configurable: true
  65337. });
  65338. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65339. set: function (wrap) {
  65340. if (this._textures) {
  65341. for (var i = 0; i < this._textures.length; i++) {
  65342. this._textures[i].wrapU = wrap;
  65343. }
  65344. }
  65345. },
  65346. enumerable: true,
  65347. configurable: true
  65348. });
  65349. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65350. set: function (wrap) {
  65351. if (this._textures) {
  65352. for (var i = 0; i < this._textures.length; i++) {
  65353. this._textures[i].wrapV = wrap;
  65354. }
  65355. }
  65356. },
  65357. enumerable: true,
  65358. configurable: true
  65359. });
  65360. MultiRenderTarget.prototype._rebuild = function () {
  65361. this.releaseInternalTextures();
  65362. this._createInternalTextures();
  65363. for (var i = 0; i < this._internalTextures.length; i++) {
  65364. var texture = this._textures[i];
  65365. texture._texture = this._internalTextures[i];
  65366. }
  65367. // Keeps references to frame buffer and stencil/depth buffer
  65368. this._texture = this._internalTextures[0];
  65369. };
  65370. MultiRenderTarget.prototype._createInternalTextures = function () {
  65371. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65372. };
  65373. MultiRenderTarget.prototype._createTextures = function () {
  65374. this._textures = [];
  65375. for (var i = 0; i < this._internalTextures.length; i++) {
  65376. var texture = new BABYLON.Texture(null, this.getScene());
  65377. texture._texture = this._internalTextures[i];
  65378. this._textures.push(texture);
  65379. }
  65380. // Keeps references to frame buffer and stencil/depth buffer
  65381. this._texture = this._internalTextures[0];
  65382. };
  65383. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65384. get: function () {
  65385. return this._samples;
  65386. },
  65387. set: function (value) {
  65388. if (this._samples === value) {
  65389. return;
  65390. }
  65391. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65392. },
  65393. enumerable: true,
  65394. configurable: true
  65395. });
  65396. MultiRenderTarget.prototype.resize = function (size) {
  65397. this.releaseInternalTextures();
  65398. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65399. this._createInternalTextures();
  65400. };
  65401. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65402. var _this = this;
  65403. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65404. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65405. });
  65406. };
  65407. MultiRenderTarget.prototype.dispose = function () {
  65408. this.releaseInternalTextures();
  65409. _super.prototype.dispose.call(this);
  65410. };
  65411. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65412. if (!this._internalTextures) {
  65413. return;
  65414. }
  65415. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65416. if (this._internalTextures[i] !== undefined) {
  65417. this._internalTextures[i].dispose();
  65418. this._internalTextures.splice(i, 1);
  65419. }
  65420. }
  65421. };
  65422. return MultiRenderTarget;
  65423. }(BABYLON.RenderTargetTexture));
  65424. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65425. })(BABYLON || (BABYLON = {}));
  65426. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65427. var BABYLON;
  65428. (function (BABYLON) {
  65429. var MirrorTexture = /** @class */ (function (_super) {
  65430. __extends(MirrorTexture, _super);
  65431. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65432. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65434. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65435. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65436. _this.scene = scene;
  65437. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65438. _this._transformMatrix = BABYLON.Matrix.Zero();
  65439. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65440. _this._adaptiveBlurKernel = 0;
  65441. _this._blurKernelX = 0;
  65442. _this._blurKernelY = 0;
  65443. _this._blurRatio = 1.0;
  65444. _this.ignoreCameraViewport = true;
  65445. _this._updateGammaSpace();
  65446. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65447. _this._updateGammaSpace;
  65448. });
  65449. _this.onBeforeRenderObservable.add(function () {
  65450. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65451. _this._savedViewMatrix = scene.getViewMatrix();
  65452. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65453. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65454. scene.clipPlane = _this.mirrorPlane;
  65455. scene.getEngine().cullBackFaces = false;
  65456. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65457. });
  65458. _this.onAfterRenderObservable.add(function () {
  65459. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65460. scene.getEngine().cullBackFaces = true;
  65461. scene._mirroredCameraPosition = null;
  65462. delete scene.clipPlane;
  65463. });
  65464. return _this;
  65465. }
  65466. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65467. get: function () {
  65468. return this._blurRatio;
  65469. },
  65470. set: function (value) {
  65471. if (this._blurRatio === value) {
  65472. return;
  65473. }
  65474. this._blurRatio = value;
  65475. this._preparePostProcesses();
  65476. },
  65477. enumerable: true,
  65478. configurable: true
  65479. });
  65480. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65481. set: function (value) {
  65482. this._adaptiveBlurKernel = value;
  65483. this._autoComputeBlurKernel();
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65489. set: function (value) {
  65490. this.blurKernelX = value;
  65491. this.blurKernelY = value;
  65492. },
  65493. enumerable: true,
  65494. configurable: true
  65495. });
  65496. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65497. get: function () {
  65498. return this._blurKernelX;
  65499. },
  65500. set: function (value) {
  65501. if (this._blurKernelX === value) {
  65502. return;
  65503. }
  65504. this._blurKernelX = value;
  65505. this._preparePostProcesses();
  65506. },
  65507. enumerable: true,
  65508. configurable: true
  65509. });
  65510. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65511. get: function () {
  65512. return this._blurKernelY;
  65513. },
  65514. set: function (value) {
  65515. if (this._blurKernelY === value) {
  65516. return;
  65517. }
  65518. this._blurKernelY = value;
  65519. this._preparePostProcesses();
  65520. },
  65521. enumerable: true,
  65522. configurable: true
  65523. });
  65524. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65525. var engine = this.getScene().getEngine();
  65526. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65527. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65528. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65529. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65530. };
  65531. MirrorTexture.prototype._onRatioRescale = function () {
  65532. if (this._sizeRatio) {
  65533. this.resize(this._initialSizeParameter);
  65534. if (!this._adaptiveBlurKernel) {
  65535. this._preparePostProcesses();
  65536. }
  65537. }
  65538. if (this._adaptiveBlurKernel) {
  65539. this._autoComputeBlurKernel();
  65540. }
  65541. };
  65542. MirrorTexture.prototype._updateGammaSpace = function () {
  65543. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65544. };
  65545. MirrorTexture.prototype._preparePostProcesses = function () {
  65546. this.clearPostProcesses(true);
  65547. if (this._blurKernelX && this._blurKernelY) {
  65548. var engine = this.getScene().getEngine();
  65549. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65550. 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);
  65551. this._blurX.autoClear = false;
  65552. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65553. this._blurX.inputTexture = this._texture;
  65554. }
  65555. else {
  65556. this._blurX.alwaysForcePOT = true;
  65557. }
  65558. 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);
  65559. this._blurY.autoClear = false;
  65560. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65561. this.addPostProcess(this._blurX);
  65562. this.addPostProcess(this._blurY);
  65563. }
  65564. else {
  65565. if (this._blurY) {
  65566. this.removePostProcess(this._blurY);
  65567. this._blurY.dispose();
  65568. this._blurY = null;
  65569. }
  65570. if (this._blurX) {
  65571. this.removePostProcess(this._blurX);
  65572. this._blurX.dispose();
  65573. this._blurX = null;
  65574. }
  65575. }
  65576. };
  65577. MirrorTexture.prototype.clone = function () {
  65578. var scene = this.getScene();
  65579. if (!scene) {
  65580. return this;
  65581. }
  65582. var textureSize = this.getSize();
  65583. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65584. // Base texture
  65585. newTexture.hasAlpha = this.hasAlpha;
  65586. newTexture.level = this.level;
  65587. // Mirror Texture
  65588. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65589. if (this.renderList) {
  65590. newTexture.renderList = this.renderList.slice(0);
  65591. }
  65592. return newTexture;
  65593. };
  65594. MirrorTexture.prototype.serialize = function () {
  65595. if (!this.name) {
  65596. return null;
  65597. }
  65598. var serializationObject = _super.prototype.serialize.call(this);
  65599. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65600. return serializationObject;
  65601. };
  65602. MirrorTexture.prototype.dispose = function () {
  65603. _super.prototype.dispose.call(this);
  65604. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65605. };
  65606. return MirrorTexture;
  65607. }(BABYLON.RenderTargetTexture));
  65608. BABYLON.MirrorTexture = MirrorTexture;
  65609. })(BABYLON || (BABYLON = {}));
  65610. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65611. var BABYLON;
  65612. (function (BABYLON) {
  65613. /**
  65614. * Creates a refraction texture used by refraction channel of the standard material.
  65615. * @param name the texture name
  65616. * @param size size of the underlying texture
  65617. * @param scene root scene
  65618. */
  65619. var RefractionTexture = /** @class */ (function (_super) {
  65620. __extends(RefractionTexture, _super);
  65621. function RefractionTexture(name, size, scene, generateMipMaps) {
  65622. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65623. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65624. _this.depth = 2.0;
  65625. _this.onBeforeRenderObservable.add(function () {
  65626. scene.clipPlane = _this.refractionPlane;
  65627. });
  65628. _this.onAfterRenderObservable.add(function () {
  65629. delete scene.clipPlane;
  65630. });
  65631. return _this;
  65632. }
  65633. RefractionTexture.prototype.clone = function () {
  65634. var scene = this.getScene();
  65635. if (!scene) {
  65636. return this;
  65637. }
  65638. var textureSize = this.getSize();
  65639. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65640. // Base texture
  65641. newTexture.hasAlpha = this.hasAlpha;
  65642. newTexture.level = this.level;
  65643. // Refraction Texture
  65644. newTexture.refractionPlane = this.refractionPlane.clone();
  65645. if (this.renderList) {
  65646. newTexture.renderList = this.renderList.slice(0);
  65647. }
  65648. newTexture.depth = this.depth;
  65649. return newTexture;
  65650. };
  65651. RefractionTexture.prototype.serialize = function () {
  65652. if (!this.name) {
  65653. return null;
  65654. }
  65655. var serializationObject = _super.prototype.serialize.call(this);
  65656. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  65657. serializationObject.depth = this.depth;
  65658. return serializationObject;
  65659. };
  65660. return RefractionTexture;
  65661. }(BABYLON.RenderTargetTexture));
  65662. BABYLON.RefractionTexture = RefractionTexture;
  65663. })(BABYLON || (BABYLON = {}));
  65664. //# sourceMappingURL=babylon.refractionTexture.js.map
  65665. var BABYLON;
  65666. (function (BABYLON) {
  65667. /**
  65668. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65669. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65670. */
  65671. var DynamicTexture = /** @class */ (function (_super) {
  65672. __extends(DynamicTexture, _super);
  65673. /**
  65674. * Creates a {BABYLON.DynamicTexture}
  65675. * @param name defines the name of the texture
  65676. * @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
  65677. * @param scene defines the scene where you want the texture
  65678. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  65679. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  65680. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  65681. */
  65682. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  65683. if (scene === void 0) { scene = null; }
  65684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65685. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65686. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  65687. _this.name = name;
  65688. _this._engine = _this.getScene().getEngine();
  65689. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65690. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65691. _this._generateMipMaps = generateMipMaps;
  65692. if (options.getContext) {
  65693. _this._canvas = options;
  65694. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65695. }
  65696. else {
  65697. _this._canvas = document.createElement("canvas");
  65698. if (options.width || options.width === 0) {
  65699. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65700. }
  65701. else {
  65702. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  65703. }
  65704. }
  65705. var textureSize = _this.getSize();
  65706. _this._canvas.width = textureSize.width;
  65707. _this._canvas.height = textureSize.height;
  65708. _this._context = _this._canvas.getContext("2d");
  65709. return _this;
  65710. }
  65711. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  65712. /**
  65713. * Gets the current state of canRescale
  65714. */
  65715. get: function () {
  65716. return true;
  65717. },
  65718. enumerable: true,
  65719. configurable: true
  65720. });
  65721. DynamicTexture.prototype._recreate = function (textureSize) {
  65722. this._canvas.width = textureSize.width;
  65723. this._canvas.height = textureSize.height;
  65724. this.releaseInternalTexture();
  65725. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65726. };
  65727. /**
  65728. * Scales the texture
  65729. * @param ratio the scale factor to apply to both width and height
  65730. */
  65731. DynamicTexture.prototype.scale = function (ratio) {
  65732. var textureSize = this.getSize();
  65733. textureSize.width *= ratio;
  65734. textureSize.height *= ratio;
  65735. this._recreate(textureSize);
  65736. };
  65737. /**
  65738. * Resizes the texture
  65739. * @param width the new width
  65740. * @param height the new height
  65741. */
  65742. DynamicTexture.prototype.scaleTo = function (width, height) {
  65743. var textureSize = this.getSize();
  65744. textureSize.width = width;
  65745. textureSize.height = height;
  65746. this._recreate(textureSize);
  65747. };
  65748. /**
  65749. * Gets the context of the canvas used by the texture
  65750. * @returns the canvas context of the dynamic texture
  65751. */
  65752. DynamicTexture.prototype.getContext = function () {
  65753. return this._context;
  65754. };
  65755. /**
  65756. * Clears the texture
  65757. */
  65758. DynamicTexture.prototype.clear = function () {
  65759. var size = this.getSize();
  65760. this._context.fillRect(0, 0, size.width, size.height);
  65761. };
  65762. /**
  65763. * Updates the texture
  65764. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65765. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65766. */
  65767. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65768. if (premulAlpha === void 0) { premulAlpha = false; }
  65769. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65770. };
  65771. /**
  65772. * Draws text onto the texture
  65773. * @param text defines the text to be drawn
  65774. * @param x defines the placement of the text from the left
  65775. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65776. * @param font defines the font to be used with font-style, font-size, font-name
  65777. * @param color defines the color used for the text
  65778. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65779. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65780. * @param update defines whether texture is immediately update (default is true)
  65781. */
  65782. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65783. if (update === void 0) { update = true; }
  65784. var size = this.getSize();
  65785. if (clearColor) {
  65786. this._context.fillStyle = clearColor;
  65787. this._context.fillRect(0, 0, size.width, size.height);
  65788. }
  65789. this._context.font = font;
  65790. if (x === null || x === undefined) {
  65791. var textSize = this._context.measureText(text);
  65792. x = (size.width - textSize.width) / 2;
  65793. }
  65794. if (y === null || y === undefined) {
  65795. var fontSize = parseInt((font.replace(/\D/g, '')));
  65796. y = (size.height / 2) + (fontSize / 3.65);
  65797. }
  65798. this._context.fillStyle = color;
  65799. this._context.fillText(text, x, y);
  65800. if (update) {
  65801. this.update(invertY);
  65802. }
  65803. };
  65804. /**
  65805. * Clones the texture
  65806. * @returns the clone of the texture.
  65807. */
  65808. DynamicTexture.prototype.clone = function () {
  65809. var scene = this.getScene();
  65810. if (!scene) {
  65811. return this;
  65812. }
  65813. var textureSize = this.getSize();
  65814. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65815. // Base texture
  65816. newTexture.hasAlpha = this.hasAlpha;
  65817. newTexture.level = this.level;
  65818. // Dynamic Texture
  65819. newTexture.wrapU = this.wrapU;
  65820. newTexture.wrapV = this.wrapV;
  65821. return newTexture;
  65822. };
  65823. /** @hidden */
  65824. DynamicTexture.prototype._rebuild = function () {
  65825. this.update();
  65826. };
  65827. return DynamicTexture;
  65828. }(BABYLON.Texture));
  65829. BABYLON.DynamicTexture = DynamicTexture;
  65830. })(BABYLON || (BABYLON = {}));
  65831. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65832. var BABYLON;
  65833. (function (BABYLON) {
  65834. var VideoTexture = /** @class */ (function (_super) {
  65835. __extends(VideoTexture, _super);
  65836. /**
  65837. * Creates a video texture.
  65838. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65839. * @param {string | null} name optional name, will detect from video source, if not defined
  65840. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65841. * @param {BABYLON.Scene} scene is obviously the current scene.
  65842. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65843. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65844. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65845. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65846. */
  65847. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65848. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65849. if (invertY === void 0) { invertY = false; }
  65850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65851. if (settings === void 0) { settings = {
  65852. autoPlay: true,
  65853. loop: true,
  65854. autoUpdateTexture: true,
  65855. }; }
  65856. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65857. _this._onUserActionRequestedObservable = null;
  65858. _this._stillImageCaptured = false;
  65859. _this._poster = false;
  65860. _this._createInternalTexture = function () {
  65861. if (_this._texture != null) {
  65862. if (_this._poster) {
  65863. _this._texture.dispose();
  65864. _this._poster = false;
  65865. }
  65866. else {
  65867. return;
  65868. }
  65869. }
  65870. if (!_this._engine.needPOTTextures ||
  65871. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65872. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65873. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65874. }
  65875. else {
  65876. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65877. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65878. _this._generateMipMaps = false;
  65879. }
  65880. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65881. if (!_this.video.autoplay) {
  65882. var oldHandler_1 = _this.video.onplaying;
  65883. var error_1 = false;
  65884. _this.video.onplaying = function () {
  65885. _this.video.onplaying = oldHandler_1;
  65886. _this._texture.isReady = true;
  65887. _this._updateInternalTexture();
  65888. if (!error_1) {
  65889. _this.video.pause();
  65890. }
  65891. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65892. _this.onLoadObservable.notifyObservers(_this);
  65893. }
  65894. };
  65895. var playing = _this.video.play();
  65896. if (playing) {
  65897. playing.then(function () {
  65898. // Everything is good.
  65899. })
  65900. .catch(function () {
  65901. error_1 = true;
  65902. // On Chrome for instance, new policies might prevent playing without user interaction.
  65903. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65904. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65905. }
  65906. });
  65907. }
  65908. else {
  65909. _this.video.onplaying = oldHandler_1;
  65910. _this._texture.isReady = true;
  65911. _this._updateInternalTexture();
  65912. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65913. _this.onLoadObservable.notifyObservers(_this);
  65914. }
  65915. }
  65916. }
  65917. else {
  65918. _this._texture.isReady = true;
  65919. _this._updateInternalTexture();
  65920. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65921. _this.onLoadObservable.notifyObservers(_this);
  65922. }
  65923. }
  65924. };
  65925. _this.reset = function () {
  65926. if (_this._texture == null) {
  65927. return;
  65928. }
  65929. if (!_this._poster) {
  65930. _this._texture.dispose();
  65931. _this._texture = null;
  65932. }
  65933. };
  65934. _this._updateInternalTexture = function (e) {
  65935. if (_this._texture == null || !_this._texture.isReady) {
  65936. return;
  65937. }
  65938. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65939. return;
  65940. }
  65941. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65942. };
  65943. _this._engine = _this.getScene().getEngine();
  65944. _this._generateMipMaps = generateMipMaps;
  65945. _this._samplingMode = samplingMode;
  65946. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65947. _this.name = name || _this._getName(src);
  65948. _this.video = _this._getVideo(src);
  65949. if (settings.poster) {
  65950. _this.video.poster = settings.poster;
  65951. }
  65952. if (settings.autoPlay !== undefined) {
  65953. _this.video.autoplay = settings.autoPlay;
  65954. }
  65955. if (settings.loop !== undefined) {
  65956. _this.video.loop = settings.loop;
  65957. }
  65958. _this.video.setAttribute("playsinline", "");
  65959. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65960. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65961. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65962. _this.video.addEventListener("emptied", _this.reset);
  65963. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65964. _this._createInternalTexture();
  65965. }
  65966. if (settings.poster) {
  65967. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  65968. _this._poster = true;
  65969. }
  65970. return _this;
  65971. }
  65972. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65973. get: function () {
  65974. if (!this._onUserActionRequestedObservable) {
  65975. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65976. }
  65977. return this._onUserActionRequestedObservable;
  65978. },
  65979. enumerable: true,
  65980. configurable: true
  65981. });
  65982. VideoTexture.prototype._getName = function (src) {
  65983. if (src instanceof HTMLVideoElement) {
  65984. return src.currentSrc;
  65985. }
  65986. if (typeof src === "object") {
  65987. return src.toString();
  65988. }
  65989. return src;
  65990. };
  65991. ;
  65992. VideoTexture.prototype._getVideo = function (src) {
  65993. if (src instanceof HTMLVideoElement) {
  65994. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65995. return src;
  65996. }
  65997. var video = document.createElement("video");
  65998. if (typeof src === "string") {
  65999. BABYLON.Tools.SetCorsBehavior(src, video);
  66000. video.src = src;
  66001. }
  66002. else {
  66003. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66004. src.forEach(function (url) {
  66005. var source = document.createElement("source");
  66006. source.src = url;
  66007. video.appendChild(source);
  66008. });
  66009. }
  66010. return video;
  66011. };
  66012. ;
  66013. /**
  66014. * Internal method to initiate `update`.
  66015. */
  66016. VideoTexture.prototype._rebuild = function () {
  66017. this.update();
  66018. };
  66019. /**
  66020. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66021. */
  66022. VideoTexture.prototype.update = function () {
  66023. if (!this.autoUpdateTexture) {
  66024. // Expecting user to call `updateTexture` manually
  66025. return;
  66026. }
  66027. this.updateTexture(true);
  66028. };
  66029. /**
  66030. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66031. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66032. */
  66033. VideoTexture.prototype.updateTexture = function (isVisible) {
  66034. if (!isVisible) {
  66035. return;
  66036. }
  66037. if (this.video.paused && this._stillImageCaptured) {
  66038. return;
  66039. }
  66040. this._stillImageCaptured = true;
  66041. this._updateInternalTexture();
  66042. };
  66043. /**
  66044. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66045. * @param url New url.
  66046. */
  66047. VideoTexture.prototype.updateURL = function (url) {
  66048. this.video.src = url;
  66049. };
  66050. VideoTexture.prototype.dispose = function () {
  66051. _super.prototype.dispose.call(this);
  66052. if (this._onUserActionRequestedObservable) {
  66053. this._onUserActionRequestedObservable.clear();
  66054. this._onUserActionRequestedObservable = null;
  66055. }
  66056. this.video.removeEventListener("canplay", this._createInternalTexture);
  66057. this.video.removeEventListener("paused", this._updateInternalTexture);
  66058. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66059. this.video.removeEventListener("emptied", this.reset);
  66060. this.video.pause();
  66061. };
  66062. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66063. var video = document.createElement("video");
  66064. video.setAttribute('autoplay', '');
  66065. video.setAttribute('muted', '');
  66066. video.setAttribute('playsinline', '');
  66067. var constraintsDeviceId;
  66068. if (constraints && constraints.deviceId) {
  66069. constraintsDeviceId = {
  66070. exact: constraints.deviceId,
  66071. };
  66072. }
  66073. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66074. if (navigator.mediaDevices) {
  66075. navigator.mediaDevices.getUserMedia({ video: constraints })
  66076. .then(function (stream) {
  66077. if (video.mozSrcObject !== undefined) {
  66078. // hack for Firefox < 19
  66079. video.mozSrcObject = stream;
  66080. }
  66081. else {
  66082. video.srcObject = stream;
  66083. }
  66084. var onPlaying = function () {
  66085. if (onReady) {
  66086. onReady(new VideoTexture("video", video, scene, true, true));
  66087. }
  66088. video.removeEventListener("playing", onPlaying);
  66089. };
  66090. video.addEventListener("playing", onPlaying);
  66091. video.play();
  66092. })
  66093. .catch(function (err) {
  66094. BABYLON.Tools.Error(err.name);
  66095. });
  66096. }
  66097. else {
  66098. navigator.getUserMedia =
  66099. navigator.getUserMedia ||
  66100. navigator.webkitGetUserMedia ||
  66101. navigator.mozGetUserMedia ||
  66102. navigator.msGetUserMedia;
  66103. if (navigator.getUserMedia) {
  66104. navigator.getUserMedia({
  66105. video: {
  66106. deviceId: constraintsDeviceId,
  66107. width: {
  66108. min: (constraints && constraints.minWidth) || 256,
  66109. max: (constraints && constraints.maxWidth) || 640,
  66110. },
  66111. height: {
  66112. min: (constraints && constraints.minHeight) || 256,
  66113. max: (constraints && constraints.maxHeight) || 480,
  66114. },
  66115. },
  66116. }, function (stream) {
  66117. if (video.mozSrcObject !== undefined) {
  66118. // hack for Firefox < 19
  66119. video.mozSrcObject = stream;
  66120. }
  66121. else {
  66122. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66123. }
  66124. video.play();
  66125. if (onReady) {
  66126. onReady(new VideoTexture("video", video, scene, true, true));
  66127. }
  66128. }, function (e) {
  66129. BABYLON.Tools.Error(e.name);
  66130. });
  66131. }
  66132. }
  66133. };
  66134. return VideoTexture;
  66135. }(BABYLON.Texture));
  66136. BABYLON.VideoTexture = VideoTexture;
  66137. })(BABYLON || (BABYLON = {}));
  66138. //# sourceMappingURL=babylon.videoTexture.js.map
  66139. var BABYLON;
  66140. (function (BABYLON) {
  66141. var RawTexture = /** @class */ (function (_super) {
  66142. __extends(RawTexture, _super);
  66143. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66144. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66145. if (invertY === void 0) { invertY = false; }
  66146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66147. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66148. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66149. _this.format = format;
  66150. _this._engine = scene.getEngine();
  66151. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66152. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66153. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66154. return _this;
  66155. }
  66156. RawTexture.prototype.update = function (data) {
  66157. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66158. };
  66159. // Statics
  66160. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66161. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66162. if (invertY === void 0) { invertY = false; }
  66163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66164. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66165. };
  66166. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66168. if (invertY === void 0) { invertY = false; }
  66169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66170. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66171. };
  66172. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66173. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66174. if (invertY === void 0) { invertY = false; }
  66175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66176. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66177. };
  66178. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66179. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66180. if (invertY === void 0) { invertY = false; }
  66181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66182. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66183. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66184. };
  66185. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66186. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66187. if (invertY === void 0) { invertY = false; }
  66188. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66189. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66190. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66191. };
  66192. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66193. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66194. if (invertY === void 0) { invertY = false; }
  66195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66196. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66197. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66198. };
  66199. return RawTexture;
  66200. }(BABYLON.Texture));
  66201. BABYLON.RawTexture = RawTexture;
  66202. })(BABYLON || (BABYLON = {}));
  66203. //# sourceMappingURL=babylon.rawTexture.js.map
  66204. var BABYLON;
  66205. (function (BABYLON) {
  66206. /**
  66207. * Class used to store 3D textures containing user data
  66208. */
  66209. var RawTexture3D = /** @class */ (function (_super) {
  66210. __extends(RawTexture3D, _super);
  66211. /**
  66212. * Create a new RawTexture3D
  66213. * @param data defines the data of the texture
  66214. * @param width defines the width of the texture
  66215. * @param height defines the height of the texture
  66216. * @param depth defines the depth of the texture
  66217. * @param format defines the texture format to use
  66218. * @param scene defines the hosting scene
  66219. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66220. * @param invertY defines if texture must be stored with Y axis inverted
  66221. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66222. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66223. */
  66224. function RawTexture3D(data, width, height, depth,
  66225. /** Gets or sets the texture format to use */
  66226. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66227. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66228. if (invertY === void 0) { invertY = false; }
  66229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66230. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66231. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66232. _this.format = format;
  66233. _this._engine = scene.getEngine();
  66234. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66235. _this.is3D = true;
  66236. return _this;
  66237. }
  66238. /**
  66239. * Update the texture with new data
  66240. * @param data defines the data to store in the texture
  66241. */
  66242. RawTexture3D.prototype.update = function (data) {
  66243. if (!this._texture) {
  66244. return;
  66245. }
  66246. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66247. };
  66248. return RawTexture3D;
  66249. }(BABYLON.Texture));
  66250. BABYLON.RawTexture3D = RawTexture3D;
  66251. })(BABYLON || (BABYLON = {}));
  66252. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66253. var BABYLON;
  66254. (function (BABYLON) {
  66255. /**
  66256. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66257. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66258. */
  66259. var PostProcessManager = /** @class */ (function () {
  66260. /**
  66261. * Creates a new instance PostProcess
  66262. * @param scene The scene that the post process is associated with.
  66263. */
  66264. function PostProcessManager(scene) {
  66265. this._vertexBuffers = {};
  66266. this._scene = scene;
  66267. }
  66268. PostProcessManager.prototype._prepareBuffers = function () {
  66269. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66270. return;
  66271. }
  66272. // VBO
  66273. var vertices = [];
  66274. vertices.push(1, 1);
  66275. vertices.push(-1, 1);
  66276. vertices.push(-1, -1);
  66277. vertices.push(1, -1);
  66278. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66279. this._buildIndexBuffer();
  66280. };
  66281. PostProcessManager.prototype._buildIndexBuffer = function () {
  66282. // Indices
  66283. var indices = [];
  66284. indices.push(0);
  66285. indices.push(1);
  66286. indices.push(2);
  66287. indices.push(0);
  66288. indices.push(2);
  66289. indices.push(3);
  66290. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66291. };
  66292. /**
  66293. * Rebuilds the vertex buffers of the manager.
  66294. */
  66295. PostProcessManager.prototype._rebuild = function () {
  66296. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66297. if (!vb) {
  66298. return;
  66299. }
  66300. vb._rebuild();
  66301. this._buildIndexBuffer();
  66302. };
  66303. // Methods
  66304. /**
  66305. * Prepares a frame to be run through a post process.
  66306. * @param sourceTexture The input texture to the post procesess. (default: null)
  66307. * @param postProcesses An array of post processes to be run. (default: null)
  66308. * @returns True if the post processes were able to be run.
  66309. */
  66310. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66311. if (sourceTexture === void 0) { sourceTexture = null; }
  66312. if (postProcesses === void 0) { postProcesses = null; }
  66313. var camera = this._scene.activeCamera;
  66314. if (!camera) {
  66315. return false;
  66316. }
  66317. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66318. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66319. return false;
  66320. }
  66321. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66322. return true;
  66323. };
  66324. /**
  66325. * Manually render a set of post processes to a texture.
  66326. * @param postProcesses An array of post processes to be run.
  66327. * @param targetTexture The target texture to render to.
  66328. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66329. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66330. * @param lodLevel defines which lod of the texture to render to
  66331. */
  66332. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66333. if (targetTexture === void 0) { targetTexture = null; }
  66334. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66335. if (faceIndex === void 0) { faceIndex = 0; }
  66336. if (lodLevel === void 0) { lodLevel = 0; }
  66337. var engine = this._scene.getEngine();
  66338. for (var index = 0; index < postProcesses.length; index++) {
  66339. if (index < postProcesses.length - 1) {
  66340. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66341. }
  66342. else {
  66343. if (targetTexture) {
  66344. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66345. }
  66346. else {
  66347. engine.restoreDefaultFramebuffer();
  66348. }
  66349. }
  66350. var pp = postProcesses[index];
  66351. var effect = pp.apply();
  66352. if (effect) {
  66353. pp.onBeforeRenderObservable.notifyObservers(effect);
  66354. // VBOs
  66355. this._prepareBuffers();
  66356. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66357. // Draw order
  66358. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66359. pp.onAfterRenderObservable.notifyObservers(effect);
  66360. }
  66361. }
  66362. // Restore depth buffer
  66363. engine.setDepthBuffer(true);
  66364. engine.setDepthWrite(true);
  66365. };
  66366. /**
  66367. * Finalize the result of the output of the postprocesses.
  66368. * @param doNotPresent If true the result will not be displayed to the screen.
  66369. * @param targetTexture The target texture to render to.
  66370. * @param faceIndex The index of the face to bind the target texture to.
  66371. * @param postProcesses The array of post processes to render.
  66372. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66373. */
  66374. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66375. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66376. var camera = this._scene.activeCamera;
  66377. if (!camera) {
  66378. return;
  66379. }
  66380. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66381. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66382. return;
  66383. }
  66384. var engine = this._scene.getEngine();
  66385. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66386. var pp = postProcesses[index];
  66387. if (index < len - 1) {
  66388. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66389. }
  66390. else {
  66391. if (targetTexture) {
  66392. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66393. pp._outputTexture = targetTexture;
  66394. }
  66395. else {
  66396. engine.restoreDefaultFramebuffer();
  66397. pp._outputTexture = null;
  66398. }
  66399. }
  66400. if (doNotPresent) {
  66401. break;
  66402. }
  66403. var effect = pp.apply();
  66404. if (effect) {
  66405. pp.onBeforeRenderObservable.notifyObservers(effect);
  66406. // VBOs
  66407. this._prepareBuffers();
  66408. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66409. // Draw order
  66410. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66411. pp.onAfterRenderObservable.notifyObservers(effect);
  66412. }
  66413. }
  66414. // Restore states
  66415. engine.setDepthBuffer(true);
  66416. engine.setDepthWrite(true);
  66417. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66418. };
  66419. /**
  66420. * Disposes of the post process manager.
  66421. */
  66422. PostProcessManager.prototype.dispose = function () {
  66423. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66424. if (buffer) {
  66425. buffer.dispose();
  66426. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66427. }
  66428. if (this._indexBuffer) {
  66429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66430. this._indexBuffer = null;
  66431. }
  66432. };
  66433. return PostProcessManager;
  66434. }());
  66435. BABYLON.PostProcessManager = PostProcessManager;
  66436. })(BABYLON || (BABYLON = {}));
  66437. //# sourceMappingURL=babylon.postProcessManager.js.map
  66438. var BABYLON;
  66439. (function (BABYLON) {
  66440. /**
  66441. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66442. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66443. */
  66444. var PostProcess = /** @class */ (function () {
  66445. /**
  66446. * Creates a new instance PostProcess
  66447. * @param name The name of the PostProcess.
  66448. * @param fragmentUrl The url of the fragment shader to be used.
  66449. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66450. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66451. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66452. * @param camera The camera to apply the render pass to.
  66453. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66454. * @param engine The engine which the post process will be applied. (default: current engine)
  66455. * @param reusable If the post process can be reused on the same frame. (default: false)
  66456. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66457. * @param textureType Type of textures used when performing the post process. (default: 0)
  66458. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66459. * @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
  66460. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66461. */
  66462. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66464. if (defines === void 0) { defines = null; }
  66465. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66466. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66467. if (blockCompilation === void 0) { blockCompilation = false; }
  66468. this.name = name;
  66469. /**
  66470. * Width of the texture to apply the post process on
  66471. */
  66472. this.width = -1;
  66473. /**
  66474. * Height of the texture to apply the post process on
  66475. */
  66476. this.height = -1;
  66477. /**
  66478. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66479. */
  66480. this._outputTexture = null;
  66481. /**
  66482. * If the buffer needs to be cleared before applying the post process. (default: true)
  66483. * Should be set to false if shader will overwrite all previous pixels.
  66484. */
  66485. this.autoClear = true;
  66486. /**
  66487. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66488. */
  66489. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66490. /**
  66491. * Animations to be used for the post processing
  66492. */
  66493. this.animations = new Array();
  66494. /**
  66495. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66496. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66497. */
  66498. this.enablePixelPerfectMode = false;
  66499. /**
  66500. * Force the postprocess to be applied without taking in account viewport
  66501. */
  66502. this.forceFullscreenViewport = true;
  66503. /**
  66504. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66505. *
  66506. * | Value | Type | Description |
  66507. * | ----- | ----------------------------------- | ----------- |
  66508. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66509. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66510. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66511. *
  66512. */
  66513. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66514. /**
  66515. * Force textures to be a power of two (default: false)
  66516. */
  66517. this.alwaysForcePOT = false;
  66518. /**
  66519. * Number of sample textures (default: 1)
  66520. */
  66521. this.samples = 1;
  66522. /**
  66523. * Modify the scale of the post process to be the same as the viewport (default: false)
  66524. */
  66525. this.adaptScaleToCurrentViewport = false;
  66526. this._reusable = false;
  66527. /**
  66528. * Smart array of input and output textures for the post process.
  66529. */
  66530. this._textures = new BABYLON.SmartArray(2);
  66531. /**
  66532. * The index in _textures that corresponds to the output texture.
  66533. */
  66534. this._currentRenderTextureInd = 0;
  66535. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66536. this._texelSize = BABYLON.Vector2.Zero();
  66537. // Events
  66538. /**
  66539. * An event triggered when the postprocess is activated.
  66540. */
  66541. this.onActivateObservable = new BABYLON.Observable();
  66542. /**
  66543. * An event triggered when the postprocess changes its size.
  66544. */
  66545. this.onSizeChangedObservable = new BABYLON.Observable();
  66546. /**
  66547. * An event triggered when the postprocess applies its effect.
  66548. */
  66549. this.onApplyObservable = new BABYLON.Observable();
  66550. /**
  66551. * An event triggered before rendering the postprocess
  66552. */
  66553. this.onBeforeRenderObservable = new BABYLON.Observable();
  66554. /**
  66555. * An event triggered after rendering the postprocess
  66556. */
  66557. this.onAfterRenderObservable = new BABYLON.Observable();
  66558. if (camera != null) {
  66559. this._camera = camera;
  66560. this._scene = camera.getScene();
  66561. camera.attachPostProcess(this);
  66562. this._engine = this._scene.getEngine();
  66563. this._scene.postProcesses.push(this);
  66564. }
  66565. else if (engine) {
  66566. this._engine = engine;
  66567. this._engine.postProcesses.push(this);
  66568. }
  66569. this._options = options;
  66570. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66571. this._reusable = reusable || false;
  66572. this._textureType = textureType;
  66573. this._samplers = samplers || [];
  66574. this._samplers.push("textureSampler");
  66575. this._fragmentUrl = fragmentUrl;
  66576. this._vertexUrl = vertexUrl;
  66577. this._parameters = parameters || [];
  66578. this._parameters.push("scale");
  66579. this._indexParameters = indexParameters;
  66580. if (!blockCompilation) {
  66581. this.updateEffect(defines);
  66582. }
  66583. }
  66584. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66585. /**
  66586. * A function that is added to the onActivateObservable
  66587. */
  66588. set: function (callback) {
  66589. if (this._onActivateObserver) {
  66590. this.onActivateObservable.remove(this._onActivateObserver);
  66591. }
  66592. if (callback) {
  66593. this._onActivateObserver = this.onActivateObservable.add(callback);
  66594. }
  66595. },
  66596. enumerable: true,
  66597. configurable: true
  66598. });
  66599. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66600. /**
  66601. * A function that is added to the onSizeChangedObservable
  66602. */
  66603. set: function (callback) {
  66604. if (this._onSizeChangedObserver) {
  66605. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66606. }
  66607. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66608. },
  66609. enumerable: true,
  66610. configurable: true
  66611. });
  66612. Object.defineProperty(PostProcess.prototype, "onApply", {
  66613. /**
  66614. * A function that is added to the onApplyObservable
  66615. */
  66616. set: function (callback) {
  66617. if (this._onApplyObserver) {
  66618. this.onApplyObservable.remove(this._onApplyObserver);
  66619. }
  66620. this._onApplyObserver = this.onApplyObservable.add(callback);
  66621. },
  66622. enumerable: true,
  66623. configurable: true
  66624. });
  66625. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66626. /**
  66627. * A function that is added to the onBeforeRenderObservable
  66628. */
  66629. set: function (callback) {
  66630. if (this._onBeforeRenderObserver) {
  66631. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66632. }
  66633. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66634. },
  66635. enumerable: true,
  66636. configurable: true
  66637. });
  66638. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  66639. /**
  66640. * A function that is added to the onAfterRenderObservable
  66641. */
  66642. set: function (callback) {
  66643. if (this._onAfterRenderObserver) {
  66644. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66645. }
  66646. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66647. },
  66648. enumerable: true,
  66649. configurable: true
  66650. });
  66651. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  66652. /**
  66653. * 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
  66654. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  66655. */
  66656. get: function () {
  66657. return this._textures.data[this._currentRenderTextureInd];
  66658. },
  66659. set: function (value) {
  66660. this._forcedOutputTexture = value;
  66661. },
  66662. enumerable: true,
  66663. configurable: true
  66664. });
  66665. /**
  66666. * Gets the camera which post process is applied to.
  66667. * @returns The camera the post process is applied to.
  66668. */
  66669. PostProcess.prototype.getCamera = function () {
  66670. return this._camera;
  66671. };
  66672. Object.defineProperty(PostProcess.prototype, "texelSize", {
  66673. /**
  66674. * Gets the texel size of the postprocess.
  66675. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  66676. */
  66677. get: function () {
  66678. if (this._shareOutputWithPostProcess) {
  66679. return this._shareOutputWithPostProcess.texelSize;
  66680. }
  66681. if (this._forcedOutputTexture) {
  66682. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  66683. }
  66684. return this._texelSize;
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. /**
  66690. * Gets the engine which this post process belongs to.
  66691. * @returns The engine the post process was enabled with.
  66692. */
  66693. PostProcess.prototype.getEngine = function () {
  66694. return this._engine;
  66695. };
  66696. /**
  66697. * The effect that is created when initializing the post process.
  66698. * @returns The created effect corrisponding the the postprocess.
  66699. */
  66700. PostProcess.prototype.getEffect = function () {
  66701. return this._effect;
  66702. };
  66703. /**
  66704. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  66705. * @param postProcess The post process to share the output with.
  66706. * @returns This post process.
  66707. */
  66708. PostProcess.prototype.shareOutputWith = function (postProcess) {
  66709. this._disposeTextures();
  66710. this._shareOutputWithPostProcess = postProcess;
  66711. return this;
  66712. };
  66713. /**
  66714. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  66715. * This should be called if the post process that shares output with this post process is disabled/disposed.
  66716. */
  66717. PostProcess.prototype.useOwnOutput = function () {
  66718. if (this._textures.length == 0) {
  66719. this._textures = new BABYLON.SmartArray(2);
  66720. }
  66721. this._shareOutputWithPostProcess = null;
  66722. };
  66723. /**
  66724. * Updates the effect with the current post process compile time values and recompiles the shader.
  66725. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  66726. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  66727. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  66728. * @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
  66729. * @param onCompiled Called when the shader has been compiled.
  66730. * @param onError Called if there is an error when compiling a shader.
  66731. */
  66732. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  66733. if (defines === void 0) { defines = null; }
  66734. if (uniforms === void 0) { uniforms = null; }
  66735. if (samplers === void 0) { samplers = null; }
  66736. 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);
  66737. };
  66738. /**
  66739. * The post process is reusable if it can be used multiple times within one frame.
  66740. * @returns If the post process is reusable
  66741. */
  66742. PostProcess.prototype.isReusable = function () {
  66743. return this._reusable;
  66744. };
  66745. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  66746. PostProcess.prototype.markTextureDirty = function () {
  66747. this.width = -1;
  66748. };
  66749. /**
  66750. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  66751. * 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.
  66752. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  66753. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  66754. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  66755. * @returns The target texture that was bound to be written to.
  66756. */
  66757. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  66758. var _this = this;
  66759. if (sourceTexture === void 0) { sourceTexture = null; }
  66760. camera = camera || this._camera;
  66761. var scene = camera.getScene();
  66762. var engine = scene.getEngine();
  66763. var maxSize = engine.getCaps().maxTextureSize;
  66764. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  66765. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  66766. // 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
  66767. var webVRCamera = camera.parent;
  66768. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  66769. requiredWidth /= 2;
  66770. }
  66771. var desiredWidth = (this._options.width || requiredWidth);
  66772. var desiredHeight = this._options.height || requiredHeight;
  66773. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  66774. if (this.adaptScaleToCurrentViewport) {
  66775. var currentViewport = engine.currentViewport;
  66776. if (currentViewport) {
  66777. desiredWidth *= currentViewport.width;
  66778. desiredHeight *= currentViewport.height;
  66779. }
  66780. }
  66781. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  66782. if (!this._options.width) {
  66783. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  66784. }
  66785. if (!this._options.height) {
  66786. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  66787. }
  66788. }
  66789. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  66790. if (this._textures.length > 0) {
  66791. for (var i = 0; i < this._textures.length; i++) {
  66792. this._engine._releaseTexture(this._textures.data[i]);
  66793. }
  66794. this._textures.reset();
  66795. }
  66796. this.width = desiredWidth;
  66797. this.height = desiredHeight;
  66798. var textureSize = { width: this.width, height: this.height };
  66799. var textureOptions = {
  66800. generateMipMaps: false,
  66801. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  66802. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  66803. samplingMode: this.renderTargetSamplingMode,
  66804. type: this._textureType
  66805. };
  66806. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66807. if (this._reusable) {
  66808. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66809. }
  66810. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  66811. this.onSizeChangedObservable.notifyObservers(this);
  66812. }
  66813. this._textures.forEach(function (texture) {
  66814. if (texture.samples !== _this.samples) {
  66815. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  66816. }
  66817. });
  66818. }
  66819. var target;
  66820. if (this._shareOutputWithPostProcess) {
  66821. target = this._shareOutputWithPostProcess.inputTexture;
  66822. }
  66823. else if (this._forcedOutputTexture) {
  66824. target = this._forcedOutputTexture;
  66825. this.width = this._forcedOutputTexture.width;
  66826. this.height = this._forcedOutputTexture.height;
  66827. }
  66828. else {
  66829. target = this.inputTexture;
  66830. }
  66831. // Bind the input of this post process to be used as the output of the previous post process.
  66832. if (this.enablePixelPerfectMode) {
  66833. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66834. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66835. }
  66836. else {
  66837. this._scaleRatio.copyFromFloats(1, 1);
  66838. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66839. }
  66840. this.onActivateObservable.notifyObservers(camera);
  66841. // Clear
  66842. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66843. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66844. }
  66845. if (this._reusable) {
  66846. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66847. }
  66848. return target;
  66849. };
  66850. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66851. /**
  66852. * If the post process is supported.
  66853. */
  66854. get: function () {
  66855. return this._effect.isSupported;
  66856. },
  66857. enumerable: true,
  66858. configurable: true
  66859. });
  66860. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66861. /**
  66862. * The aspect ratio of the output texture.
  66863. */
  66864. get: function () {
  66865. if (this._shareOutputWithPostProcess) {
  66866. return this._shareOutputWithPostProcess.aspectRatio;
  66867. }
  66868. if (this._forcedOutputTexture) {
  66869. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66870. }
  66871. return this.width / this.height;
  66872. },
  66873. enumerable: true,
  66874. configurable: true
  66875. });
  66876. /**
  66877. * Get a value indicating if the post-process is ready to be used
  66878. * @returns true if the post-process is ready (shader is compiled)
  66879. */
  66880. PostProcess.prototype.isReady = function () {
  66881. return this._effect && this._effect.isReady();
  66882. };
  66883. /**
  66884. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66885. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66886. */
  66887. PostProcess.prototype.apply = function () {
  66888. // Check
  66889. if (!this._effect || !this._effect.isReady())
  66890. return null;
  66891. // States
  66892. this._engine.enableEffect(this._effect);
  66893. this._engine.setState(false);
  66894. this._engine.setDepthBuffer(false);
  66895. this._engine.setDepthWrite(false);
  66896. // Alpha
  66897. this._engine.setAlphaMode(this.alphaMode);
  66898. if (this.alphaConstants) {
  66899. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66900. }
  66901. // Bind the output texture of the preivous post process as the input to this post process.
  66902. var source;
  66903. if (this._shareOutputWithPostProcess) {
  66904. source = this._shareOutputWithPostProcess.inputTexture;
  66905. }
  66906. else if (this._forcedOutputTexture) {
  66907. source = this._forcedOutputTexture;
  66908. }
  66909. else {
  66910. source = this.inputTexture;
  66911. }
  66912. this._effect._bindTexture("textureSampler", source);
  66913. // Parameters
  66914. this._effect.setVector2("scale", this._scaleRatio);
  66915. this.onApplyObservable.notifyObservers(this._effect);
  66916. return this._effect;
  66917. };
  66918. PostProcess.prototype._disposeTextures = function () {
  66919. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66920. return;
  66921. }
  66922. if (this._textures.length > 0) {
  66923. for (var i = 0; i < this._textures.length; i++) {
  66924. this._engine._releaseTexture(this._textures.data[i]);
  66925. }
  66926. }
  66927. this._textures.dispose();
  66928. };
  66929. /**
  66930. * Disposes the post process.
  66931. * @param camera The camera to dispose the post process on.
  66932. */
  66933. PostProcess.prototype.dispose = function (camera) {
  66934. camera = camera || this._camera;
  66935. this._disposeTextures();
  66936. if (this._scene) {
  66937. var index_1 = this._scene.postProcesses.indexOf(this);
  66938. if (index_1 !== -1) {
  66939. this._scene.postProcesses.splice(index_1, 1);
  66940. }
  66941. }
  66942. else {
  66943. var index_2 = this._engine.postProcesses.indexOf(this);
  66944. if (index_2 !== -1) {
  66945. this._engine.postProcesses.splice(index_2, 1);
  66946. }
  66947. }
  66948. if (!camera) {
  66949. return;
  66950. }
  66951. camera.detachPostProcess(this);
  66952. var index = camera._postProcesses.indexOf(this);
  66953. if (index === 0 && camera._postProcesses.length > 0) {
  66954. var firstPostProcess = this._camera._getFirstPostProcess();
  66955. if (firstPostProcess) {
  66956. firstPostProcess.markTextureDirty();
  66957. }
  66958. }
  66959. this.onActivateObservable.clear();
  66960. this.onAfterRenderObservable.clear();
  66961. this.onApplyObservable.clear();
  66962. this.onBeforeRenderObservable.clear();
  66963. this.onSizeChangedObservable.clear();
  66964. };
  66965. return PostProcess;
  66966. }());
  66967. BABYLON.PostProcess = PostProcess;
  66968. })(BABYLON || (BABYLON = {}));
  66969. //# sourceMappingURL=babylon.postProcess.js.map
  66970. var BABYLON;
  66971. (function (BABYLON) {
  66972. var PassPostProcess = /** @class */ (function (_super) {
  66973. __extends(PassPostProcess, _super);
  66974. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66975. if (camera === void 0) { camera = null; }
  66976. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66977. if (blockCompilation === void 0) { blockCompilation = false; }
  66978. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66979. }
  66980. return PassPostProcess;
  66981. }(BABYLON.PostProcess));
  66982. BABYLON.PassPostProcess = PassPostProcess;
  66983. })(BABYLON || (BABYLON = {}));
  66984. //# sourceMappingURL=babylon.passPostProcess.js.map
  66985. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66986. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66987. s = arguments[i];
  66988. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66989. t[p] = s[p];
  66990. }
  66991. return t;
  66992. };
  66993. var BABYLON;
  66994. (function (BABYLON) {
  66995. /**
  66996. * Default implementation IShadowGenerator.
  66997. * This is the main object responsible of generating shadows in the framework.
  66998. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66999. */
  67000. var ShadowGenerator = /** @class */ (function () {
  67001. /**
  67002. * Creates a ShadowGenerator object.
  67003. * A ShadowGenerator is the required tool to use the shadows.
  67004. * Each light casting shadows needs to use its own ShadowGenerator.
  67005. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67006. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67007. * @param light The light object generating the shadows.
  67008. * @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.
  67009. */
  67010. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67011. this._bias = 0.00005;
  67012. this._normalBias = 0;
  67013. this._blurBoxOffset = 1;
  67014. this._blurScale = 2;
  67015. this._blurKernel = 1;
  67016. this._useKernelBlur = false;
  67017. this._filter = ShadowGenerator.FILTER_NONE;
  67018. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67019. this._contactHardeningLightSizeUVRatio = 0.1;
  67020. this._darkness = 0;
  67021. this._transparencyShadow = false;
  67022. /**
  67023. * Controls the extent to which the shadows fade out at the edge of the frustum
  67024. * Used only by directionals and spots
  67025. */
  67026. this.frustumEdgeFalloff = 0;
  67027. /**
  67028. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67029. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67030. * It might on the other hand introduce peter panning.
  67031. */
  67032. this.forceBackFacesOnly = false;
  67033. this._lightDirection = BABYLON.Vector3.Zero();
  67034. this._viewMatrix = BABYLON.Matrix.Zero();
  67035. this._projectionMatrix = BABYLON.Matrix.Zero();
  67036. this._transformMatrix = BABYLON.Matrix.Zero();
  67037. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67038. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67039. this._currentFaceIndex = 0;
  67040. this._currentFaceIndexCache = 0;
  67041. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67042. this._mapSize = mapSize;
  67043. this._light = light;
  67044. this._scene = light.getScene();
  67045. light._shadowGenerator = this;
  67046. // Texture type fallback from float to int if not supported.
  67047. var caps = this._scene.getEngine().getCaps();
  67048. if (!useFullFloatFirst) {
  67049. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67050. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67051. }
  67052. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67053. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67054. }
  67055. else {
  67056. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67057. }
  67058. }
  67059. else {
  67060. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67061. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67062. }
  67063. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67064. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67065. }
  67066. else {
  67067. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67068. }
  67069. }
  67070. this._initializeGenerator();
  67071. this._applyFilterValues();
  67072. }
  67073. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67074. /**
  67075. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67076. */
  67077. get: function () {
  67078. return this._bias;
  67079. },
  67080. /**
  67081. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67082. */
  67083. set: function (bias) {
  67084. this._bias = bias;
  67085. },
  67086. enumerable: true,
  67087. configurable: true
  67088. });
  67089. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67090. /**
  67091. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67092. */
  67093. get: function () {
  67094. return this._normalBias;
  67095. },
  67096. /**
  67097. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67098. */
  67099. set: function (normalBias) {
  67100. this._normalBias = normalBias;
  67101. },
  67102. enumerable: true,
  67103. configurable: true
  67104. });
  67105. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67106. /**
  67107. * Gets the blur box offset: offset applied during the blur pass.
  67108. * Only usefull if useKernelBlur = false
  67109. */
  67110. get: function () {
  67111. return this._blurBoxOffset;
  67112. },
  67113. /**
  67114. * Sets the blur box offset: offset applied during the blur pass.
  67115. * Only usefull if useKernelBlur = false
  67116. */
  67117. set: function (value) {
  67118. if (this._blurBoxOffset === value) {
  67119. return;
  67120. }
  67121. this._blurBoxOffset = value;
  67122. this._disposeBlurPostProcesses();
  67123. },
  67124. enumerable: true,
  67125. configurable: true
  67126. });
  67127. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67128. /**
  67129. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67130. * 2 means half of the size.
  67131. */
  67132. get: function () {
  67133. return this._blurScale;
  67134. },
  67135. /**
  67136. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67137. * 2 means half of the size.
  67138. */
  67139. set: function (value) {
  67140. if (this._blurScale === value) {
  67141. return;
  67142. }
  67143. this._blurScale = value;
  67144. this._disposeBlurPostProcesses();
  67145. },
  67146. enumerable: true,
  67147. configurable: true
  67148. });
  67149. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67150. /**
  67151. * Gets the blur kernel: kernel size of the blur pass.
  67152. * Only usefull if useKernelBlur = true
  67153. */
  67154. get: function () {
  67155. return this._blurKernel;
  67156. },
  67157. /**
  67158. * Sets the blur kernel: kernel size of the blur pass.
  67159. * Only usefull if useKernelBlur = true
  67160. */
  67161. set: function (value) {
  67162. if (this._blurKernel === value) {
  67163. return;
  67164. }
  67165. this._blurKernel = value;
  67166. this._disposeBlurPostProcesses();
  67167. },
  67168. enumerable: true,
  67169. configurable: true
  67170. });
  67171. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67172. /**
  67173. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67174. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67175. */
  67176. get: function () {
  67177. return this._useKernelBlur;
  67178. },
  67179. /**
  67180. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67181. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67182. */
  67183. set: function (value) {
  67184. if (this._useKernelBlur === value) {
  67185. return;
  67186. }
  67187. this._useKernelBlur = value;
  67188. this._disposeBlurPostProcesses();
  67189. },
  67190. enumerable: true,
  67191. configurable: true
  67192. });
  67193. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67194. /**
  67195. * Gets the depth scale used in ESM mode.
  67196. */
  67197. get: function () {
  67198. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67199. },
  67200. /**
  67201. * Sets the depth scale used in ESM mode.
  67202. * This can override the scale stored on the light.
  67203. */
  67204. set: function (value) {
  67205. this._depthScale = value;
  67206. },
  67207. enumerable: true,
  67208. configurable: true
  67209. });
  67210. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67211. /**
  67212. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67213. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67214. */
  67215. get: function () {
  67216. return this._filter;
  67217. },
  67218. /**
  67219. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67220. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67221. */
  67222. set: function (value) {
  67223. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67224. if (this._light.needCube()) {
  67225. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67226. this.useExponentialShadowMap = true;
  67227. return;
  67228. }
  67229. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67230. this.useCloseExponentialShadowMap = true;
  67231. return;
  67232. }
  67233. // PCF on cubemap would also be expensive
  67234. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67235. this.usePoissonSampling = true;
  67236. return;
  67237. }
  67238. }
  67239. // Weblg1 fallback for PCF.
  67240. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67241. if (this._scene.getEngine().webGLVersion === 1) {
  67242. this.usePoissonSampling = true;
  67243. return;
  67244. }
  67245. }
  67246. if (this._filter === value) {
  67247. return;
  67248. }
  67249. this._filter = value;
  67250. this._disposeBlurPostProcesses();
  67251. this._applyFilterValues();
  67252. this._light._markMeshesAsLightDirty();
  67253. },
  67254. enumerable: true,
  67255. configurable: true
  67256. });
  67257. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67258. /**
  67259. * Gets if the current filter is set to Poisson Sampling.
  67260. */
  67261. get: function () {
  67262. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67263. },
  67264. /**
  67265. * Sets the current filter to Poisson Sampling.
  67266. */
  67267. set: function (value) {
  67268. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67269. return;
  67270. }
  67271. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67272. },
  67273. enumerable: true,
  67274. configurable: true
  67275. });
  67276. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67277. /**
  67278. * Gets if the current filter is set to VSM.
  67279. * DEPRECATED. Should use useExponentialShadowMap instead.
  67280. */
  67281. get: function () {
  67282. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67283. return this.useExponentialShadowMap;
  67284. },
  67285. /**
  67286. * Sets the current filter is to VSM.
  67287. * DEPRECATED. Should use useExponentialShadowMap instead.
  67288. */
  67289. set: function (value) {
  67290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67291. this.useExponentialShadowMap = value;
  67292. },
  67293. enumerable: true,
  67294. configurable: true
  67295. });
  67296. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67297. /**
  67298. * Gets if the current filter is set to blurred VSM.
  67299. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67300. */
  67301. get: function () {
  67302. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67303. return this.useBlurExponentialShadowMap;
  67304. },
  67305. /**
  67306. * Sets the current filter is to blurred VSM.
  67307. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67308. */
  67309. set: function (value) {
  67310. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67311. this.useBlurExponentialShadowMap = value;
  67312. },
  67313. enumerable: true,
  67314. configurable: true
  67315. });
  67316. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67317. /**
  67318. * Gets if the current filter is set to ESM.
  67319. */
  67320. get: function () {
  67321. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67322. },
  67323. /**
  67324. * Sets the current filter is to ESM.
  67325. */
  67326. set: function (value) {
  67327. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67328. return;
  67329. }
  67330. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67331. },
  67332. enumerable: true,
  67333. configurable: true
  67334. });
  67335. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67336. /**
  67337. * Gets if the current filter is set to filtered ESM.
  67338. */
  67339. get: function () {
  67340. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67341. },
  67342. /**
  67343. * Gets if the current filter is set to filtered ESM.
  67344. */
  67345. set: function (value) {
  67346. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67347. return;
  67348. }
  67349. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67350. },
  67351. enumerable: true,
  67352. configurable: true
  67353. });
  67354. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67355. /**
  67356. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67357. * exponential to prevent steep falloff artifacts).
  67358. */
  67359. get: function () {
  67360. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67361. },
  67362. /**
  67363. * Sets the current filter to "close ESM" (using the inverse of the
  67364. * exponential to prevent steep falloff artifacts).
  67365. */
  67366. set: function (value) {
  67367. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67368. return;
  67369. }
  67370. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67371. },
  67372. enumerable: true,
  67373. configurable: true
  67374. });
  67375. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67376. /**
  67377. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67378. * exponential to prevent steep falloff artifacts).
  67379. */
  67380. get: function () {
  67381. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67382. },
  67383. /**
  67384. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67385. * exponential to prevent steep falloff artifacts).
  67386. */
  67387. set: function (value) {
  67388. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67389. return;
  67390. }
  67391. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67392. },
  67393. enumerable: true,
  67394. configurable: true
  67395. });
  67396. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67397. /**
  67398. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67399. */
  67400. get: function () {
  67401. return this.filter === ShadowGenerator.FILTER_PCF;
  67402. },
  67403. /**
  67404. * Sets the current filter to "PCF" (percentage closer filtering).
  67405. */
  67406. set: function (value) {
  67407. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67408. return;
  67409. }
  67410. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67411. },
  67412. enumerable: true,
  67413. configurable: true
  67414. });
  67415. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67416. /**
  67417. * Gets the PCF or PCSS Quality.
  67418. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67419. */
  67420. get: function () {
  67421. return this._filteringQuality;
  67422. },
  67423. /**
  67424. * Sets the PCF or PCSS Quality.
  67425. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67426. */
  67427. set: function (filteringQuality) {
  67428. this._filteringQuality = filteringQuality;
  67429. },
  67430. enumerable: true,
  67431. configurable: true
  67432. });
  67433. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67434. /**
  67435. * Gets if the current filter is set to "PCSS" (contact hardening).
  67436. */
  67437. get: function () {
  67438. return this.filter === ShadowGenerator.FILTER_PCSS;
  67439. },
  67440. /**
  67441. * Sets the current filter to "PCSS" (contact hardening).
  67442. */
  67443. set: function (value) {
  67444. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67445. return;
  67446. }
  67447. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67448. },
  67449. enumerable: true,
  67450. configurable: true
  67451. });
  67452. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67453. /**
  67454. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67455. * Using a ratio helps keeping shape stability independently of the map size.
  67456. *
  67457. * It does not account for the light projection as it was having too much
  67458. * instability during the light setup or during light position changes.
  67459. *
  67460. * Only valid if useContactHardeningShadow is true.
  67461. */
  67462. get: function () {
  67463. return this._contactHardeningLightSizeUVRatio;
  67464. },
  67465. /**
  67466. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67467. * Using a ratio helps keeping shape stability independently of the map size.
  67468. *
  67469. * It does not account for the light projection as it was having too much
  67470. * instability during the light setup or during light position changes.
  67471. *
  67472. * Only valid if useContactHardeningShadow is true.
  67473. */
  67474. set: function (contactHardeningLightSizeUVRatio) {
  67475. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67476. },
  67477. enumerable: true,
  67478. configurable: true
  67479. });
  67480. /**
  67481. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67482. * 0 means strongest and 1 would means no shadow.
  67483. * @returns the darkness.
  67484. */
  67485. ShadowGenerator.prototype.getDarkness = function () {
  67486. return this._darkness;
  67487. };
  67488. /**
  67489. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67490. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67491. * @returns the shadow generator allowing fluent coding.
  67492. */
  67493. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67494. if (darkness >= 1.0)
  67495. this._darkness = 1.0;
  67496. else if (darkness <= 0.0)
  67497. this._darkness = 0.0;
  67498. else
  67499. this._darkness = darkness;
  67500. return this;
  67501. };
  67502. /**
  67503. * Sets the ability to have transparent shadow (boolean).
  67504. * @param transparent True if transparent else False
  67505. * @returns the shadow generator allowing fluent coding
  67506. */
  67507. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67508. this._transparencyShadow = transparent;
  67509. return this;
  67510. };
  67511. /**
  67512. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67513. * @returns The render target texture if present otherwise, null
  67514. */
  67515. ShadowGenerator.prototype.getShadowMap = function () {
  67516. return this._shadowMap;
  67517. };
  67518. /**
  67519. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67520. * @returns The render target texture if the shadow map is present otherwise, null
  67521. */
  67522. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67523. if (this._shadowMap2) {
  67524. return this._shadowMap2;
  67525. }
  67526. return this._shadowMap;
  67527. };
  67528. /**
  67529. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67530. * @param mesh Mesh to add
  67531. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67532. * @returns the Shadow Generator itself
  67533. */
  67534. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67535. if (includeDescendants === void 0) { includeDescendants = true; }
  67536. if (!this._shadowMap) {
  67537. return this;
  67538. }
  67539. if (!this._shadowMap.renderList) {
  67540. this._shadowMap.renderList = [];
  67541. }
  67542. this._shadowMap.renderList.push(mesh);
  67543. if (includeDescendants) {
  67544. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67545. }
  67546. return this;
  67547. var _a;
  67548. };
  67549. /**
  67550. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67551. * @param mesh Mesh to remove
  67552. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67553. * @returns the Shadow Generator itself
  67554. */
  67555. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67556. if (includeDescendants === void 0) { includeDescendants = true; }
  67557. if (!this._shadowMap || !this._shadowMap.renderList) {
  67558. return this;
  67559. }
  67560. var index = this._shadowMap.renderList.indexOf(mesh);
  67561. if (index !== -1) {
  67562. this._shadowMap.renderList.splice(index, 1);
  67563. }
  67564. if (includeDescendants) {
  67565. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67566. var child = _a[_i];
  67567. this.removeShadowCaster(child);
  67568. }
  67569. }
  67570. return this;
  67571. };
  67572. /**
  67573. * Returns the associated light object.
  67574. * @returns the light generating the shadow
  67575. */
  67576. ShadowGenerator.prototype.getLight = function () {
  67577. return this._light;
  67578. };
  67579. ShadowGenerator.prototype._initializeGenerator = function () {
  67580. this._light._markMeshesAsLightDirty();
  67581. this._initializeShadowMap();
  67582. };
  67583. ShadowGenerator.prototype._initializeShadowMap = function () {
  67584. var _this = this;
  67585. // Render target
  67586. var engine = this._scene.getEngine();
  67587. if (engine.webGLVersion > 1) {
  67588. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67589. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67590. }
  67591. else {
  67592. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67593. }
  67594. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67595. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67596. this._shadowMap.anisotropicFilteringLevel = 1;
  67597. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67598. this._shadowMap.renderParticles = false;
  67599. this._shadowMap.ignoreCameraViewport = true;
  67600. // Record Face Index before render.
  67601. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67602. _this._currentFaceIndex = faceIndex;
  67603. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67604. engine.setColorWrite(false);
  67605. }
  67606. });
  67607. // Custom render function.
  67608. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67609. // Blur if required afer render.
  67610. this._shadowMap.onAfterUnbindObservable.add(function () {
  67611. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67612. engine.setColorWrite(true);
  67613. }
  67614. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67615. return;
  67616. }
  67617. var shadowMap = _this.getShadowMapForRendering();
  67618. if (shadowMap) {
  67619. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67620. }
  67621. });
  67622. // Clear according to the chosen filter.
  67623. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67624. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67625. this._shadowMap.onClearObservable.add(function (engine) {
  67626. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67627. engine.clear(clearOne, false, true, false);
  67628. }
  67629. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  67630. engine.clear(clearZero, true, true, false);
  67631. }
  67632. else {
  67633. engine.clear(clearOne, true, true, false);
  67634. }
  67635. });
  67636. };
  67637. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  67638. var _this = this;
  67639. var engine = this._scene.getEngine();
  67640. var targetSize = this._mapSize / this.blurScale;
  67641. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  67642. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  67643. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67644. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67645. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67646. }
  67647. if (this.useKernelBlur) {
  67648. 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);
  67649. this._kernelBlurXPostprocess.width = targetSize;
  67650. this._kernelBlurXPostprocess.height = targetSize;
  67651. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  67652. effect.setTexture("textureSampler", _this._shadowMap);
  67653. });
  67654. 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);
  67655. this._kernelBlurXPostprocess.autoClear = false;
  67656. this._kernelBlurYPostprocess.autoClear = false;
  67657. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67658. this._kernelBlurXPostprocess.packedFloat = true;
  67659. this._kernelBlurYPostprocess.packedFloat = true;
  67660. }
  67661. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  67662. }
  67663. else {
  67664. 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);
  67665. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  67666. effect.setFloat2("screenSize", targetSize, targetSize);
  67667. effect.setTexture("textureSampler", _this._shadowMap);
  67668. });
  67669. this._boxBlurPostprocess.autoClear = false;
  67670. this._blurPostProcesses = [this._boxBlurPostprocess];
  67671. }
  67672. };
  67673. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67674. var index;
  67675. var engine = this._scene.getEngine();
  67676. if (depthOnlySubMeshes.length) {
  67677. engine.setColorWrite(false);
  67678. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67679. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  67680. }
  67681. engine.setColorWrite(true);
  67682. }
  67683. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67684. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  67685. }
  67686. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67687. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  67688. }
  67689. if (this._transparencyShadow) {
  67690. for (index = 0; index < transparentSubMeshes.length; index++) {
  67691. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  67692. }
  67693. }
  67694. };
  67695. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  67696. var _this = this;
  67697. var mesh = subMesh.getRenderingMesh();
  67698. var scene = this._scene;
  67699. var engine = scene.getEngine();
  67700. var material = subMesh.getMaterial();
  67701. if (!material) {
  67702. return;
  67703. }
  67704. // Culling
  67705. engine.setState(material.backFaceCulling);
  67706. // Managing instances
  67707. var batch = mesh._getInstancesRenderList(subMesh._id);
  67708. if (batch.mustReturn) {
  67709. return;
  67710. }
  67711. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67712. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  67713. engine.enableEffect(this._effect);
  67714. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67715. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  67716. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  67717. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67718. this._effect.setVector3("lightData", this._cachedDirection);
  67719. }
  67720. else {
  67721. this._effect.setVector3("lightData", this._cachedPosition);
  67722. }
  67723. if (scene.activeCamera) {
  67724. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  67725. }
  67726. // Alpha test
  67727. if (material && material.needAlphaTesting()) {
  67728. var alphaTexture = material.getAlphaTestTexture();
  67729. if (alphaTexture) {
  67730. this._effect.setTexture("diffuseSampler", alphaTexture);
  67731. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  67732. }
  67733. }
  67734. // Bones
  67735. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67736. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  67737. }
  67738. // Morph targets
  67739. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  67740. if (this.forceBackFacesOnly) {
  67741. engine.setState(true, 0, false, true);
  67742. }
  67743. // Draw
  67744. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67745. if (this.forceBackFacesOnly) {
  67746. engine.setState(true, 0, false, false);
  67747. }
  67748. }
  67749. else {
  67750. // Need to reset refresh rate of the shadowMap
  67751. if (this._shadowMap) {
  67752. this._shadowMap.resetRefreshCounter();
  67753. }
  67754. }
  67755. };
  67756. ShadowGenerator.prototype._applyFilterValues = function () {
  67757. if (!this._shadowMap) {
  67758. return;
  67759. }
  67760. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  67761. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67762. }
  67763. else {
  67764. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67765. }
  67766. };
  67767. /**
  67768. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67769. * @param onCompiled Callback triggered at the and of the effects compilation
  67770. * @param options Sets of optional options forcing the compilation with different modes
  67771. */
  67772. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  67773. var _this = this;
  67774. var localOptions = __assign({ useInstances: false }, options);
  67775. var shadowMap = this.getShadowMap();
  67776. if (!shadowMap) {
  67777. if (onCompiled) {
  67778. onCompiled(this);
  67779. }
  67780. return;
  67781. }
  67782. var renderList = shadowMap.renderList;
  67783. if (!renderList) {
  67784. if (onCompiled) {
  67785. onCompiled(this);
  67786. }
  67787. return;
  67788. }
  67789. var subMeshes = new Array();
  67790. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  67791. var mesh = renderList_1[_i];
  67792. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  67793. }
  67794. if (subMeshes.length === 0) {
  67795. if (onCompiled) {
  67796. onCompiled(this);
  67797. }
  67798. return;
  67799. }
  67800. var currentIndex = 0;
  67801. var checkReady = function () {
  67802. if (!_this._scene || !_this._scene.getEngine()) {
  67803. return;
  67804. }
  67805. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  67806. currentIndex++;
  67807. if (currentIndex >= subMeshes.length) {
  67808. if (onCompiled) {
  67809. onCompiled(_this);
  67810. }
  67811. return;
  67812. }
  67813. }
  67814. setTimeout(checkReady, 16);
  67815. };
  67816. checkReady();
  67817. };
  67818. /**
  67819. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67820. * @param options Sets of optional options forcing the compilation with different modes
  67821. * @returns A promise that resolves when the compilation completes
  67822. */
  67823. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  67824. var _this = this;
  67825. return new Promise(function (resolve) {
  67826. _this.forceCompilation(function () {
  67827. resolve();
  67828. }, options);
  67829. });
  67830. };
  67831. /**
  67832. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67833. * @param subMesh The submesh we want to render in the shadow map
  67834. * @param useInstances Defines wether will draw in the map using instances
  67835. * @returns true if ready otherwise, false
  67836. */
  67837. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67838. var defines = [];
  67839. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67840. defines.push("#define FLOAT");
  67841. }
  67842. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67843. defines.push("#define ESM");
  67844. }
  67845. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67846. defines.push("#define DEPTHTEXTURE");
  67847. }
  67848. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67849. var mesh = subMesh.getMesh();
  67850. var material = subMesh.getMaterial();
  67851. // Normal bias.
  67852. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67853. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67854. defines.push("#define NORMAL");
  67855. if (mesh.nonUniformScaling) {
  67856. defines.push("#define NONUNIFORMSCALING");
  67857. }
  67858. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67859. defines.push("#define DIRECTIONINLIGHTDATA");
  67860. }
  67861. }
  67862. // Alpha test
  67863. if (material && material.needAlphaTesting()) {
  67864. var alphaTexture = material.getAlphaTestTexture();
  67865. if (alphaTexture) {
  67866. defines.push("#define ALPHATEST");
  67867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67868. attribs.push(BABYLON.VertexBuffer.UVKind);
  67869. defines.push("#define UV1");
  67870. }
  67871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67872. if (alphaTexture.coordinatesIndex === 1) {
  67873. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67874. defines.push("#define UV2");
  67875. }
  67876. }
  67877. }
  67878. }
  67879. // Bones
  67880. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67881. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67882. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67883. if (mesh.numBoneInfluencers > 4) {
  67884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67886. }
  67887. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67888. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67889. }
  67890. else {
  67891. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67892. }
  67893. // Morph targets
  67894. var manager = mesh.morphTargetManager;
  67895. var morphInfluencers = 0;
  67896. if (manager) {
  67897. if (manager.numInfluencers > 0) {
  67898. defines.push("#define MORPHTARGETS");
  67899. morphInfluencers = manager.numInfluencers;
  67900. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67901. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67902. }
  67903. }
  67904. // Instances
  67905. if (useInstances) {
  67906. defines.push("#define INSTANCES");
  67907. attribs.push("world0");
  67908. attribs.push("world1");
  67909. attribs.push("world2");
  67910. attribs.push("world3");
  67911. }
  67912. // Get correct effect
  67913. var join = defines.join("\n");
  67914. if (this._cachedDefines !== join) {
  67915. this._cachedDefines = join;
  67916. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67917. }
  67918. if (!this._effect.isReady()) {
  67919. return false;
  67920. }
  67921. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67922. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67923. this._initializeBlurRTTAndPostProcesses();
  67924. }
  67925. }
  67926. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67927. return false;
  67928. }
  67929. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67930. return false;
  67931. }
  67932. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67933. return false;
  67934. }
  67935. return true;
  67936. };
  67937. /**
  67938. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67939. * @param defines Defines of the material we want to update
  67940. * @param lightIndex Index of the light in the enabled light list of the material
  67941. */
  67942. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67943. var scene = this._scene;
  67944. var light = this._light;
  67945. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67946. return;
  67947. }
  67948. defines["SHADOW" + lightIndex] = true;
  67949. if (this.useContactHardeningShadow) {
  67950. defines["SHADOWPCSS" + lightIndex] = true;
  67951. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67952. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67953. }
  67954. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67955. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67956. }
  67957. // else default to high.
  67958. }
  67959. if (this.usePercentageCloserFiltering) {
  67960. defines["SHADOWPCF" + lightIndex] = true;
  67961. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67962. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67963. }
  67964. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67965. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67966. }
  67967. // else default to high.
  67968. }
  67969. else if (this.usePoissonSampling) {
  67970. defines["SHADOWPOISSON" + lightIndex] = true;
  67971. }
  67972. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67973. defines["SHADOWESM" + lightIndex] = true;
  67974. }
  67975. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67976. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67977. }
  67978. if (light.needCube()) {
  67979. defines["SHADOWCUBE" + lightIndex] = true;
  67980. }
  67981. };
  67982. /**
  67983. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67984. * defined in the generator but impacting the effect).
  67985. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67986. * @param effect The effect we are binfing the information for
  67987. */
  67988. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67989. var light = this._light;
  67990. var scene = this._scene;
  67991. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67992. return;
  67993. }
  67994. var camera = scene.activeCamera;
  67995. if (!camera) {
  67996. return;
  67997. }
  67998. var shadowMap = this.getShadowMap();
  67999. if (!shadowMap) {
  68000. return;
  68001. }
  68002. if (!light.needCube()) {
  68003. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68004. }
  68005. // Only PCF uses depth stencil texture.
  68006. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68007. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68008. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68009. }
  68010. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68011. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68012. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68013. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68014. }
  68015. else {
  68016. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68017. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68018. }
  68019. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68020. };
  68021. /**
  68022. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68023. * (eq to shadow prjection matrix * light transform matrix)
  68024. * @returns The transform matrix used to create the shadow map
  68025. */
  68026. ShadowGenerator.prototype.getTransformMatrix = function () {
  68027. var scene = this._scene;
  68028. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68029. return this._transformMatrix;
  68030. }
  68031. this._currentRenderID = scene.getRenderId();
  68032. this._currentFaceIndexCache = this._currentFaceIndex;
  68033. var lightPosition = this._light.position;
  68034. if (this._light.computeTransformedInformation()) {
  68035. lightPosition = this._light.transformedPosition;
  68036. }
  68037. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68038. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68039. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68040. }
  68041. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68042. this._cachedPosition.copyFrom(lightPosition);
  68043. this._cachedDirection.copyFrom(this._lightDirection);
  68044. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68045. var shadowMap = this.getShadowMap();
  68046. if (shadowMap) {
  68047. var renderList = shadowMap.renderList;
  68048. if (renderList) {
  68049. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68050. }
  68051. }
  68052. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68053. }
  68054. return this._transformMatrix;
  68055. };
  68056. /**
  68057. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68058. * Cube and 2D textures for instance.
  68059. */
  68060. ShadowGenerator.prototype.recreateShadowMap = function () {
  68061. var shadowMap = this._shadowMap;
  68062. if (!shadowMap) {
  68063. return;
  68064. }
  68065. // Track render list.
  68066. var renderList = shadowMap.renderList;
  68067. // Clean up existing data.
  68068. this._disposeRTTandPostProcesses();
  68069. // Reinitializes.
  68070. this._initializeGenerator();
  68071. // Reaffect the filter to ensure a correct fallback if necessary.
  68072. this.filter = this.filter;
  68073. // Reaffect the filter.
  68074. this._applyFilterValues();
  68075. // Reaffect Render List.
  68076. this._shadowMap.renderList = renderList;
  68077. };
  68078. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68079. if (this._shadowMap2) {
  68080. this._shadowMap2.dispose();
  68081. this._shadowMap2 = null;
  68082. }
  68083. if (this._boxBlurPostprocess) {
  68084. this._boxBlurPostprocess.dispose();
  68085. this._boxBlurPostprocess = null;
  68086. }
  68087. if (this._kernelBlurXPostprocess) {
  68088. this._kernelBlurXPostprocess.dispose();
  68089. this._kernelBlurXPostprocess = null;
  68090. }
  68091. if (this._kernelBlurYPostprocess) {
  68092. this._kernelBlurYPostprocess.dispose();
  68093. this._kernelBlurYPostprocess = null;
  68094. }
  68095. this._blurPostProcesses = [];
  68096. };
  68097. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68098. if (this._shadowMap) {
  68099. this._shadowMap.dispose();
  68100. this._shadowMap = null;
  68101. }
  68102. this._disposeBlurPostProcesses();
  68103. };
  68104. /**
  68105. * Disposes the ShadowGenerator.
  68106. * Returns nothing.
  68107. */
  68108. ShadowGenerator.prototype.dispose = function () {
  68109. this._disposeRTTandPostProcesses();
  68110. if (this._light) {
  68111. this._light._shadowGenerator = null;
  68112. this._light._markMeshesAsLightDirty();
  68113. }
  68114. };
  68115. /**
  68116. * Serializes the shadow generator setup to a json object.
  68117. * @returns The serialized JSON object
  68118. */
  68119. ShadowGenerator.prototype.serialize = function () {
  68120. var serializationObject = {};
  68121. var shadowMap = this.getShadowMap();
  68122. if (!shadowMap) {
  68123. return serializationObject;
  68124. }
  68125. serializationObject.lightId = this._light.id;
  68126. serializationObject.mapSize = shadowMap.getRenderSize();
  68127. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68128. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68129. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68130. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68131. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68132. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68133. serializationObject.depthScale = this.depthScale;
  68134. serializationObject.darkness = this.getDarkness();
  68135. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68136. serializationObject.blurKernel = this.blurKernel;
  68137. serializationObject.blurScale = this.blurScale;
  68138. serializationObject.useKernelBlur = this.useKernelBlur;
  68139. serializationObject.transparencyShadow = this._transparencyShadow;
  68140. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68141. serializationObject.bias = this.bias;
  68142. serializationObject.normalBias = this.normalBias;
  68143. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68144. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68145. serializationObject.filteringQuality = this.filteringQuality;
  68146. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68147. serializationObject.renderList = [];
  68148. if (shadowMap.renderList) {
  68149. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68150. var mesh = shadowMap.renderList[meshIndex];
  68151. serializationObject.renderList.push(mesh.id);
  68152. }
  68153. }
  68154. return serializationObject;
  68155. };
  68156. /**
  68157. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68158. * @param parsedShadowGenerator The JSON object to parse
  68159. * @param scene The scene to create the shadow map for
  68160. * @returns The parsed shadow generator
  68161. */
  68162. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68163. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68164. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68165. var shadowMap = shadowGenerator.getShadowMap();
  68166. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68167. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68168. meshes.forEach(function (mesh) {
  68169. if (!shadowMap) {
  68170. return;
  68171. }
  68172. if (!shadowMap.renderList) {
  68173. shadowMap.renderList = [];
  68174. }
  68175. shadowMap.renderList.push(mesh);
  68176. });
  68177. }
  68178. if (parsedShadowGenerator.usePoissonSampling) {
  68179. shadowGenerator.usePoissonSampling = true;
  68180. }
  68181. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68182. shadowGenerator.useExponentialShadowMap = true;
  68183. }
  68184. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68185. shadowGenerator.useBlurExponentialShadowMap = true;
  68186. }
  68187. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68188. shadowGenerator.useCloseExponentialShadowMap = true;
  68189. }
  68190. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68191. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68192. }
  68193. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68194. shadowGenerator.usePercentageCloserFiltering = true;
  68195. }
  68196. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68197. shadowGenerator.useContactHardeningShadow = true;
  68198. }
  68199. if (parsedShadowGenerator.filteringQuality) {
  68200. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68201. }
  68202. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68203. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68204. }
  68205. // Backward compat
  68206. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68207. shadowGenerator.useExponentialShadowMap = true;
  68208. }
  68209. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68210. shadowGenerator.useBlurExponentialShadowMap = true;
  68211. }
  68212. if (parsedShadowGenerator.depthScale) {
  68213. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68214. }
  68215. if (parsedShadowGenerator.blurScale) {
  68216. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68217. }
  68218. if (parsedShadowGenerator.blurBoxOffset) {
  68219. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68220. }
  68221. if (parsedShadowGenerator.useKernelBlur) {
  68222. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68223. }
  68224. if (parsedShadowGenerator.blurKernel) {
  68225. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68226. }
  68227. if (parsedShadowGenerator.bias !== undefined) {
  68228. shadowGenerator.bias = parsedShadowGenerator.bias;
  68229. }
  68230. if (parsedShadowGenerator.normalBias !== undefined) {
  68231. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68232. }
  68233. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68234. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68235. }
  68236. if (parsedShadowGenerator.darkness) {
  68237. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68238. }
  68239. if (parsedShadowGenerator.transparencyShadow) {
  68240. shadowGenerator.setTransparencyShadow(true);
  68241. }
  68242. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68243. return shadowGenerator;
  68244. };
  68245. /**
  68246. * Shadow generator mode None: no filtering applied.
  68247. */
  68248. ShadowGenerator.FILTER_NONE = 0;
  68249. /**
  68250. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68251. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68252. */
  68253. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68254. /**
  68255. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68256. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68257. */
  68258. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68259. /**
  68260. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68261. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68262. */
  68263. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68264. /**
  68265. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68266. * edge artifacts on steep falloff.
  68267. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68268. */
  68269. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68270. /**
  68271. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68272. * edge artifacts on steep falloff.
  68273. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68274. */
  68275. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68276. /**
  68277. * Shadow generator mode PCF: Percentage Closer Filtering
  68278. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68279. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68280. */
  68281. ShadowGenerator.FILTER_PCF = 6;
  68282. /**
  68283. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68284. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68285. * Contact Hardening
  68286. */
  68287. ShadowGenerator.FILTER_PCSS = 7;
  68288. /**
  68289. * Reserved for PCF and PCSS
  68290. * Highest Quality.
  68291. *
  68292. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68293. *
  68294. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68295. */
  68296. ShadowGenerator.QUALITY_HIGH = 0;
  68297. /**
  68298. * Reserved for PCF and PCSS
  68299. * Good tradeoff for quality/perf cross devices
  68300. *
  68301. * Execute PCF on a 3*3 kernel.
  68302. *
  68303. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68304. */
  68305. ShadowGenerator.QUALITY_MEDIUM = 1;
  68306. /**
  68307. * Reserved for PCF and PCSS
  68308. * The lowest quality but the fastest.
  68309. *
  68310. * Execute PCF on a 1*1 kernel.
  68311. *
  68312. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68313. */
  68314. ShadowGenerator.QUALITY_LOW = 2;
  68315. return ShadowGenerator;
  68316. }());
  68317. BABYLON.ShadowGenerator = ShadowGenerator;
  68318. })(BABYLON || (BABYLON = {}));
  68319. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68320. var BABYLON;
  68321. (function (BABYLON) {
  68322. var DefaultLoadingScreen = /** @class */ (function () {
  68323. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68324. if (_loadingText === void 0) { _loadingText = ""; }
  68325. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68326. var _this = this;
  68327. this._renderingCanvas = _renderingCanvas;
  68328. this._loadingText = _loadingText;
  68329. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68330. // Resize
  68331. this._resizeLoadingUI = function () {
  68332. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68333. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68334. if (!_this._loadingDiv) {
  68335. return;
  68336. }
  68337. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68338. _this._loadingDiv.style.left = canvasRect.left + "px";
  68339. _this._loadingDiv.style.top = canvasRect.top + "px";
  68340. _this._loadingDiv.style.width = canvasRect.width + "px";
  68341. _this._loadingDiv.style.height = canvasRect.height + "px";
  68342. };
  68343. }
  68344. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68345. if (this._loadingDiv) {
  68346. // Do not add a loading screen if there is already one
  68347. return;
  68348. }
  68349. this._loadingDiv = document.createElement("div");
  68350. this._loadingDiv.id = "babylonjsLoadingDiv";
  68351. this._loadingDiv.style.opacity = "0";
  68352. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68353. this._loadingDiv.style.pointerEvents = "none";
  68354. // Loading text
  68355. this._loadingTextDiv = document.createElement("div");
  68356. this._loadingTextDiv.style.position = "absolute";
  68357. this._loadingTextDiv.style.left = "0";
  68358. this._loadingTextDiv.style.top = "50%";
  68359. this._loadingTextDiv.style.marginTop = "80px";
  68360. this._loadingTextDiv.style.width = "100%";
  68361. this._loadingTextDiv.style.height = "20px";
  68362. this._loadingTextDiv.style.fontFamily = "Arial";
  68363. this._loadingTextDiv.style.fontSize = "14px";
  68364. this._loadingTextDiv.style.color = "white";
  68365. this._loadingTextDiv.style.textAlign = "center";
  68366. this._loadingTextDiv.innerHTML = "Loading";
  68367. this._loadingDiv.appendChild(this._loadingTextDiv);
  68368. //set the predefined text
  68369. this._loadingTextDiv.innerHTML = this._loadingText;
  68370. // Generating keyframes
  68371. var style = document.createElement('style');
  68372. style.type = 'text/css';
  68373. 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 }";
  68374. style.innerHTML = keyFrames;
  68375. document.getElementsByTagName('head')[0].appendChild(style);
  68376. // Loading img
  68377. var imgBack = new Image();
  68378. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAA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YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  68379. imgBack.style.position = "absolute";
  68380. imgBack.style.left = "50%";
  68381. imgBack.style.top = "50%";
  68382. imgBack.style.marginLeft = "-60px";
  68383. imgBack.style.marginTop = "-60px";
  68384. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68385. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68386. imgBack.style.transformOrigin = "50% 50%";
  68387. imgBack.style.webkitTransformOrigin = "50% 50%";
  68388. this._loadingDiv.appendChild(imgBack);
  68389. this._resizeLoadingUI();
  68390. window.addEventListener("resize", this._resizeLoadingUI);
  68391. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68392. document.body.appendChild(this._loadingDiv);
  68393. this._loadingDiv.style.opacity = "1";
  68394. };
  68395. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68396. var _this = this;
  68397. if (!this._loadingDiv) {
  68398. return;
  68399. }
  68400. var onTransitionEnd = function () {
  68401. if (!_this._loadingDiv) {
  68402. return;
  68403. }
  68404. document.body.removeChild(_this._loadingDiv);
  68405. window.removeEventListener("resize", _this._resizeLoadingUI);
  68406. _this._loadingDiv = null;
  68407. };
  68408. this._loadingDiv.style.opacity = "0";
  68409. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68410. };
  68411. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68412. set: function (text) {
  68413. this._loadingText = text;
  68414. if (this._loadingTextDiv) {
  68415. this._loadingTextDiv.innerHTML = this._loadingText;
  68416. }
  68417. },
  68418. enumerable: true,
  68419. configurable: true
  68420. });
  68421. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68422. get: function () {
  68423. return this._loadingDivBackgroundColor;
  68424. },
  68425. set: function (color) {
  68426. this._loadingDivBackgroundColor = color;
  68427. if (!this._loadingDiv) {
  68428. return;
  68429. }
  68430. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68431. },
  68432. enumerable: true,
  68433. configurable: true
  68434. });
  68435. return DefaultLoadingScreen;
  68436. }());
  68437. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68438. })(BABYLON || (BABYLON = {}));
  68439. //# sourceMappingURL=babylon.loadingScreen.js.map
  68440. var BABYLON;
  68441. (function (BABYLON) {
  68442. var SceneLoaderProgressEvent = /** @class */ (function () {
  68443. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68444. this.lengthComputable = lengthComputable;
  68445. this.loaded = loaded;
  68446. this.total = total;
  68447. }
  68448. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68449. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68450. };
  68451. return SceneLoaderProgressEvent;
  68452. }());
  68453. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68454. var SceneLoader = /** @class */ (function () {
  68455. function SceneLoader() {
  68456. }
  68457. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68458. get: function () {
  68459. return 0;
  68460. },
  68461. enumerable: true,
  68462. configurable: true
  68463. });
  68464. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68465. get: function () {
  68466. return 1;
  68467. },
  68468. enumerable: true,
  68469. configurable: true
  68470. });
  68471. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68472. get: function () {
  68473. return 2;
  68474. },
  68475. enumerable: true,
  68476. configurable: true
  68477. });
  68478. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68479. get: function () {
  68480. return 3;
  68481. },
  68482. enumerable: true,
  68483. configurable: true
  68484. });
  68485. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68486. get: function () {
  68487. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68488. },
  68489. set: function (value) {
  68490. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68491. },
  68492. enumerable: true,
  68493. configurable: true
  68494. });
  68495. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68496. get: function () {
  68497. return SceneLoader._ShowLoadingScreen;
  68498. },
  68499. set: function (value) {
  68500. SceneLoader._ShowLoadingScreen = value;
  68501. },
  68502. enumerable: true,
  68503. configurable: true
  68504. });
  68505. Object.defineProperty(SceneLoader, "loggingLevel", {
  68506. get: function () {
  68507. return SceneLoader._loggingLevel;
  68508. },
  68509. set: function (value) {
  68510. SceneLoader._loggingLevel = value;
  68511. },
  68512. enumerable: true,
  68513. configurable: true
  68514. });
  68515. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68516. get: function () {
  68517. return SceneLoader._CleanBoneMatrixWeights;
  68518. },
  68519. set: function (value) {
  68520. SceneLoader._CleanBoneMatrixWeights = value;
  68521. },
  68522. enumerable: true,
  68523. configurable: true
  68524. });
  68525. SceneLoader._getDefaultPlugin = function () {
  68526. return SceneLoader._registeredPlugins[".babylon"];
  68527. };
  68528. SceneLoader._getPluginForExtension = function (extension) {
  68529. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68530. if (registeredPlugin) {
  68531. return registeredPlugin;
  68532. }
  68533. 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");
  68534. return SceneLoader._getDefaultPlugin();
  68535. };
  68536. SceneLoader._getPluginForDirectLoad = function (data) {
  68537. for (var extension in SceneLoader._registeredPlugins) {
  68538. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68539. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68540. return SceneLoader._registeredPlugins[extension];
  68541. }
  68542. }
  68543. return SceneLoader._getDefaultPlugin();
  68544. };
  68545. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68546. if (sceneFilename.name) {
  68547. sceneFilename = sceneFilename.name;
  68548. }
  68549. var queryStringPosition = sceneFilename.indexOf("?");
  68550. if (queryStringPosition !== -1) {
  68551. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68552. }
  68553. var dotPosition = sceneFilename.lastIndexOf(".");
  68554. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68555. return SceneLoader._getPluginForExtension(extension);
  68556. };
  68557. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68558. SceneLoader._getDirectLoad = function (sceneFilename) {
  68559. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68560. return sceneFilename.substr(5);
  68561. }
  68562. return null;
  68563. };
  68564. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68565. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68566. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68567. var plugin;
  68568. if (registeredPlugin.plugin.createPlugin) {
  68569. plugin = registeredPlugin.plugin.createPlugin();
  68570. }
  68571. else {
  68572. plugin = registeredPlugin.plugin;
  68573. }
  68574. var useArrayBuffer = registeredPlugin.isBinary;
  68575. var database;
  68576. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68577. var dataCallback = function (data, responseURL) {
  68578. if (scene.isDisposed) {
  68579. onError("Scene has been disposed");
  68580. return;
  68581. }
  68582. scene.database = database;
  68583. onSuccess(plugin, data, responseURL);
  68584. };
  68585. var request = null;
  68586. var pluginDisposed = false;
  68587. var onDisposeObservable = plugin.onDisposeObservable;
  68588. if (onDisposeObservable) {
  68589. onDisposeObservable.add(function () {
  68590. pluginDisposed = true;
  68591. if (request) {
  68592. request.abort();
  68593. request = null;
  68594. }
  68595. onDispose();
  68596. });
  68597. }
  68598. var manifestChecked = function () {
  68599. if (pluginDisposed) {
  68600. return;
  68601. }
  68602. var url = rootUrl + sceneFilename;
  68603. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68604. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68605. } : undefined, database, useArrayBuffer, function (request, exception) {
  68606. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68607. });
  68608. };
  68609. if (directLoad) {
  68610. dataCallback(directLoad);
  68611. return plugin;
  68612. }
  68613. if (rootUrl.indexOf("file:") === -1) {
  68614. var engine = scene.getEngine();
  68615. var canUseOfflineSupport = engine.enableOfflineSupport;
  68616. if (canUseOfflineSupport) {
  68617. // Also check for exceptions
  68618. var exceptionFound = false;
  68619. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68620. var regex = _a[_i];
  68621. if (regex.test(rootUrl + sceneFilename)) {
  68622. exceptionFound = true;
  68623. break;
  68624. }
  68625. }
  68626. canUseOfflineSupport = !exceptionFound;
  68627. }
  68628. if (canUseOfflineSupport) {
  68629. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  68630. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  68631. }
  68632. else {
  68633. manifestChecked();
  68634. }
  68635. }
  68636. // Loading file from disk via input file or drag'n'drop
  68637. else {
  68638. var fileOrString = sceneFilename;
  68639. if (fileOrString.name) { // File
  68640. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  68641. }
  68642. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  68643. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  68644. }
  68645. else {
  68646. onError("Unable to find file named " + sceneFilename);
  68647. }
  68648. }
  68649. return plugin;
  68650. };
  68651. // Public functions
  68652. SceneLoader.GetPluginForExtension = function (extension) {
  68653. return SceneLoader._getPluginForExtension(extension).plugin;
  68654. };
  68655. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  68656. return !!SceneLoader._registeredPlugins[extension];
  68657. };
  68658. SceneLoader.RegisterPlugin = function (plugin) {
  68659. if (typeof plugin.extensions === "string") {
  68660. var extension = plugin.extensions;
  68661. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68662. plugin: plugin,
  68663. isBinary: false
  68664. };
  68665. }
  68666. else {
  68667. var extensions = plugin.extensions;
  68668. Object.keys(extensions).forEach(function (extension) {
  68669. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68670. plugin: plugin,
  68671. isBinary: extensions[extension].isBinary
  68672. };
  68673. });
  68674. }
  68675. };
  68676. /**
  68677. * Import meshes into a scene
  68678. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68679. * @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)
  68680. * @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)
  68681. * @param scene the instance of BABYLON.Scene to append to
  68682. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  68683. * @param onProgress a callback with a progress event for each file being loaded
  68684. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68685. * @param pluginExtension the extension used to determine the plugin
  68686. * @returns The loaded plugin
  68687. */
  68688. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68689. if (sceneFilename === void 0) { sceneFilename = ""; }
  68690. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68691. if (onSuccess === void 0) { onSuccess = null; }
  68692. if (onProgress === void 0) { onProgress = null; }
  68693. if (onError === void 0) { onError = null; }
  68694. if (pluginExtension === void 0) { pluginExtension = null; }
  68695. if (!scene) {
  68696. BABYLON.Tools.Error("No scene available to import mesh to");
  68697. return null;
  68698. }
  68699. if (!sceneFilename) {
  68700. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68701. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68702. }
  68703. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68704. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68705. return null;
  68706. }
  68707. var loadingToken = {};
  68708. scene._addPendingData(loadingToken);
  68709. var disposeHandler = function () {
  68710. scene._removePendingData(loadingToken);
  68711. };
  68712. var errorHandler = function (message, exception) {
  68713. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  68714. if (onError) {
  68715. onError(scene, errorMessage, exception);
  68716. }
  68717. else {
  68718. BABYLON.Tools.Error(errorMessage);
  68719. // should the exception be thrown?
  68720. }
  68721. disposeHandler();
  68722. };
  68723. var progressHandler = onProgress ? function (event) {
  68724. try {
  68725. onProgress(event);
  68726. }
  68727. catch (e) {
  68728. errorHandler("Error in onProgress callback", e);
  68729. }
  68730. } : undefined;
  68731. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  68732. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  68733. if (onSuccess) {
  68734. try {
  68735. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  68736. }
  68737. catch (e) {
  68738. errorHandler("Error in onSuccess callback", e);
  68739. }
  68740. }
  68741. scene._removePendingData(loadingToken);
  68742. };
  68743. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68744. if (plugin.rewriteRootURL) {
  68745. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  68746. }
  68747. if (sceneFilename === "") {
  68748. if (sceneFilename === "") {
  68749. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68750. }
  68751. }
  68752. if (plugin.importMesh) {
  68753. var syncedPlugin = plugin;
  68754. var meshes = new Array();
  68755. var particleSystems = new Array();
  68756. var skeletons = new Array();
  68757. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  68758. return;
  68759. }
  68760. scene.loadingPluginName = plugin.name;
  68761. successHandler(meshes, particleSystems, skeletons, []);
  68762. }
  68763. else {
  68764. var asyncedPlugin = plugin;
  68765. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  68766. scene.loadingPluginName = plugin.name;
  68767. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  68768. }).catch(function (error) {
  68769. errorHandler(error.message, error);
  68770. });
  68771. }
  68772. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68773. };
  68774. /**
  68775. * Import meshes into a scene
  68776. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68777. * @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)
  68778. * @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)
  68779. * @param scene the instance of BABYLON.Scene to append to
  68780. * @param onProgress a callback with a progress event for each file being loaded
  68781. * @param pluginExtension the extension used to determine the plugin
  68782. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  68783. */
  68784. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68785. if (sceneFilename === void 0) { sceneFilename = ""; }
  68786. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68787. if (onProgress === void 0) { onProgress = null; }
  68788. if (pluginExtension === void 0) { pluginExtension = null; }
  68789. return new Promise(function (resolve, reject) {
  68790. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  68791. resolve({
  68792. meshes: meshes,
  68793. particleSystems: particleSystems,
  68794. skeletons: skeletons,
  68795. animationGroups: animationGroups
  68796. });
  68797. }, onProgress, function (scene, message, exception) {
  68798. reject(exception || new Error(message));
  68799. }, pluginExtension);
  68800. });
  68801. };
  68802. /**
  68803. * Load a scene
  68804. * @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)
  68805. * @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)
  68806. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68807. * @param onSuccess a callback with the scene when import succeeds
  68808. * @param onProgress a callback with a progress event for each file being loaded
  68809. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68810. * @param pluginExtension the extension used to determine the plugin
  68811. * @returns The loaded plugin
  68812. */
  68813. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  68814. if (onSuccess === void 0) { onSuccess = null; }
  68815. if (onProgress === void 0) { onProgress = null; }
  68816. if (onError === void 0) { onError = null; }
  68817. if (pluginExtension === void 0) { pluginExtension = null; }
  68818. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  68819. };
  68820. /**
  68821. * Load a scene
  68822. * @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)
  68823. * @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)
  68824. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68825. * @param onProgress a callback with a progress event for each file being loaded
  68826. * @param pluginExtension the extension used to determine the plugin
  68827. * @returns The loaded scene
  68828. */
  68829. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68830. if (onProgress === void 0) { onProgress = null; }
  68831. if (pluginExtension === void 0) { pluginExtension = null; }
  68832. return new Promise(function (resolve, reject) {
  68833. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68834. resolve(scene);
  68835. }, onProgress, function (scene, message, exception) {
  68836. reject(exception || new Error(message));
  68837. }, pluginExtension);
  68838. });
  68839. };
  68840. /**
  68841. * Append a scene
  68842. * @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)
  68843. * @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)
  68844. * @param scene is the instance of BABYLON.Scene to append to
  68845. * @param onSuccess a callback with the scene when import succeeds
  68846. * @param onProgress a callback with a progress event for each file being loaded
  68847. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68848. * @param pluginExtension the extension used to determine the plugin
  68849. * @returns The loaded plugin
  68850. */
  68851. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68852. if (sceneFilename === void 0) { sceneFilename = ""; }
  68853. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68854. if (onSuccess === void 0) { onSuccess = null; }
  68855. if (onProgress === void 0) { onProgress = null; }
  68856. if (onError === void 0) { onError = null; }
  68857. if (pluginExtension === void 0) { pluginExtension = null; }
  68858. if (!scene) {
  68859. BABYLON.Tools.Error("No scene available to append to");
  68860. return null;
  68861. }
  68862. if (!sceneFilename) {
  68863. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68864. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68865. }
  68866. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68867. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68868. return null;
  68869. }
  68870. if (SceneLoader.ShowLoadingScreen) {
  68871. scene.getEngine().displayLoadingUI();
  68872. }
  68873. var loadingToken = {};
  68874. scene._addPendingData(loadingToken);
  68875. var disposeHandler = function () {
  68876. scene._removePendingData(loadingToken);
  68877. scene.getEngine().hideLoadingUI();
  68878. };
  68879. var errorHandler = function (message, exception) {
  68880. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68881. if (onError) {
  68882. onError(scene, errorMessage, exception);
  68883. }
  68884. else {
  68885. BABYLON.Tools.Error(errorMessage);
  68886. // should the exception be thrown?
  68887. }
  68888. disposeHandler();
  68889. };
  68890. var progressHandler = onProgress ? function (event) {
  68891. try {
  68892. onProgress(event);
  68893. }
  68894. catch (e) {
  68895. errorHandler("Error in onProgress callback", e);
  68896. }
  68897. } : undefined;
  68898. var successHandler = function () {
  68899. if (onSuccess) {
  68900. try {
  68901. onSuccess(scene);
  68902. }
  68903. catch (e) {
  68904. errorHandler("Error in onSuccess callback", e);
  68905. }
  68906. }
  68907. scene._removePendingData(loadingToken);
  68908. };
  68909. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68910. if (sceneFilename === "") {
  68911. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68912. }
  68913. if (plugin.load) {
  68914. var syncedPlugin = plugin;
  68915. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68916. return;
  68917. }
  68918. scene.loadingPluginName = plugin.name;
  68919. successHandler();
  68920. }
  68921. else {
  68922. var asyncedPlugin = plugin;
  68923. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68924. scene.loadingPluginName = plugin.name;
  68925. successHandler();
  68926. }).catch(function (error) {
  68927. errorHandler(error.message, error);
  68928. });
  68929. }
  68930. if (SceneLoader.ShowLoadingScreen) {
  68931. scene.executeWhenReady(function () {
  68932. scene.getEngine().hideLoadingUI();
  68933. });
  68934. }
  68935. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68936. };
  68937. /**
  68938. * Append a scene
  68939. * @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)
  68940. * @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)
  68941. * @param scene is the instance of BABYLON.Scene to append to
  68942. * @param onProgress a callback with a progress event for each file being loaded
  68943. * @param pluginExtension the extension used to determine the plugin
  68944. * @returns The given scene
  68945. */
  68946. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68947. if (sceneFilename === void 0) { sceneFilename = ""; }
  68948. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68949. if (onProgress === void 0) { onProgress = null; }
  68950. if (pluginExtension === void 0) { pluginExtension = null; }
  68951. return new Promise(function (resolve, reject) {
  68952. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68953. resolve(scene);
  68954. }, onProgress, function (scene, message, exception) {
  68955. reject(exception || new Error(message));
  68956. }, pluginExtension);
  68957. });
  68958. };
  68959. /**
  68960. * Load a scene into an asset container
  68961. * @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)
  68962. * @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)
  68963. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68964. * @param onSuccess a callback with the scene when import succeeds
  68965. * @param onProgress a callback with a progress event for each file being loaded
  68966. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68967. * @param pluginExtension the extension used to determine the plugin
  68968. * @returns The loaded plugin
  68969. */
  68970. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68971. if (sceneFilename === void 0) { sceneFilename = ""; }
  68972. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68973. if (onSuccess === void 0) { onSuccess = null; }
  68974. if (onProgress === void 0) { onProgress = null; }
  68975. if (onError === void 0) { onError = null; }
  68976. if (pluginExtension === void 0) { pluginExtension = null; }
  68977. if (!scene) {
  68978. BABYLON.Tools.Error("No scene available to load asset container to");
  68979. return null;
  68980. }
  68981. if (!sceneFilename) {
  68982. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68983. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68984. }
  68985. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68986. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68987. return null;
  68988. }
  68989. var loadingToken = {};
  68990. scene._addPendingData(loadingToken);
  68991. var disposeHandler = function () {
  68992. scene._removePendingData(loadingToken);
  68993. };
  68994. var errorHandler = function (message, exception) {
  68995. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68996. if (onError) {
  68997. onError(scene, errorMessage, exception);
  68998. }
  68999. else {
  69000. BABYLON.Tools.Error(errorMessage);
  69001. // should the exception be thrown?
  69002. }
  69003. disposeHandler();
  69004. };
  69005. var progressHandler = onProgress ? function (event) {
  69006. try {
  69007. onProgress(event);
  69008. }
  69009. catch (e) {
  69010. errorHandler("Error in onProgress callback", e);
  69011. }
  69012. } : undefined;
  69013. var successHandler = function (assets) {
  69014. if (onSuccess) {
  69015. try {
  69016. onSuccess(assets);
  69017. }
  69018. catch (e) {
  69019. errorHandler("Error in onSuccess callback", e);
  69020. }
  69021. }
  69022. scene._removePendingData(loadingToken);
  69023. };
  69024. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69025. if (plugin.loadAssetContainer) {
  69026. var syncedPlugin = plugin;
  69027. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69028. if (!assetContainer) {
  69029. return;
  69030. }
  69031. scene.loadingPluginName = plugin.name;
  69032. successHandler(assetContainer);
  69033. }
  69034. else if (plugin.loadAssetContainerAsync) {
  69035. var asyncedPlugin = plugin;
  69036. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69037. scene.loadingPluginName = plugin.name;
  69038. successHandler(assetContainer);
  69039. }).catch(function (error) {
  69040. errorHandler(error.message, error);
  69041. });
  69042. }
  69043. else {
  69044. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69045. }
  69046. if (SceneLoader.ShowLoadingScreen) {
  69047. scene.executeWhenReady(function () {
  69048. scene.getEngine().hideLoadingUI();
  69049. });
  69050. }
  69051. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69052. };
  69053. /**
  69054. * Load a scene into an asset container
  69055. * @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)
  69056. * @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)
  69057. * @param scene is the instance of BABYLON.Scene to append to
  69058. * @param onProgress a callback with a progress event for each file being loaded
  69059. * @param pluginExtension the extension used to determine the plugin
  69060. * @returns The loaded asset container
  69061. */
  69062. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69063. if (sceneFilename === void 0) { sceneFilename = ""; }
  69064. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69065. if (onProgress === void 0) { onProgress = null; }
  69066. if (pluginExtension === void 0) { pluginExtension = null; }
  69067. return new Promise(function (resolve, reject) {
  69068. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69069. resolve(assetContainer);
  69070. }, onProgress, function (scene, message, exception) {
  69071. reject(exception || new Error(message));
  69072. }, pluginExtension);
  69073. });
  69074. };
  69075. // Flags
  69076. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69077. SceneLoader._ShowLoadingScreen = true;
  69078. SceneLoader._CleanBoneMatrixWeights = false;
  69079. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69080. // Members
  69081. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69082. SceneLoader._registeredPlugins = {};
  69083. return SceneLoader;
  69084. }());
  69085. BABYLON.SceneLoader = SceneLoader;
  69086. ;
  69087. })(BABYLON || (BABYLON = {}));
  69088. //# sourceMappingURL=babylon.sceneLoader.js.map
  69089. var BABYLON;
  69090. (function (BABYLON) {
  69091. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69092. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69093. var parsedMaterial = parsedData.materials[index];
  69094. if (parsedMaterial.id === id) {
  69095. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69096. }
  69097. }
  69098. return null;
  69099. };
  69100. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69101. for (var i in names) {
  69102. if (mesh.name === names[i]) {
  69103. hierarchyIds.push(mesh.id);
  69104. return true;
  69105. }
  69106. }
  69107. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69108. hierarchyIds.push(mesh.id);
  69109. return true;
  69110. }
  69111. return false;
  69112. };
  69113. var logOperation = function (operation, producer) {
  69114. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69115. };
  69116. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69117. if (addToScene === void 0) { addToScene = false; }
  69118. var container = new BABYLON.AssetContainer(scene);
  69119. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69120. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69121. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69122. // and avoid problems with multiple concurrent .babylon loads.
  69123. var log = "importScene has failed JSON parse";
  69124. try {
  69125. var parsedData = JSON.parse(data);
  69126. log = "";
  69127. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69128. var index;
  69129. var cache;
  69130. // Lights
  69131. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69132. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69133. var parsedLight = parsedData.lights[index];
  69134. var light = BABYLON.Light.Parse(parsedLight, scene);
  69135. if (light) {
  69136. container.lights.push(light);
  69137. log += (index === 0 ? "\n\tLights:" : "");
  69138. log += "\n\t\t" + light.toString(fullDetails);
  69139. }
  69140. }
  69141. }
  69142. // Animations
  69143. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69144. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69145. var parsedAnimation = parsedData.animations[index];
  69146. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69147. scene.animations.push(animation);
  69148. container.animations.push(animation);
  69149. log += (index === 0 ? "\n\tAnimations:" : "");
  69150. log += "\n\t\t" + animation.toString(fullDetails);
  69151. }
  69152. }
  69153. // Materials
  69154. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69155. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69156. var parsedMaterial = parsedData.materials[index];
  69157. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69158. container.materials.push(mat);
  69159. log += (index === 0 ? "\n\tMaterials:" : "");
  69160. log += "\n\t\t" + mat.toString(fullDetails);
  69161. }
  69162. }
  69163. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69164. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69165. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69166. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69167. container.multiMaterials.push(mmat);
  69168. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69169. log += "\n\t\t" + mmat.toString(fullDetails);
  69170. }
  69171. }
  69172. // Morph targets
  69173. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69174. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69175. var managerData = _a[_i];
  69176. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69177. }
  69178. }
  69179. // Skeletons
  69180. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69181. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69182. var parsedSkeleton = parsedData.skeletons[index];
  69183. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69184. container.skeletons.push(skeleton);
  69185. log += (index === 0 ? "\n\tSkeletons:" : "");
  69186. log += "\n\t\t" + skeleton.toString(fullDetails);
  69187. }
  69188. }
  69189. // Geometries
  69190. var geometries = parsedData.geometries;
  69191. if (geometries !== undefined && geometries !== null) {
  69192. var addedGeometry = new Array();
  69193. // Boxes
  69194. var boxes = geometries.boxes;
  69195. if (boxes !== undefined && boxes !== null) {
  69196. for (index = 0, cache = boxes.length; index < cache; index++) {
  69197. var parsedBox = boxes[index];
  69198. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69199. }
  69200. }
  69201. // Spheres
  69202. var spheres = geometries.spheres;
  69203. if (spheres !== undefined && spheres !== null) {
  69204. for (index = 0, cache = spheres.length; index < cache; index++) {
  69205. var parsedSphere = spheres[index];
  69206. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69207. }
  69208. }
  69209. // Cylinders
  69210. var cylinders = geometries.cylinders;
  69211. if (cylinders !== undefined && cylinders !== null) {
  69212. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69213. var parsedCylinder = cylinders[index];
  69214. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69215. }
  69216. }
  69217. // Toruses
  69218. var toruses = geometries.toruses;
  69219. if (toruses !== undefined && toruses !== null) {
  69220. for (index = 0, cache = toruses.length; index < cache; index++) {
  69221. var parsedTorus = toruses[index];
  69222. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69223. }
  69224. }
  69225. // Grounds
  69226. var grounds = geometries.grounds;
  69227. if (grounds !== undefined && grounds !== null) {
  69228. for (index = 0, cache = grounds.length; index < cache; index++) {
  69229. var parsedGround = grounds[index];
  69230. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69231. }
  69232. }
  69233. // Planes
  69234. var planes = geometries.planes;
  69235. if (planes !== undefined && planes !== null) {
  69236. for (index = 0, cache = planes.length; index < cache; index++) {
  69237. var parsedPlane = planes[index];
  69238. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69239. }
  69240. }
  69241. // TorusKnots
  69242. var torusKnots = geometries.torusKnots;
  69243. if (torusKnots !== undefined && torusKnots !== null) {
  69244. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69245. var parsedTorusKnot = torusKnots[index];
  69246. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69247. }
  69248. }
  69249. // VertexData
  69250. var vertexData = geometries.vertexData;
  69251. if (vertexData !== undefined && vertexData !== null) {
  69252. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69253. var parsedVertexData = vertexData[index];
  69254. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69255. }
  69256. }
  69257. addedGeometry.forEach(function (g) {
  69258. if (g) {
  69259. container.geometries.push(g);
  69260. }
  69261. });
  69262. }
  69263. // Transform nodes
  69264. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69265. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69266. var parsedTransformNode = parsedData.transformNodes[index];
  69267. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69268. container.transformNodes.push(node);
  69269. }
  69270. }
  69271. // Meshes
  69272. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69273. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69274. var parsedMesh = parsedData.meshes[index];
  69275. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69276. container.meshes.push(mesh);
  69277. log += (index === 0 ? "\n\tMeshes:" : "");
  69278. log += "\n\t\t" + mesh.toString(fullDetails);
  69279. }
  69280. }
  69281. // Cameras
  69282. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69283. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69284. var parsedCamera = parsedData.cameras[index];
  69285. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69286. container.cameras.push(camera);
  69287. log += (index === 0 ? "\n\tCameras:" : "");
  69288. log += "\n\t\t" + camera.toString(fullDetails);
  69289. }
  69290. }
  69291. // Browsing all the graph to connect the dots
  69292. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69293. var camera = scene.cameras[index];
  69294. if (camera._waitingParentId) {
  69295. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69296. camera._waitingParentId = null;
  69297. }
  69298. }
  69299. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69300. var light_1 = scene.lights[index];
  69301. if (light_1 && light_1._waitingParentId) {
  69302. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69303. light_1._waitingParentId = null;
  69304. }
  69305. }
  69306. // Sounds
  69307. // TODO: add sound
  69308. var loadedSounds = [];
  69309. var loadedSound;
  69310. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69311. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69312. var parsedSound = parsedData.sounds[index];
  69313. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69314. if (!parsedSound.url)
  69315. parsedSound.url = parsedSound.name;
  69316. if (!loadedSounds[parsedSound.url]) {
  69317. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69318. loadedSounds[parsedSound.url] = loadedSound;
  69319. container.sounds.push(loadedSound);
  69320. }
  69321. else {
  69322. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69323. }
  69324. }
  69325. else {
  69326. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69327. }
  69328. }
  69329. }
  69330. loadedSounds = [];
  69331. // Connect parents & children and parse actions
  69332. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69333. var transformNode = scene.transformNodes[index];
  69334. if (transformNode._waitingParentId) {
  69335. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69336. transformNode._waitingParentId = null;
  69337. }
  69338. }
  69339. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69340. var mesh = scene.meshes[index];
  69341. if (mesh._waitingParentId) {
  69342. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69343. mesh._waitingParentId = null;
  69344. }
  69345. if (mesh._waitingActions) {
  69346. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69347. mesh._waitingActions = null;
  69348. }
  69349. }
  69350. // freeze world matrix application
  69351. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69352. var currentMesh = scene.meshes[index];
  69353. if (currentMesh._waitingFreezeWorldMatrix) {
  69354. currentMesh.freezeWorldMatrix();
  69355. currentMesh._waitingFreezeWorldMatrix = null;
  69356. }
  69357. else {
  69358. currentMesh.computeWorldMatrix(true);
  69359. }
  69360. }
  69361. // Shadows
  69362. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69363. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69364. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69365. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69366. // SG would be available on their associated lights
  69367. }
  69368. }
  69369. // Lights exclusions / inclusions
  69370. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69371. var light_2 = scene.lights[index];
  69372. // Excluded check
  69373. if (light_2._excludedMeshesIds.length > 0) {
  69374. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69375. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69376. if (excludedMesh) {
  69377. light_2.excludedMeshes.push(excludedMesh);
  69378. }
  69379. }
  69380. light_2._excludedMeshesIds = [];
  69381. }
  69382. // Included check
  69383. if (light_2._includedOnlyMeshesIds.length > 0) {
  69384. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69385. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69386. if (includedOnlyMesh) {
  69387. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69388. }
  69389. }
  69390. light_2._includedOnlyMeshesIds = [];
  69391. }
  69392. }
  69393. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69394. // Actions (scene)
  69395. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69396. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69397. }
  69398. if (!addToScene) {
  69399. container.removeAllFromScene();
  69400. }
  69401. }
  69402. catch (err) {
  69403. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69404. if (onError) {
  69405. onError(msg, err);
  69406. }
  69407. else {
  69408. BABYLON.Tools.Log(msg);
  69409. throw err;
  69410. }
  69411. }
  69412. finally {
  69413. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69414. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69415. }
  69416. }
  69417. return container;
  69418. };
  69419. BABYLON.SceneLoader.RegisterPlugin({
  69420. name: "babylon.js",
  69421. extensions: ".babylon",
  69422. canDirectLoad: function (data) {
  69423. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69424. return true;
  69425. }
  69426. return false;
  69427. },
  69428. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69429. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69430. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69431. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69432. // and avoid problems with multiple concurrent .babylon loads.
  69433. var log = "importMesh has failed JSON parse";
  69434. try {
  69435. var parsedData = JSON.parse(data);
  69436. log = "";
  69437. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69438. if (!meshesNames) {
  69439. meshesNames = null;
  69440. }
  69441. else if (!Array.isArray(meshesNames)) {
  69442. meshesNames = [meshesNames];
  69443. }
  69444. var hierarchyIds = new Array();
  69445. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69446. var loadedSkeletonsIds = [];
  69447. var loadedMaterialsIds = [];
  69448. var index;
  69449. var cache;
  69450. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69451. var parsedMesh = parsedData.meshes[index];
  69452. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69453. if (meshesNames !== null) {
  69454. // Remove found mesh name from list.
  69455. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69456. }
  69457. //Geometry?
  69458. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69459. //does the file contain geometries?
  69460. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69461. //find the correct geometry and add it to the scene
  69462. var found = false;
  69463. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69464. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69465. return;
  69466. }
  69467. else {
  69468. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69469. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69470. switch (geometryType) {
  69471. case "boxes":
  69472. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69473. break;
  69474. case "spheres":
  69475. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69476. break;
  69477. case "cylinders":
  69478. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69479. break;
  69480. case "toruses":
  69481. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69482. break;
  69483. case "grounds":
  69484. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69485. break;
  69486. case "planes":
  69487. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69488. break;
  69489. case "torusKnots":
  69490. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69491. break;
  69492. case "vertexData":
  69493. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69494. break;
  69495. }
  69496. found = true;
  69497. }
  69498. });
  69499. }
  69500. });
  69501. if (found === false) {
  69502. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69503. }
  69504. }
  69505. }
  69506. // Material ?
  69507. if (parsedMesh.materialId) {
  69508. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69509. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69510. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69511. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69512. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69513. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69514. var subMatId = parsedMultiMaterial.materials[matIndex];
  69515. loadedMaterialsIds.push(subMatId);
  69516. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69517. if (mat) {
  69518. log += "\n\tMaterial " + mat.toString(fullDetails);
  69519. }
  69520. }
  69521. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69522. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69523. if (mmat) {
  69524. materialFound = true;
  69525. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69526. }
  69527. break;
  69528. }
  69529. }
  69530. }
  69531. if (materialFound === false) {
  69532. loadedMaterialsIds.push(parsedMesh.materialId);
  69533. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69534. if (!mat) {
  69535. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69536. }
  69537. else {
  69538. log += "\n\tMaterial " + mat.toString(fullDetails);
  69539. }
  69540. }
  69541. }
  69542. // Skeleton ?
  69543. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69544. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69545. if (skeletonAlreadyLoaded === false) {
  69546. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69547. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69548. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69549. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69550. skeletons.push(skeleton);
  69551. loadedSkeletonsIds.push(parsedSkeleton.id);
  69552. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69553. }
  69554. }
  69555. }
  69556. }
  69557. // Morph targets ?
  69558. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69559. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69560. var managerData = _a[_i];
  69561. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69562. }
  69563. }
  69564. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69565. meshes.push(mesh);
  69566. log += "\n\tMesh " + mesh.toString(fullDetails);
  69567. }
  69568. }
  69569. // Connecting parents
  69570. var currentMesh;
  69571. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69572. currentMesh = scene.meshes[index];
  69573. if (currentMesh._waitingParentId) {
  69574. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69575. currentMesh._waitingParentId = null;
  69576. }
  69577. }
  69578. // freeze and compute world matrix application
  69579. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69580. currentMesh = scene.meshes[index];
  69581. if (currentMesh._waitingFreezeWorldMatrix) {
  69582. currentMesh.freezeWorldMatrix();
  69583. currentMesh._waitingFreezeWorldMatrix = null;
  69584. }
  69585. else {
  69586. currentMesh.computeWorldMatrix(true);
  69587. }
  69588. }
  69589. }
  69590. // Particles
  69591. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69592. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69593. if (parser) {
  69594. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69595. var parsedParticleSystem = parsedData.particleSystems[index];
  69596. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69597. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69598. }
  69599. }
  69600. }
  69601. }
  69602. return true;
  69603. }
  69604. catch (err) {
  69605. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69606. if (onError) {
  69607. onError(msg, err);
  69608. }
  69609. else {
  69610. BABYLON.Tools.Log(msg);
  69611. throw err;
  69612. }
  69613. }
  69614. finally {
  69615. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69616. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69617. }
  69618. }
  69619. return false;
  69620. },
  69621. load: function (scene, data, rootUrl, onError) {
  69622. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69623. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69624. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69625. // and avoid problems with multiple concurrent .babylon loads.
  69626. var log = "importScene has failed JSON parse";
  69627. try {
  69628. var parsedData = JSON.parse(data);
  69629. log = "";
  69630. // Scene
  69631. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  69632. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  69633. }
  69634. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  69635. scene.autoClear = parsedData.autoClear;
  69636. }
  69637. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  69638. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  69639. }
  69640. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  69641. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  69642. }
  69643. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  69644. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  69645. }
  69646. // Fog
  69647. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  69648. scene.fogMode = parsedData.fogMode;
  69649. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  69650. scene.fogStart = parsedData.fogStart;
  69651. scene.fogEnd = parsedData.fogEnd;
  69652. scene.fogDensity = parsedData.fogDensity;
  69653. log += "\tFog mode for scene: ";
  69654. switch (scene.fogMode) {
  69655. // getters not compiling, so using hardcoded
  69656. case 1:
  69657. log += "exp\n";
  69658. break;
  69659. case 2:
  69660. log += "exp2\n";
  69661. break;
  69662. case 3:
  69663. log += "linear\n";
  69664. break;
  69665. }
  69666. }
  69667. //Physics
  69668. if (parsedData.physicsEnabled) {
  69669. var physicsPlugin;
  69670. if (parsedData.physicsEngine === "cannon") {
  69671. physicsPlugin = new BABYLON.CannonJSPlugin();
  69672. }
  69673. else if (parsedData.physicsEngine === "oimo") {
  69674. physicsPlugin = new BABYLON.OimoJSPlugin();
  69675. }
  69676. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  69677. //else - default engine, which is currently oimo
  69678. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  69679. scene.enablePhysics(physicsGravity, physicsPlugin);
  69680. }
  69681. // Metadata
  69682. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  69683. scene.metadata = parsedData.metadata;
  69684. }
  69685. //collisions, if defined. otherwise, default is true
  69686. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  69687. scene.collisionsEnabled = parsedData.collisionsEnabled;
  69688. }
  69689. scene.workerCollisions = !!parsedData.workerCollisions;
  69690. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  69691. if (!container) {
  69692. return false;
  69693. }
  69694. if (parsedData.autoAnimate) {
  69695. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  69696. }
  69697. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  69698. scene.setActiveCameraByID(parsedData.activeCameraID);
  69699. }
  69700. // Environment texture
  69701. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  69702. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  69703. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  69704. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  69705. if (parsedData.environmentTextureRotationY) {
  69706. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  69707. }
  69708. scene.environmentTexture = hdrTexture;
  69709. }
  69710. else {
  69711. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  69712. if (parsedData.environmentTextureRotationY) {
  69713. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  69714. }
  69715. scene.environmentTexture = cubeTexture;
  69716. }
  69717. if (parsedData.createDefaultSkybox === true) {
  69718. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  69719. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  69720. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  69721. }
  69722. }
  69723. // Finish
  69724. return true;
  69725. }
  69726. catch (err) {
  69727. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  69728. if (onError) {
  69729. onError(msg, err);
  69730. }
  69731. else {
  69732. BABYLON.Tools.Log(msg);
  69733. throw err;
  69734. }
  69735. }
  69736. finally {
  69737. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69738. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69739. }
  69740. }
  69741. return false;
  69742. },
  69743. loadAssetContainer: function (scene, data, rootUrl, onError) {
  69744. var container = loadAssetContainer(scene, data, rootUrl, onError);
  69745. return container;
  69746. }
  69747. });
  69748. })(BABYLON || (BABYLON = {}));
  69749. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  69750. var BABYLON;
  69751. (function (BABYLON) {
  69752. var FilesInput = /** @class */ (function () {
  69753. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  69754. this.onProcessFileCallback = function () { return true; };
  69755. this._engine = engine;
  69756. this._currentScene = scene;
  69757. this._sceneLoadedCallback = sceneLoadedCallback;
  69758. this._progressCallback = progressCallback;
  69759. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  69760. this._textureLoadingCallback = textureLoadingCallback;
  69761. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  69762. this._onReloadCallback = onReloadCallback;
  69763. this._errorCallback = errorCallback;
  69764. }
  69765. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  69766. var _this = this;
  69767. if (elementToMonitor) {
  69768. this._elementToMonitor = elementToMonitor;
  69769. this._dragEnterHandler = function (e) { _this.drag(e); };
  69770. this._dragOverHandler = function (e) { _this.drag(e); };
  69771. this._dropHandler = function (e) { _this.drop(e); };
  69772. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  69773. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  69774. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  69775. }
  69776. };
  69777. FilesInput.prototype.dispose = function () {
  69778. if (!this._elementToMonitor) {
  69779. return;
  69780. }
  69781. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  69782. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  69783. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  69784. };
  69785. FilesInput.prototype.renderFunction = function () {
  69786. if (this._additionalRenderLoopLogicCallback) {
  69787. this._additionalRenderLoopLogicCallback();
  69788. }
  69789. if (this._currentScene) {
  69790. if (this._textureLoadingCallback) {
  69791. var remaining = this._currentScene.getWaitingItemsCount();
  69792. if (remaining > 0) {
  69793. this._textureLoadingCallback(remaining);
  69794. }
  69795. }
  69796. this._currentScene.render();
  69797. }
  69798. };
  69799. FilesInput.prototype.drag = function (e) {
  69800. e.stopPropagation();
  69801. e.preventDefault();
  69802. };
  69803. FilesInput.prototype.drop = function (eventDrop) {
  69804. eventDrop.stopPropagation();
  69805. eventDrop.preventDefault();
  69806. this.loadFiles(eventDrop);
  69807. };
  69808. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69809. var _this = this;
  69810. var reader = folder.createReader();
  69811. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69812. reader.readEntries(function (entries) {
  69813. remaining.count += entries.length;
  69814. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69815. var entry = entries_1[_i];
  69816. if (entry.isFile) {
  69817. entry.file(function (file) {
  69818. file.correctName = relativePath + file.name;
  69819. files.push(file);
  69820. if (--remaining.count === 0) {
  69821. callback();
  69822. }
  69823. });
  69824. }
  69825. else if (entry.isDirectory) {
  69826. _this._traverseFolder(entry, files, remaining, callback);
  69827. }
  69828. }
  69829. if (--remaining.count) {
  69830. callback();
  69831. }
  69832. });
  69833. };
  69834. FilesInput.prototype._processFiles = function (files) {
  69835. for (var i = 0; i < files.length; i++) {
  69836. var name = files[i].correctName.toLowerCase();
  69837. var extension = name.split('.').pop();
  69838. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69839. continue;
  69840. }
  69841. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69842. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69843. this._sceneFileToLoad = files[i];
  69844. }
  69845. else {
  69846. FilesInput.FilesToLoad[name] = files[i];
  69847. }
  69848. }
  69849. };
  69850. FilesInput.prototype.loadFiles = function (event) {
  69851. var _this = this;
  69852. if (this._startingProcessingFilesCallback)
  69853. this._startingProcessingFilesCallback();
  69854. // Handling data transfer via drag'n'drop
  69855. if (event && event.dataTransfer && event.dataTransfer.files) {
  69856. this._filesToLoad = event.dataTransfer.files;
  69857. }
  69858. // Handling files from input files
  69859. if (event && event.target && event.target.files) {
  69860. this._filesToLoad = event.target.files;
  69861. }
  69862. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69863. var files_1 = new Array();
  69864. var folders = [];
  69865. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69866. for (var i = 0; i < this._filesToLoad.length; i++) {
  69867. var fileToLoad = this._filesToLoad[i];
  69868. var name_1 = fileToLoad.name.toLowerCase();
  69869. var entry = void 0;
  69870. fileToLoad.correctName = name_1;
  69871. if (items) {
  69872. var item = items[i];
  69873. if (item.getAsEntry) {
  69874. entry = item.getAsEntry();
  69875. }
  69876. else if (item.webkitGetAsEntry) {
  69877. entry = item.webkitGetAsEntry();
  69878. }
  69879. }
  69880. if (!entry) {
  69881. files_1.push(fileToLoad);
  69882. }
  69883. else {
  69884. if (entry.isDirectory) {
  69885. folders.push(entry);
  69886. }
  69887. else {
  69888. files_1.push(fileToLoad);
  69889. }
  69890. }
  69891. }
  69892. if (folders.length === 0) {
  69893. this._processFiles(files_1);
  69894. this._processReload();
  69895. }
  69896. else {
  69897. var remaining = { count: folders.length };
  69898. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69899. var folder = folders_1[_i];
  69900. this._traverseFolder(folder, files_1, remaining, function () {
  69901. _this._processFiles(files_1);
  69902. if (remaining.count === 0) {
  69903. _this._processReload();
  69904. }
  69905. });
  69906. }
  69907. }
  69908. }
  69909. };
  69910. FilesInput.prototype._processReload = function () {
  69911. if (this._onReloadCallback) {
  69912. this._onReloadCallback(this._sceneFileToLoad);
  69913. }
  69914. else {
  69915. this.reload();
  69916. }
  69917. };
  69918. FilesInput.prototype.reload = function () {
  69919. var _this = this;
  69920. // If a scene file has been provided
  69921. if (this._sceneFileToLoad) {
  69922. if (this._currentScene) {
  69923. if (BABYLON.Tools.errorsCount > 0) {
  69924. BABYLON.Tools.ClearLogCache();
  69925. }
  69926. this._engine.stopRenderLoop();
  69927. }
  69928. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69929. if (_this._progressCallback) {
  69930. _this._progressCallback(progress);
  69931. }
  69932. }).then(function (scene) {
  69933. if (_this._currentScene) {
  69934. _this._currentScene.dispose();
  69935. }
  69936. _this._currentScene = scene;
  69937. if (_this._sceneLoadedCallback) {
  69938. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69939. }
  69940. // Wait for textures and shaders to be ready
  69941. _this._currentScene.executeWhenReady(function () {
  69942. _this._engine.runRenderLoop(function () {
  69943. _this.renderFunction();
  69944. });
  69945. });
  69946. }).catch(function (error) {
  69947. if (_this._errorCallback) {
  69948. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69949. }
  69950. });
  69951. }
  69952. else {
  69953. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69954. }
  69955. };
  69956. FilesInput.FilesToLoad = {};
  69957. return FilesInput;
  69958. }());
  69959. BABYLON.FilesInput = FilesInput;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.filesInput.js.map
  69962. var BABYLON;
  69963. (function (BABYLON) {
  69964. var Tags = /** @class */ (function () {
  69965. function Tags() {
  69966. }
  69967. Tags.EnableFor = function (obj) {
  69968. obj._tags = obj._tags || {};
  69969. obj.hasTags = function () {
  69970. return Tags.HasTags(obj);
  69971. };
  69972. obj.addTags = function (tagsString) {
  69973. return Tags.AddTagsTo(obj, tagsString);
  69974. };
  69975. obj.removeTags = function (tagsString) {
  69976. return Tags.RemoveTagsFrom(obj, tagsString);
  69977. };
  69978. obj.matchesTagsQuery = function (tagsQuery) {
  69979. return Tags.MatchesQuery(obj, tagsQuery);
  69980. };
  69981. };
  69982. Tags.DisableFor = function (obj) {
  69983. delete obj._tags;
  69984. delete obj.hasTags;
  69985. delete obj.addTags;
  69986. delete obj.removeTags;
  69987. delete obj.matchesTagsQuery;
  69988. };
  69989. Tags.HasTags = function (obj) {
  69990. if (!obj._tags) {
  69991. return false;
  69992. }
  69993. return !BABYLON.Tools.IsEmpty(obj._tags);
  69994. };
  69995. Tags.GetTags = function (obj, asString) {
  69996. if (asString === void 0) { asString = true; }
  69997. if (!obj._tags) {
  69998. return null;
  69999. }
  70000. if (asString) {
  70001. var tagsArray = [];
  70002. for (var tag in obj._tags) {
  70003. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70004. tagsArray.push(tag);
  70005. }
  70006. }
  70007. return tagsArray.join(" ");
  70008. }
  70009. else {
  70010. return obj._tags;
  70011. }
  70012. };
  70013. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70014. // a tag cannot start with '||', '&&', and '!'
  70015. // it cannot contain whitespaces
  70016. Tags.AddTagsTo = function (obj, tagsString) {
  70017. if (!tagsString) {
  70018. return;
  70019. }
  70020. if (typeof tagsString !== "string") {
  70021. return;
  70022. }
  70023. var tags = tagsString.split(" ");
  70024. tags.forEach(function (tag, index, array) {
  70025. Tags._AddTagTo(obj, tag);
  70026. });
  70027. };
  70028. Tags._AddTagTo = function (obj, tag) {
  70029. tag = tag.trim();
  70030. if (tag === "" || tag === "true" || tag === "false") {
  70031. return;
  70032. }
  70033. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70034. return;
  70035. }
  70036. Tags.EnableFor(obj);
  70037. obj._tags[tag] = true;
  70038. };
  70039. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70040. if (!Tags.HasTags(obj)) {
  70041. return;
  70042. }
  70043. var tags = tagsString.split(" ");
  70044. for (var t in tags) {
  70045. Tags._RemoveTagFrom(obj, tags[t]);
  70046. }
  70047. };
  70048. Tags._RemoveTagFrom = function (obj, tag) {
  70049. delete obj._tags[tag];
  70050. };
  70051. Tags.MatchesQuery = function (obj, tagsQuery) {
  70052. if (tagsQuery === undefined) {
  70053. return true;
  70054. }
  70055. if (tagsQuery === "") {
  70056. return Tags.HasTags(obj);
  70057. }
  70058. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70059. };
  70060. return Tags;
  70061. }());
  70062. BABYLON.Tags = Tags;
  70063. })(BABYLON || (BABYLON = {}));
  70064. //# sourceMappingURL=babylon.tags.js.map
  70065. var BABYLON;
  70066. (function (BABYLON) {
  70067. /**
  70068. * Class used to evalaute queries containing `and` and `or` operators
  70069. */
  70070. var AndOrNotEvaluator = /** @class */ (function () {
  70071. function AndOrNotEvaluator() {
  70072. }
  70073. /**
  70074. * Evaluate a query
  70075. * @param query defines the query to evaluate
  70076. * @param evaluateCallback defines the callback used to filter result
  70077. * @returns true if the query matches
  70078. */
  70079. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70080. if (!query.match(/\([^\(\)]*\)/g)) {
  70081. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70082. }
  70083. else {
  70084. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70085. // remove parenthesis
  70086. r = r.slice(1, r.length - 1);
  70087. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70088. });
  70089. }
  70090. if (query === "true") {
  70091. return true;
  70092. }
  70093. if (query === "false") {
  70094. return false;
  70095. }
  70096. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70097. };
  70098. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70099. evaluateCallback = evaluateCallback || (function (r) {
  70100. return r === "true" ? true : false;
  70101. });
  70102. var result;
  70103. var or = parenthesisContent.split("||");
  70104. for (var i in or) {
  70105. if (or.hasOwnProperty(i)) {
  70106. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70107. var and = ori.split("&&");
  70108. if (and.length > 1) {
  70109. for (var j = 0; j < and.length; ++j) {
  70110. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70111. if (andj !== "true" && andj !== "false") {
  70112. if (andj[0] === "!") {
  70113. result = !evaluateCallback(andj.substring(1));
  70114. }
  70115. else {
  70116. result = evaluateCallback(andj);
  70117. }
  70118. }
  70119. else {
  70120. result = andj === "true" ? true : false;
  70121. }
  70122. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70123. ori = "false";
  70124. break;
  70125. }
  70126. }
  70127. }
  70128. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70129. result = true;
  70130. break;
  70131. }
  70132. // result equals false (or undefined)
  70133. if (ori !== "true" && ori !== "false") {
  70134. if (ori[0] === "!") {
  70135. result = !evaluateCallback(ori.substring(1));
  70136. }
  70137. else {
  70138. result = evaluateCallback(ori);
  70139. }
  70140. }
  70141. else {
  70142. result = ori === "true" ? true : false;
  70143. }
  70144. }
  70145. }
  70146. // the whole parenthesis scope is replaced by 'true' or 'false'
  70147. return result ? "true" : "false";
  70148. };
  70149. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70150. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70151. // remove whitespaces
  70152. r = r.replace(/[\s]/g, function () { return ""; });
  70153. return r.length % 2 ? "!" : "";
  70154. });
  70155. booleanString = booleanString.trim();
  70156. if (booleanString === "!true") {
  70157. booleanString = "false";
  70158. }
  70159. else if (booleanString === "!false") {
  70160. booleanString = "true";
  70161. }
  70162. return booleanString;
  70163. };
  70164. return AndOrNotEvaluator;
  70165. }());
  70166. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70167. })(BABYLON || (BABYLON = {}));
  70168. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70169. var BABYLON;
  70170. (function (BABYLON) {
  70171. /**
  70172. * Class used to enable access to IndexedDB
  70173. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70174. */
  70175. var Database = /** @class */ (function () {
  70176. /**
  70177. * Creates a new Database
  70178. * @param urlToScene defines the url to load the scene
  70179. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70180. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70181. */
  70182. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70183. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70184. var _this = this;
  70185. // Handling various flavors of prefixed version of IndexedDB
  70186. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70187. this.callbackManifestChecked = callbackManifestChecked;
  70188. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70189. this.db = null;
  70190. this._enableSceneOffline = false;
  70191. this._enableTexturesOffline = false;
  70192. this.manifestVersionFound = 0;
  70193. this.mustUpdateRessources = false;
  70194. this.hasReachedQuota = false;
  70195. if (!Database.IDBStorageEnabled) {
  70196. this.callbackManifestChecked(true);
  70197. }
  70198. else {
  70199. if (disableManifestCheck) {
  70200. this._enableSceneOffline = true;
  70201. this._enableTexturesOffline = true;
  70202. this.manifestVersionFound = 1;
  70203. BABYLON.Tools.SetImmediate(function () {
  70204. _this.callbackManifestChecked(true);
  70205. });
  70206. }
  70207. else {
  70208. this._checkManifestFile();
  70209. }
  70210. }
  70211. }
  70212. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70213. /**
  70214. * Gets a boolean indicating if scene must be saved in the database
  70215. */
  70216. get: function () {
  70217. return this._enableSceneOffline;
  70218. },
  70219. enumerable: true,
  70220. configurable: true
  70221. });
  70222. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70223. /**
  70224. * Gets a boolean indicating if textures must be saved in the database
  70225. */
  70226. get: function () {
  70227. return this._enableTexturesOffline;
  70228. },
  70229. enumerable: true,
  70230. configurable: true
  70231. });
  70232. Database.prototype._checkManifestFile = function () {
  70233. var _this = this;
  70234. var noManifestFile = function () {
  70235. _this._enableSceneOffline = false;
  70236. _this._enableTexturesOffline = false;
  70237. _this.callbackManifestChecked(false);
  70238. };
  70239. var timeStampUsed = false;
  70240. var manifestURL = this.currentSceneUrl + ".manifest";
  70241. var xhr = new XMLHttpRequest();
  70242. if (navigator.onLine) {
  70243. // Adding a timestamp to by-pass browsers' cache
  70244. timeStampUsed = true;
  70245. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70246. }
  70247. xhr.open("GET", manifestURL, true);
  70248. xhr.addEventListener("load", function () {
  70249. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70250. try {
  70251. var manifestFile = JSON.parse(xhr.response);
  70252. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70253. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70254. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70255. _this.manifestVersionFound = manifestFile.version;
  70256. }
  70257. if (_this.callbackManifestChecked) {
  70258. _this.callbackManifestChecked(true);
  70259. }
  70260. }
  70261. catch (ex) {
  70262. noManifestFile();
  70263. }
  70264. }
  70265. else {
  70266. noManifestFile();
  70267. }
  70268. }, false);
  70269. xhr.addEventListener("error", function (event) {
  70270. if (timeStampUsed) {
  70271. timeStampUsed = false;
  70272. // Let's retry without the timeStamp
  70273. // It could fail when coupled with HTML5 Offline API
  70274. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70275. xhr.open("GET", retryManifestURL, true);
  70276. xhr.send();
  70277. }
  70278. else {
  70279. noManifestFile();
  70280. }
  70281. }, false);
  70282. try {
  70283. xhr.send();
  70284. }
  70285. catch (ex) {
  70286. BABYLON.Tools.Error("Error on XHR send request.");
  70287. this.callbackManifestChecked(false);
  70288. }
  70289. };
  70290. /**
  70291. * Open the database and make it available
  70292. * @param successCallback defines the callback to call on success
  70293. * @param errorCallback defines the callback to call on error
  70294. */
  70295. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70296. var _this = this;
  70297. var handleError = function () {
  70298. _this.isSupported = false;
  70299. if (errorCallback)
  70300. errorCallback();
  70301. };
  70302. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70303. // Your browser doesn't support IndexedDB
  70304. this.isSupported = false;
  70305. if (errorCallback)
  70306. errorCallback();
  70307. }
  70308. else {
  70309. // If the DB hasn't been opened or created yet
  70310. if (!this.db) {
  70311. this.hasReachedQuota = false;
  70312. this.isSupported = true;
  70313. var request = this.idbFactory.open("babylonjs", 1);
  70314. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70315. request.onerror = function (event) {
  70316. handleError();
  70317. };
  70318. // executes when a version change transaction cannot complete due to other active transactions
  70319. request.onblocked = function (event) {
  70320. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70321. handleError();
  70322. };
  70323. // DB has been opened successfully
  70324. request.onsuccess = function (event) {
  70325. _this.db = request.result;
  70326. successCallback();
  70327. };
  70328. // Initialization of the DB. Creating Scenes & Textures stores
  70329. request.onupgradeneeded = function (event) {
  70330. _this.db = (event.target).result;
  70331. if (_this.db) {
  70332. try {
  70333. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70334. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70335. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70336. }
  70337. catch (ex) {
  70338. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70339. handleError();
  70340. }
  70341. }
  70342. };
  70343. }
  70344. // DB has already been created and opened
  70345. else {
  70346. if (successCallback)
  70347. successCallback();
  70348. }
  70349. }
  70350. };
  70351. /**
  70352. * Loads an image from the database
  70353. * @param url defines the url to load from
  70354. * @param image defines the target DOM image
  70355. */
  70356. Database.prototype.loadImageFromDB = function (url, image) {
  70357. var _this = this;
  70358. var completeURL = Database._ReturnFullUrlLocation(url);
  70359. var saveAndLoadImage = function () {
  70360. if (!_this.hasReachedQuota && _this.db !== null) {
  70361. // the texture is not yet in the DB, let's try to save it
  70362. _this._saveImageIntoDBAsync(completeURL, image);
  70363. }
  70364. // If the texture is not in the DB and we've reached the DB quota limit
  70365. // let's load it directly from the web
  70366. else {
  70367. image.src = url;
  70368. }
  70369. };
  70370. if (!this.mustUpdateRessources) {
  70371. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70372. }
  70373. // First time we're download the images or update requested in the manifest file by a version change
  70374. else {
  70375. saveAndLoadImage();
  70376. }
  70377. };
  70378. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70379. if (this.isSupported && this.db !== null) {
  70380. var texture;
  70381. var transaction = this.db.transaction(["textures"]);
  70382. transaction.onabort = function (event) {
  70383. image.src = url;
  70384. };
  70385. transaction.oncomplete = function (event) {
  70386. var blobTextureURL;
  70387. if (texture) {
  70388. var URL = window.URL || window.webkitURL;
  70389. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70390. image.onerror = function () {
  70391. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70392. image.src = url;
  70393. };
  70394. image.src = blobTextureURL;
  70395. }
  70396. else {
  70397. notInDBCallback();
  70398. }
  70399. };
  70400. var getRequest = transaction.objectStore("textures").get(url);
  70401. getRequest.onsuccess = function (event) {
  70402. texture = (event.target).result;
  70403. };
  70404. getRequest.onerror = function (event) {
  70405. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70406. image.src = url;
  70407. };
  70408. }
  70409. else {
  70410. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70411. image.src = url;
  70412. }
  70413. };
  70414. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70415. var _this = this;
  70416. if (this.isSupported) {
  70417. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70418. var generateBlobUrl = function () {
  70419. var blobTextureURL;
  70420. if (blob) {
  70421. var URL = window.URL || window.webkitURL;
  70422. try {
  70423. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70424. }
  70425. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70426. catch (ex) {
  70427. blobTextureURL = URL.createObjectURL(blob);
  70428. }
  70429. }
  70430. if (blobTextureURL) {
  70431. image.src = blobTextureURL;
  70432. }
  70433. };
  70434. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70435. var xhr = new XMLHttpRequest(), blob;
  70436. xhr.open("GET", url, true);
  70437. xhr.responseType = "blob";
  70438. xhr.addEventListener("load", function () {
  70439. if (xhr.status === 200 && _this.db) {
  70440. // Blob as response (XHR2)
  70441. blob = xhr.response;
  70442. var transaction = _this.db.transaction(["textures"], "readwrite");
  70443. // the transaction could abort because of a QuotaExceededError error
  70444. transaction.onabort = function (event) {
  70445. try {
  70446. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70447. var srcElement = (event.srcElement || event.target);
  70448. var error = srcElement.error;
  70449. if (error && error.name === "QuotaExceededError") {
  70450. _this.hasReachedQuota = true;
  70451. }
  70452. }
  70453. catch (ex) { }
  70454. generateBlobUrl();
  70455. };
  70456. transaction.oncomplete = function (event) {
  70457. generateBlobUrl();
  70458. };
  70459. var newTexture = { textureUrl: url, data: blob };
  70460. try {
  70461. // Put the blob into the dabase
  70462. var addRequest = transaction.objectStore("textures").put(newTexture);
  70463. addRequest.onsuccess = function (event) {
  70464. };
  70465. addRequest.onerror = function (event) {
  70466. generateBlobUrl();
  70467. };
  70468. }
  70469. catch (ex) {
  70470. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70471. if (ex.code === 25) {
  70472. Database.IsUASupportingBlobStorage = false;
  70473. }
  70474. image.src = url;
  70475. }
  70476. }
  70477. else {
  70478. image.src = url;
  70479. }
  70480. }, false);
  70481. xhr.addEventListener("error", function (event) {
  70482. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70483. image.src = url;
  70484. }, false);
  70485. xhr.send();
  70486. }
  70487. else {
  70488. image.src = url;
  70489. }
  70490. }
  70491. else {
  70492. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70493. image.src = url;
  70494. }
  70495. };
  70496. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70497. var _this = this;
  70498. var updateVersion = function () {
  70499. // the version is not yet in the DB or we need to update it
  70500. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70501. };
  70502. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70503. };
  70504. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70505. var _this = this;
  70506. if (this.isSupported && this.db) {
  70507. var version;
  70508. try {
  70509. var transaction = this.db.transaction(["versions"]);
  70510. transaction.oncomplete = function (event) {
  70511. if (version) {
  70512. // If the version in the JSON file is different from the version in DB
  70513. if (_this.manifestVersionFound !== version.data) {
  70514. _this.mustUpdateRessources = true;
  70515. updateInDBCallback();
  70516. }
  70517. else {
  70518. callback(version.data);
  70519. }
  70520. }
  70521. // version was not found in DB
  70522. else {
  70523. _this.mustUpdateRessources = true;
  70524. updateInDBCallback();
  70525. }
  70526. };
  70527. transaction.onabort = function (event) {
  70528. callback(-1);
  70529. };
  70530. var getRequest = transaction.objectStore("versions").get(url);
  70531. getRequest.onsuccess = function (event) {
  70532. version = (event.target).result;
  70533. };
  70534. getRequest.onerror = function (event) {
  70535. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70536. callback(-1);
  70537. };
  70538. }
  70539. catch (ex) {
  70540. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70541. callback(-1);
  70542. }
  70543. }
  70544. else {
  70545. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70546. callback(-1);
  70547. }
  70548. };
  70549. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70550. var _this = this;
  70551. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70552. try {
  70553. // Open a transaction to the database
  70554. var transaction = this.db.transaction(["versions"], "readwrite");
  70555. // the transaction could abort because of a QuotaExceededError error
  70556. transaction.onabort = function (event) {
  70557. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70558. var error = event.srcElement['error'];
  70559. if (error && error.name === "QuotaExceededError") {
  70560. _this.hasReachedQuota = true;
  70561. }
  70562. }
  70563. catch (ex) { }
  70564. callback(-1);
  70565. };
  70566. transaction.oncomplete = function (event) {
  70567. callback(_this.manifestVersionFound);
  70568. };
  70569. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70570. // Put the scene into the database
  70571. var addRequest = transaction.objectStore("versions").put(newVersion);
  70572. addRequest.onsuccess = function (event) {
  70573. };
  70574. addRequest.onerror = function (event) {
  70575. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70576. };
  70577. }
  70578. catch (ex) {
  70579. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70580. callback(-1);
  70581. }
  70582. }
  70583. else {
  70584. callback(-1);
  70585. }
  70586. };
  70587. /**
  70588. * Loads a file from database
  70589. * @param url defines the URL to load from
  70590. * @param sceneLoaded defines a callback to call on success
  70591. * @param progressCallBack defines a callback to call when progress changed
  70592. * @param errorCallback defines a callback to call on error
  70593. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70594. */
  70595. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70596. var _this = this;
  70597. var completeUrl = Database._ReturnFullUrlLocation(url);
  70598. var saveAndLoadFile = function () {
  70599. // the scene is not yet in the DB, let's try to save it
  70600. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70601. };
  70602. this._checkVersionFromDB(completeUrl, function (version) {
  70603. if (version !== -1) {
  70604. if (!_this.mustUpdateRessources) {
  70605. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70606. }
  70607. else {
  70608. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70609. }
  70610. }
  70611. else {
  70612. if (errorCallback) {
  70613. errorCallback();
  70614. }
  70615. }
  70616. });
  70617. };
  70618. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70619. if (this.isSupported && this.db) {
  70620. var targetStore;
  70621. if (url.indexOf(".babylon") !== -1) {
  70622. targetStore = "scenes";
  70623. }
  70624. else {
  70625. targetStore = "textures";
  70626. }
  70627. var file;
  70628. var transaction = this.db.transaction([targetStore]);
  70629. transaction.oncomplete = function (event) {
  70630. if (file) {
  70631. callback(file.data);
  70632. }
  70633. // file was not found in DB
  70634. else {
  70635. notInDBCallback();
  70636. }
  70637. };
  70638. transaction.onabort = function (event) {
  70639. notInDBCallback();
  70640. };
  70641. var getRequest = transaction.objectStore(targetStore).get(url);
  70642. getRequest.onsuccess = function (event) {
  70643. file = (event.target).result;
  70644. };
  70645. getRequest.onerror = function (event) {
  70646. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70647. notInDBCallback();
  70648. };
  70649. }
  70650. else {
  70651. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70652. callback();
  70653. }
  70654. };
  70655. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  70656. var _this = this;
  70657. if (this.isSupported) {
  70658. var targetStore;
  70659. if (url.indexOf(".babylon") !== -1) {
  70660. targetStore = "scenes";
  70661. }
  70662. else {
  70663. targetStore = "textures";
  70664. }
  70665. // Create XHR
  70666. var xhr = new XMLHttpRequest();
  70667. var fileData;
  70668. xhr.open("GET", url, true);
  70669. if (useArrayBuffer) {
  70670. xhr.responseType = "arraybuffer";
  70671. }
  70672. if (progressCallback) {
  70673. xhr.onprogress = progressCallback;
  70674. }
  70675. xhr.addEventListener("load", function () {
  70676. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  70677. // Blob as response (XHR2)
  70678. //fileData = xhr.responseText;
  70679. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70680. if (!_this.hasReachedQuota && _this.db) {
  70681. // Open a transaction to the database
  70682. var transaction = _this.db.transaction([targetStore], "readwrite");
  70683. // the transaction could abort because of a QuotaExceededError error
  70684. transaction.onabort = function (event) {
  70685. try {
  70686. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70687. var error = event.srcElement['error'];
  70688. if (error && error.name === "QuotaExceededError") {
  70689. _this.hasReachedQuota = true;
  70690. }
  70691. }
  70692. catch (ex) { }
  70693. callback(fileData);
  70694. };
  70695. transaction.oncomplete = function (event) {
  70696. callback(fileData);
  70697. };
  70698. var newFile;
  70699. if (targetStore === "scenes") {
  70700. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70701. }
  70702. else {
  70703. newFile = { textureUrl: url, data: fileData };
  70704. }
  70705. try {
  70706. // Put the scene into the database
  70707. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70708. addRequest.onsuccess = function (event) {
  70709. };
  70710. addRequest.onerror = function (event) {
  70711. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70712. };
  70713. }
  70714. catch (ex) {
  70715. callback(fileData);
  70716. }
  70717. }
  70718. else {
  70719. callback(fileData);
  70720. }
  70721. }
  70722. else {
  70723. if (xhr.status >= 400 && errorCallback) {
  70724. errorCallback(xhr);
  70725. }
  70726. else {
  70727. callback();
  70728. }
  70729. }
  70730. }, false);
  70731. xhr.addEventListener("error", function (event) {
  70732. BABYLON.Tools.Error("error on XHR request.");
  70733. callback();
  70734. }, false);
  70735. xhr.send();
  70736. }
  70737. else {
  70738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70739. callback();
  70740. }
  70741. };
  70742. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70743. Database.IsUASupportingBlobStorage = true;
  70744. /** Gets a boolean indicating if Database storate is enabled */
  70745. Database.IDBStorageEnabled = true;
  70746. Database._ParseURL = function (url) {
  70747. var a = document.createElement('a');
  70748. a.href = url;
  70749. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70750. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70751. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70752. return absLocation;
  70753. };
  70754. Database._ReturnFullUrlLocation = function (url) {
  70755. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70756. return (Database._ParseURL(window.location.href) + url);
  70757. }
  70758. else {
  70759. return url;
  70760. }
  70761. };
  70762. return Database;
  70763. }());
  70764. BABYLON.Database = Database;
  70765. })(BABYLON || (BABYLON = {}));
  70766. //# sourceMappingURL=babylon.database.js.map
  70767. var BABYLON;
  70768. (function (BABYLON) {
  70769. var FresnelParameters = /** @class */ (function () {
  70770. function FresnelParameters() {
  70771. this._isEnabled = true;
  70772. this.leftColor = BABYLON.Color3.White();
  70773. this.rightColor = BABYLON.Color3.Black();
  70774. this.bias = 0;
  70775. this.power = 1;
  70776. }
  70777. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70778. get: function () {
  70779. return this._isEnabled;
  70780. },
  70781. set: function (value) {
  70782. if (this._isEnabled === value) {
  70783. return;
  70784. }
  70785. this._isEnabled = value;
  70786. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70787. },
  70788. enumerable: true,
  70789. configurable: true
  70790. });
  70791. FresnelParameters.prototype.clone = function () {
  70792. var newFresnelParameters = new FresnelParameters();
  70793. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70794. return newFresnelParameters;
  70795. };
  70796. FresnelParameters.prototype.serialize = function () {
  70797. var serializationObject = {};
  70798. serializationObject.isEnabled = this.isEnabled;
  70799. serializationObject.leftColor = this.leftColor.asArray();
  70800. serializationObject.rightColor = this.rightColor.asArray();
  70801. serializationObject.bias = this.bias;
  70802. serializationObject.power = this.power;
  70803. return serializationObject;
  70804. };
  70805. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70806. var fresnelParameters = new FresnelParameters();
  70807. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70808. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70809. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70810. fresnelParameters.bias = parsedFresnelParameters.bias;
  70811. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70812. return fresnelParameters;
  70813. };
  70814. return FresnelParameters;
  70815. }());
  70816. BABYLON.FresnelParameters = FresnelParameters;
  70817. })(BABYLON || (BABYLON = {}));
  70818. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70819. var BABYLON;
  70820. (function (BABYLON) {
  70821. var MultiMaterial = /** @class */ (function (_super) {
  70822. __extends(MultiMaterial, _super);
  70823. function MultiMaterial(name, scene) {
  70824. var _this = _super.call(this, name, scene, true) || this;
  70825. scene.multiMaterials.push(_this);
  70826. _this.subMaterials = new Array();
  70827. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70828. return _this;
  70829. }
  70830. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70831. get: function () {
  70832. return this._subMaterials;
  70833. },
  70834. set: function (value) {
  70835. this._subMaterials = value;
  70836. this._hookArray(value);
  70837. },
  70838. enumerable: true,
  70839. configurable: true
  70840. });
  70841. MultiMaterial.prototype._hookArray = function (array) {
  70842. var _this = this;
  70843. var oldPush = array.push;
  70844. array.push = function () {
  70845. var items = [];
  70846. for (var _i = 0; _i < arguments.length; _i++) {
  70847. items[_i] = arguments[_i];
  70848. }
  70849. var result = oldPush.apply(array, items);
  70850. _this._markAllSubMeshesAsTexturesDirty();
  70851. return result;
  70852. };
  70853. var oldSplice = array.splice;
  70854. array.splice = function (index, deleteCount) {
  70855. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70856. _this._markAllSubMeshesAsTexturesDirty();
  70857. return deleted;
  70858. };
  70859. };
  70860. // Properties
  70861. MultiMaterial.prototype.getSubMaterial = function (index) {
  70862. if (index < 0 || index >= this.subMaterials.length) {
  70863. return this.getScene().defaultMaterial;
  70864. }
  70865. return this.subMaterials[index];
  70866. };
  70867. MultiMaterial.prototype.getActiveTextures = function () {
  70868. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70869. if (subMaterial) {
  70870. return subMaterial.getActiveTextures();
  70871. }
  70872. else {
  70873. return [];
  70874. }
  70875. }));
  70876. var _a;
  70877. };
  70878. // Methods
  70879. MultiMaterial.prototype.getClassName = function () {
  70880. return "MultiMaterial";
  70881. };
  70882. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70883. for (var index = 0; index < this.subMaterials.length; index++) {
  70884. var subMaterial = this.subMaterials[index];
  70885. if (subMaterial) {
  70886. if (subMaterial.storeEffectOnSubMeshes) {
  70887. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70888. return false;
  70889. }
  70890. continue;
  70891. }
  70892. if (!subMaterial.isReady(mesh)) {
  70893. return false;
  70894. }
  70895. }
  70896. }
  70897. return true;
  70898. };
  70899. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70900. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70901. for (var index = 0; index < this.subMaterials.length; index++) {
  70902. var subMaterial = null;
  70903. var current = this.subMaterials[index];
  70904. if (cloneChildren && current) {
  70905. subMaterial = current.clone(name + "-" + current.name);
  70906. }
  70907. else {
  70908. subMaterial = this.subMaterials[index];
  70909. }
  70910. newMultiMaterial.subMaterials.push(subMaterial);
  70911. }
  70912. return newMultiMaterial;
  70913. };
  70914. MultiMaterial.prototype.serialize = function () {
  70915. var serializationObject = {};
  70916. serializationObject.name = this.name;
  70917. serializationObject.id = this.id;
  70918. if (BABYLON.Tags) {
  70919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70920. }
  70921. serializationObject.materials = [];
  70922. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70923. var subMat = this.subMaterials[matIndex];
  70924. if (subMat) {
  70925. serializationObject.materials.push(subMat.id);
  70926. }
  70927. else {
  70928. serializationObject.materials.push(null);
  70929. }
  70930. }
  70931. return serializationObject;
  70932. };
  70933. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70934. var scene = this.getScene();
  70935. if (!scene) {
  70936. return;
  70937. }
  70938. var index = scene.multiMaterials.indexOf(this);
  70939. if (index >= 0) {
  70940. scene.multiMaterials.splice(index, 1);
  70941. }
  70942. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70943. };
  70944. return MultiMaterial;
  70945. }(BABYLON.Material));
  70946. BABYLON.MultiMaterial = MultiMaterial;
  70947. })(BABYLON || (BABYLON = {}));
  70948. //# sourceMappingURL=babylon.multiMaterial.js.map
  70949. var BABYLON;
  70950. (function (BABYLON) {
  70951. var FreeCameraTouchInput = /** @class */ (function () {
  70952. function FreeCameraTouchInput() {
  70953. this._offsetX = null;
  70954. this._offsetY = null;
  70955. this._pointerPressed = new Array();
  70956. this.touchAngularSensibility = 200000.0;
  70957. this.touchMoveSensibility = 250.0;
  70958. }
  70959. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70960. var _this = this;
  70961. var previousPosition = null;
  70962. if (this._pointerInput === undefined) {
  70963. this._onLostFocus = function (evt) {
  70964. _this._offsetX = null;
  70965. _this._offsetY = null;
  70966. };
  70967. this._pointerInput = function (p, s) {
  70968. var evt = p.event;
  70969. if (evt.pointerType === "mouse") {
  70970. return;
  70971. }
  70972. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70973. if (!noPreventDefault) {
  70974. evt.preventDefault();
  70975. }
  70976. _this._pointerPressed.push(evt.pointerId);
  70977. if (_this._pointerPressed.length !== 1) {
  70978. return;
  70979. }
  70980. previousPosition = {
  70981. x: evt.clientX,
  70982. y: evt.clientY
  70983. };
  70984. }
  70985. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70986. if (!noPreventDefault) {
  70987. evt.preventDefault();
  70988. }
  70989. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70990. if (index === -1) {
  70991. return;
  70992. }
  70993. _this._pointerPressed.splice(index, 1);
  70994. if (index != 0) {
  70995. return;
  70996. }
  70997. previousPosition = null;
  70998. _this._offsetX = null;
  70999. _this._offsetY = null;
  71000. }
  71001. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71002. if (!noPreventDefault) {
  71003. evt.preventDefault();
  71004. }
  71005. if (!previousPosition) {
  71006. return;
  71007. }
  71008. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71009. if (index != 0) {
  71010. return;
  71011. }
  71012. _this._offsetX = evt.clientX - previousPosition.x;
  71013. _this._offsetY = -(evt.clientY - previousPosition.y);
  71014. }
  71015. };
  71016. }
  71017. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71018. if (this._onLostFocus) {
  71019. element.addEventListener("blur", this._onLostFocus);
  71020. }
  71021. };
  71022. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71023. if (this._pointerInput && element) {
  71024. if (this._observer) {
  71025. this.camera.getScene().onPointerObservable.remove(this._observer);
  71026. this._observer = null;
  71027. }
  71028. if (this._onLostFocus) {
  71029. element.removeEventListener("blur", this._onLostFocus);
  71030. this._onLostFocus = null;
  71031. }
  71032. this._pointerPressed = [];
  71033. this._offsetX = null;
  71034. this._offsetY = null;
  71035. }
  71036. };
  71037. FreeCameraTouchInput.prototype.checkInputs = function () {
  71038. if (this._offsetX && this._offsetY) {
  71039. var camera = this.camera;
  71040. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71041. if (this._pointerPressed.length > 1) {
  71042. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71043. }
  71044. else {
  71045. var speed = camera._computeLocalCameraSpeed();
  71046. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71047. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71048. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71049. }
  71050. }
  71051. };
  71052. FreeCameraTouchInput.prototype.getClassName = function () {
  71053. return "FreeCameraTouchInput";
  71054. };
  71055. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71056. return "touch";
  71057. };
  71058. __decorate([
  71059. BABYLON.serialize()
  71060. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71061. __decorate([
  71062. BABYLON.serialize()
  71063. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71064. return FreeCameraTouchInput;
  71065. }());
  71066. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71067. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71068. })(BABYLON || (BABYLON = {}));
  71069. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71070. var BABYLON;
  71071. (function (BABYLON) {
  71072. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71073. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71074. });
  71075. // We're mainly based on the logic defined into the FreeCamera code
  71076. var TouchCamera = /** @class */ (function (_super) {
  71077. __extends(TouchCamera, _super);
  71078. //-- end properties for backward compatibility for inputs
  71079. function TouchCamera(name, position, scene) {
  71080. var _this = _super.call(this, name, position, scene) || this;
  71081. _this.inputs.addTouch();
  71082. _this._setupInputs();
  71083. return _this;
  71084. }
  71085. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71086. //-- Begin properties for backward compatibility for inputs
  71087. get: function () {
  71088. var touch = this.inputs.attached["touch"];
  71089. if (touch)
  71090. return touch.touchAngularSensibility;
  71091. return 0;
  71092. },
  71093. set: function (value) {
  71094. var touch = this.inputs.attached["touch"];
  71095. if (touch)
  71096. touch.touchAngularSensibility = value;
  71097. },
  71098. enumerable: true,
  71099. configurable: true
  71100. });
  71101. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71102. get: function () {
  71103. var touch = this.inputs.attached["touch"];
  71104. if (touch)
  71105. return touch.touchMoveSensibility;
  71106. return 0;
  71107. },
  71108. set: function (value) {
  71109. var touch = this.inputs.attached["touch"];
  71110. if (touch)
  71111. touch.touchMoveSensibility = value;
  71112. },
  71113. enumerable: true,
  71114. configurable: true
  71115. });
  71116. TouchCamera.prototype.getClassName = function () {
  71117. return "TouchCamera";
  71118. };
  71119. TouchCamera.prototype._setupInputs = function () {
  71120. var mouse = this.inputs.attached["mouse"];
  71121. if (mouse) {
  71122. mouse.touchEnabled = false;
  71123. }
  71124. };
  71125. return TouchCamera;
  71126. }(BABYLON.FreeCamera));
  71127. BABYLON.TouchCamera = TouchCamera;
  71128. })(BABYLON || (BABYLON = {}));
  71129. //# sourceMappingURL=babylon.touchCamera.js.map
  71130. var BABYLON;
  71131. (function (BABYLON) {
  71132. var ProceduralTexture = /** @class */ (function (_super) {
  71133. __extends(ProceduralTexture, _super);
  71134. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71135. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71136. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71137. if (isCube === void 0) { isCube = false; }
  71138. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71139. _this.isCube = isCube;
  71140. _this.isEnabled = true;
  71141. _this._currentRefreshId = -1;
  71142. _this._refreshRate = 1;
  71143. _this._vertexBuffers = {};
  71144. _this._uniforms = new Array();
  71145. _this._samplers = new Array();
  71146. _this._textures = {};
  71147. _this._floats = {};
  71148. _this._floatsArrays = {};
  71149. _this._colors3 = {};
  71150. _this._colors4 = {};
  71151. _this._vectors2 = {};
  71152. _this._vectors3 = {};
  71153. _this._matrices = {};
  71154. _this._fallbackTextureUsed = false;
  71155. scene.proceduralTextures.push(_this);
  71156. _this._engine = scene.getEngine();
  71157. _this.name = name;
  71158. _this.isRenderTarget = true;
  71159. _this._size = size;
  71160. _this._generateMipMaps = generateMipMaps;
  71161. _this.setFragment(fragment);
  71162. _this._fallbackTexture = fallbackTexture;
  71163. if (isCube) {
  71164. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71165. _this.setFloat("face", 0);
  71166. }
  71167. else {
  71168. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71169. }
  71170. // VBO
  71171. var vertices = [];
  71172. vertices.push(1, 1);
  71173. vertices.push(-1, 1);
  71174. vertices.push(-1, -1);
  71175. vertices.push(1, -1);
  71176. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71177. _this._createIndexBuffer();
  71178. return _this;
  71179. }
  71180. ProceduralTexture.prototype._createIndexBuffer = function () {
  71181. var engine = this._engine;
  71182. // Indices
  71183. var indices = [];
  71184. indices.push(0);
  71185. indices.push(1);
  71186. indices.push(2);
  71187. indices.push(0);
  71188. indices.push(2);
  71189. indices.push(3);
  71190. this._indexBuffer = engine.createIndexBuffer(indices);
  71191. };
  71192. ProceduralTexture.prototype._rebuild = function () {
  71193. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71194. if (vb) {
  71195. vb._rebuild();
  71196. }
  71197. this._createIndexBuffer();
  71198. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71199. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71200. }
  71201. };
  71202. ProceduralTexture.prototype.reset = function () {
  71203. if (this._effect === undefined) {
  71204. return;
  71205. }
  71206. var engine = this._engine;
  71207. engine._releaseEffect(this._effect);
  71208. };
  71209. ProceduralTexture.prototype.isReady = function () {
  71210. var _this = this;
  71211. var engine = this._engine;
  71212. var shaders;
  71213. if (!this._fragment) {
  71214. return false;
  71215. }
  71216. if (this._fallbackTextureUsed) {
  71217. return true;
  71218. }
  71219. if (this._fragment.fragmentElement !== undefined) {
  71220. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71221. }
  71222. else {
  71223. shaders = { vertex: "procedural", fragment: this._fragment };
  71224. }
  71225. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71226. _this.releaseInternalTexture();
  71227. if (_this._fallbackTexture) {
  71228. _this._texture = _this._fallbackTexture._texture;
  71229. if (_this._texture) {
  71230. _this._texture.incrementReferences();
  71231. }
  71232. }
  71233. _this._fallbackTextureUsed = true;
  71234. });
  71235. return this._effect.isReady();
  71236. };
  71237. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71238. this._currentRefreshId = -1;
  71239. };
  71240. ProceduralTexture.prototype.setFragment = function (fragment) {
  71241. this._fragment = fragment;
  71242. };
  71243. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71244. get: function () {
  71245. return this._refreshRate;
  71246. },
  71247. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71248. set: function (value) {
  71249. this._refreshRate = value;
  71250. this.resetRefreshCounter();
  71251. },
  71252. enumerable: true,
  71253. configurable: true
  71254. });
  71255. ProceduralTexture.prototype._shouldRender = function () {
  71256. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71257. return false;
  71258. }
  71259. if (this._fallbackTextureUsed) {
  71260. return false;
  71261. }
  71262. if (this._currentRefreshId === -1) { // At least render once
  71263. this._currentRefreshId = 1;
  71264. return true;
  71265. }
  71266. if (this.refreshRate === this._currentRefreshId) {
  71267. this._currentRefreshId = 1;
  71268. return true;
  71269. }
  71270. this._currentRefreshId++;
  71271. return false;
  71272. };
  71273. ProceduralTexture.prototype.getRenderSize = function () {
  71274. return this._size;
  71275. };
  71276. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71277. if (this._fallbackTextureUsed) {
  71278. return;
  71279. }
  71280. this.releaseInternalTexture();
  71281. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71282. // Update properties
  71283. this._size = size;
  71284. this._generateMipMaps = generateMipMaps;
  71285. };
  71286. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71287. if (this._uniforms.indexOf(uniformName) === -1) {
  71288. this._uniforms.push(uniformName);
  71289. }
  71290. };
  71291. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71292. if (this._samplers.indexOf(name) === -1) {
  71293. this._samplers.push(name);
  71294. }
  71295. this._textures[name] = texture;
  71296. return this;
  71297. };
  71298. ProceduralTexture.prototype.setFloat = function (name, value) {
  71299. this._checkUniform(name);
  71300. this._floats[name] = value;
  71301. return this;
  71302. };
  71303. ProceduralTexture.prototype.setFloats = function (name, value) {
  71304. this._checkUniform(name);
  71305. this._floatsArrays[name] = value;
  71306. return this;
  71307. };
  71308. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71309. this._checkUniform(name);
  71310. this._colors3[name] = value;
  71311. return this;
  71312. };
  71313. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71314. this._checkUniform(name);
  71315. this._colors4[name] = value;
  71316. return this;
  71317. };
  71318. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71319. this._checkUniform(name);
  71320. this._vectors2[name] = value;
  71321. return this;
  71322. };
  71323. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71324. this._checkUniform(name);
  71325. this._vectors3[name] = value;
  71326. return this;
  71327. };
  71328. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71329. this._checkUniform(name);
  71330. this._matrices[name] = value;
  71331. return this;
  71332. };
  71333. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71334. var scene = this.getScene();
  71335. if (!scene) {
  71336. return;
  71337. }
  71338. var engine = this._engine;
  71339. // Render
  71340. engine.enableEffect(this._effect);
  71341. engine.setState(false);
  71342. // Texture
  71343. for (var name in this._textures) {
  71344. this._effect.setTexture(name, this._textures[name]);
  71345. }
  71346. // Float
  71347. for (name in this._floats) {
  71348. this._effect.setFloat(name, this._floats[name]);
  71349. }
  71350. // Floats
  71351. for (name in this._floatsArrays) {
  71352. this._effect.setArray(name, this._floatsArrays[name]);
  71353. }
  71354. // Color3
  71355. for (name in this._colors3) {
  71356. this._effect.setColor3(name, this._colors3[name]);
  71357. }
  71358. // Color4
  71359. for (name in this._colors4) {
  71360. var color = this._colors4[name];
  71361. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71362. }
  71363. // Vector2
  71364. for (name in this._vectors2) {
  71365. this._effect.setVector2(name, this._vectors2[name]);
  71366. }
  71367. // Vector3
  71368. for (name in this._vectors3) {
  71369. this._effect.setVector3(name, this._vectors3[name]);
  71370. }
  71371. // Matrix
  71372. for (name in this._matrices) {
  71373. this._effect.setMatrix(name, this._matrices[name]);
  71374. }
  71375. if (!this._texture) {
  71376. return;
  71377. }
  71378. if (this.isCube) {
  71379. for (var face = 0; face < 6; face++) {
  71380. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71381. // VBOs
  71382. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71383. this._effect.setFloat("face", face);
  71384. // Clear
  71385. engine.clear(scene.clearColor, true, true, true);
  71386. // Draw order
  71387. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71388. // Mipmaps
  71389. if (face === 5) {
  71390. engine.generateMipMapsForCubemap(this._texture);
  71391. }
  71392. }
  71393. }
  71394. else {
  71395. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71396. // VBOs
  71397. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71398. // Clear
  71399. engine.clear(scene.clearColor, true, true, true);
  71400. // Draw order
  71401. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71402. }
  71403. // Unbind
  71404. engine.unBindFramebuffer(this._texture, this.isCube);
  71405. if (this.onGenerated) {
  71406. this.onGenerated();
  71407. }
  71408. };
  71409. ProceduralTexture.prototype.clone = function () {
  71410. var textureSize = this.getSize();
  71411. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71412. // Base texture
  71413. newTexture.hasAlpha = this.hasAlpha;
  71414. newTexture.level = this.level;
  71415. // RenderTarget Texture
  71416. newTexture.coordinatesMode = this.coordinatesMode;
  71417. return newTexture;
  71418. };
  71419. ProceduralTexture.prototype.dispose = function () {
  71420. var scene = this.getScene();
  71421. if (!scene) {
  71422. return;
  71423. }
  71424. var index = scene.proceduralTextures.indexOf(this);
  71425. if (index >= 0) {
  71426. scene.proceduralTextures.splice(index, 1);
  71427. }
  71428. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71429. if (vertexBuffer) {
  71430. vertexBuffer.dispose();
  71431. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71432. }
  71433. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71434. this._indexBuffer = null;
  71435. }
  71436. _super.prototype.dispose.call(this);
  71437. };
  71438. __decorate([
  71439. BABYLON.serialize()
  71440. ], ProceduralTexture.prototype, "_size", void 0);
  71441. __decorate([
  71442. BABYLON.serialize()
  71443. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71444. __decorate([
  71445. BABYLON.serialize()
  71446. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71447. __decorate([
  71448. BABYLON.serialize()
  71449. ], ProceduralTexture.prototype, "refreshRate", null);
  71450. return ProceduralTexture;
  71451. }(BABYLON.Texture));
  71452. BABYLON.ProceduralTexture = ProceduralTexture;
  71453. })(BABYLON || (BABYLON = {}));
  71454. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71455. var BABYLON;
  71456. (function (BABYLON) {
  71457. var CustomProceduralTexture = /** @class */ (function (_super) {
  71458. __extends(CustomProceduralTexture, _super);
  71459. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71460. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71461. _this._animate = true;
  71462. _this._time = 0;
  71463. _this._texturePath = texturePath;
  71464. //Try to load json
  71465. _this.loadJson(texturePath);
  71466. _this.refreshRate = 1;
  71467. return _this;
  71468. }
  71469. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71470. var _this = this;
  71471. var noConfigFile = function () {
  71472. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71473. try {
  71474. _this.setFragment(_this._texturePath);
  71475. }
  71476. catch (ex) {
  71477. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71478. }
  71479. };
  71480. var configFileUrl = jsonUrl + "/config.json";
  71481. var xhr = new XMLHttpRequest();
  71482. xhr.open("GET", configFileUrl, true);
  71483. xhr.addEventListener("load", function () {
  71484. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71485. try {
  71486. _this._config = JSON.parse(xhr.response);
  71487. _this.updateShaderUniforms();
  71488. _this.updateTextures();
  71489. _this.setFragment(_this._texturePath + "/custom");
  71490. _this._animate = _this._config.animate;
  71491. _this.refreshRate = _this._config.refreshrate;
  71492. }
  71493. catch (ex) {
  71494. noConfigFile();
  71495. }
  71496. }
  71497. else {
  71498. noConfigFile();
  71499. }
  71500. }, false);
  71501. xhr.addEventListener("error", function () {
  71502. noConfigFile();
  71503. }, false);
  71504. try {
  71505. xhr.send();
  71506. }
  71507. catch (ex) {
  71508. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71509. }
  71510. };
  71511. CustomProceduralTexture.prototype.isReady = function () {
  71512. if (!_super.prototype.isReady.call(this)) {
  71513. return false;
  71514. }
  71515. for (var name in this._textures) {
  71516. var texture = this._textures[name];
  71517. if (!texture.isReady()) {
  71518. return false;
  71519. }
  71520. }
  71521. return true;
  71522. };
  71523. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71524. var scene = this.getScene();
  71525. if (this._animate && scene) {
  71526. this._time += scene.getAnimationRatio() * 0.03;
  71527. this.updateShaderUniforms();
  71528. }
  71529. _super.prototype.render.call(this, useCameraPostProcess);
  71530. };
  71531. CustomProceduralTexture.prototype.updateTextures = function () {
  71532. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71533. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71534. }
  71535. };
  71536. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71537. if (this._config) {
  71538. for (var j = 0; j < this._config.uniforms.length; j++) {
  71539. var uniform = this._config.uniforms[j];
  71540. switch (uniform.type) {
  71541. case "float":
  71542. this.setFloat(uniform.name, uniform.value);
  71543. break;
  71544. case "color3":
  71545. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71546. break;
  71547. case "color4":
  71548. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71549. break;
  71550. case "vector2":
  71551. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71552. break;
  71553. case "vector3":
  71554. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71555. break;
  71556. }
  71557. }
  71558. }
  71559. this.setFloat("time", this._time);
  71560. };
  71561. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71562. get: function () {
  71563. return this._animate;
  71564. },
  71565. set: function (value) {
  71566. this._animate = value;
  71567. },
  71568. enumerable: true,
  71569. configurable: true
  71570. });
  71571. return CustomProceduralTexture;
  71572. }(BABYLON.ProceduralTexture));
  71573. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71574. })(BABYLON || (BABYLON = {}));
  71575. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71576. var BABYLON;
  71577. (function (BABYLON) {
  71578. var FreeCameraGamepadInput = /** @class */ (function () {
  71579. function FreeCameraGamepadInput() {
  71580. this.gamepadAngularSensibility = 200;
  71581. this.gamepadMoveSensibility = 40;
  71582. // private members
  71583. this._cameraTransform = BABYLON.Matrix.Identity();
  71584. this._deltaTransform = BABYLON.Vector3.Zero();
  71585. this._vector3 = BABYLON.Vector3.Zero();
  71586. this._vector2 = BABYLON.Vector2.Zero();
  71587. }
  71588. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71589. var _this = this;
  71590. var manager = this.camera.getScene().gamepadManager;
  71591. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71592. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71593. // prioritize XBOX gamepads.
  71594. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71595. _this.gamepad = gamepad;
  71596. }
  71597. }
  71598. });
  71599. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71600. if (_this.gamepad === gamepad) {
  71601. _this.gamepad = null;
  71602. }
  71603. });
  71604. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71605. };
  71606. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71607. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71608. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71609. this.gamepad = null;
  71610. };
  71611. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71612. if (this.gamepad && this.gamepad.leftStick) {
  71613. var camera = this.camera;
  71614. var LSValues = this.gamepad.leftStick;
  71615. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71616. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71617. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71618. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71619. var RSValues = this.gamepad.rightStick;
  71620. if (RSValues) {
  71621. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71622. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71623. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71624. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71625. }
  71626. else {
  71627. RSValues = { x: 0, y: 0 };
  71628. }
  71629. if (!camera.rotationQuaternion) {
  71630. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71631. }
  71632. else {
  71633. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71634. }
  71635. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71636. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71637. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71638. camera.cameraDirection.addInPlace(this._deltaTransform);
  71639. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71640. camera.cameraRotation.addInPlace(this._vector2);
  71641. }
  71642. };
  71643. FreeCameraGamepadInput.prototype.getClassName = function () {
  71644. return "FreeCameraGamepadInput";
  71645. };
  71646. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71647. return "gamepad";
  71648. };
  71649. __decorate([
  71650. BABYLON.serialize()
  71651. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71652. __decorate([
  71653. BABYLON.serialize()
  71654. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71655. return FreeCameraGamepadInput;
  71656. }());
  71657. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71658. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71659. })(BABYLON || (BABYLON = {}));
  71660. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71661. var BABYLON;
  71662. (function (BABYLON) {
  71663. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71664. function ArcRotateCameraGamepadInput() {
  71665. this.gamepadRotationSensibility = 80;
  71666. this.gamepadMoveSensibility = 40;
  71667. }
  71668. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71669. var _this = this;
  71670. var manager = this.camera.getScene().gamepadManager;
  71671. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71672. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71673. // prioritize XBOX gamepads.
  71674. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71675. _this.gamepad = gamepad;
  71676. }
  71677. }
  71678. });
  71679. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71680. if (_this.gamepad === gamepad) {
  71681. _this.gamepad = null;
  71682. }
  71683. });
  71684. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71685. };
  71686. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71687. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71688. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71689. this.gamepad = null;
  71690. };
  71691. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71692. if (this.gamepad) {
  71693. var camera = this.camera;
  71694. var RSValues = this.gamepad.rightStick;
  71695. if (RSValues) {
  71696. if (RSValues.x != 0) {
  71697. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71698. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71699. camera.inertialAlphaOffset += normalizedRX;
  71700. }
  71701. }
  71702. if (RSValues.y != 0) {
  71703. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71704. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71705. camera.inertialBetaOffset += normalizedRY;
  71706. }
  71707. }
  71708. }
  71709. var LSValues = this.gamepad.leftStick;
  71710. if (LSValues && LSValues.y != 0) {
  71711. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71712. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71713. this.camera.inertialRadiusOffset -= normalizedLY;
  71714. }
  71715. }
  71716. }
  71717. };
  71718. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71719. return "ArcRotateCameraGamepadInput";
  71720. };
  71721. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71722. return "gamepad";
  71723. };
  71724. __decorate([
  71725. BABYLON.serialize()
  71726. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71727. __decorate([
  71728. BABYLON.serialize()
  71729. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71730. return ArcRotateCameraGamepadInput;
  71731. }());
  71732. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71733. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71734. })(BABYLON || (BABYLON = {}));
  71735. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71736. var BABYLON;
  71737. (function (BABYLON) {
  71738. var GamepadManager = /** @class */ (function () {
  71739. function GamepadManager(_scene) {
  71740. var _this = this;
  71741. this._scene = _scene;
  71742. this._babylonGamepads = [];
  71743. this._oneGamepadConnected = false;
  71744. this._isMonitoring = false;
  71745. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71746. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71747. this._gamepadEventSupported = false;
  71748. }
  71749. else {
  71750. this._gamepadEventSupported = 'GamepadEvent' in window;
  71751. this._gamepadSupport = (navigator.getGamepads ||
  71752. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71753. }
  71754. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71755. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71756. for (var i in _this._babylonGamepads) {
  71757. var gamepad = _this._babylonGamepads[i];
  71758. if (gamepad && gamepad._isConnected) {
  71759. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71760. }
  71761. }
  71762. });
  71763. this._onGamepadConnectedEvent = function (evt) {
  71764. var gamepad = evt.gamepad;
  71765. if (gamepad.index in _this._babylonGamepads) {
  71766. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71767. return;
  71768. }
  71769. }
  71770. var newGamepad;
  71771. if (_this._babylonGamepads[gamepad.index]) {
  71772. newGamepad = _this._babylonGamepads[gamepad.index];
  71773. newGamepad.browserGamepad = gamepad;
  71774. newGamepad._isConnected = true;
  71775. }
  71776. else {
  71777. newGamepad = _this._addNewGamepad(gamepad);
  71778. }
  71779. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71780. _this._startMonitoringGamepads();
  71781. };
  71782. this._onGamepadDisconnectedEvent = function (evt) {
  71783. var gamepad = evt.gamepad;
  71784. // Remove the gamepad from the list of gamepads to monitor.
  71785. for (var i in _this._babylonGamepads) {
  71786. if (_this._babylonGamepads[i].index === gamepad.index) {
  71787. var disconnectedGamepad = _this._babylonGamepads[i];
  71788. disconnectedGamepad._isConnected = false;
  71789. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71790. break;
  71791. }
  71792. }
  71793. };
  71794. if (this._gamepadSupport) {
  71795. //first add already-connected gamepads
  71796. this._updateGamepadObjects();
  71797. if (this._babylonGamepads.length) {
  71798. this._startMonitoringGamepads();
  71799. }
  71800. // Checking if the gamepad connected event is supported (like in Firefox)
  71801. if (this._gamepadEventSupported) {
  71802. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71803. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71804. }
  71805. else {
  71806. this._startMonitoringGamepads();
  71807. }
  71808. }
  71809. }
  71810. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71811. get: function () {
  71812. return this._babylonGamepads;
  71813. },
  71814. enumerable: true,
  71815. configurable: true
  71816. });
  71817. GamepadManager.prototype.getGamepadByType = function (type) {
  71818. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71819. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71820. var gamepad = _a[_i];
  71821. if (gamepad && gamepad.type === type) {
  71822. return gamepad;
  71823. }
  71824. }
  71825. return null;
  71826. };
  71827. GamepadManager.prototype.dispose = function () {
  71828. if (this._gamepadEventSupported) {
  71829. if (this._onGamepadConnectedEvent) {
  71830. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71831. }
  71832. if (this._onGamepadDisconnectedEvent) {
  71833. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71834. }
  71835. this._onGamepadConnectedEvent = null;
  71836. this._onGamepadDisconnectedEvent = null;
  71837. }
  71838. this._babylonGamepads.forEach(function (gamepad) {
  71839. gamepad.dispose();
  71840. });
  71841. this.onGamepadConnectedObservable.clear();
  71842. this.onGamepadDisconnectedObservable.clear();
  71843. this._oneGamepadConnected = false;
  71844. this._stopMonitoringGamepads();
  71845. this._babylonGamepads = [];
  71846. };
  71847. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71848. if (!this._oneGamepadConnected) {
  71849. this._oneGamepadConnected = true;
  71850. }
  71851. var newGamepad;
  71852. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71853. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71854. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71855. }
  71856. // if pose is supported, use the (WebVR) pose enabled controller
  71857. else if (gamepad.pose) {
  71858. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71859. }
  71860. else {
  71861. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71862. }
  71863. this._babylonGamepads[newGamepad.index] = newGamepad;
  71864. return newGamepad;
  71865. };
  71866. GamepadManager.prototype._startMonitoringGamepads = function () {
  71867. if (!this._isMonitoring) {
  71868. this._isMonitoring = true;
  71869. //back-comp
  71870. if (!this._scene) {
  71871. this._checkGamepadsStatus();
  71872. }
  71873. }
  71874. };
  71875. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71876. this._isMonitoring = false;
  71877. };
  71878. GamepadManager.prototype._checkGamepadsStatus = function () {
  71879. var _this = this;
  71880. // Hack to be compatible Chrome
  71881. this._updateGamepadObjects();
  71882. for (var i in this._babylonGamepads) {
  71883. var gamepad = this._babylonGamepads[i];
  71884. if (!gamepad || !gamepad.isConnected) {
  71885. continue;
  71886. }
  71887. gamepad.update();
  71888. }
  71889. if (this._isMonitoring && !this._scene) {
  71890. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71891. }
  71892. };
  71893. // This function is called only on Chrome, which does not properly support
  71894. // connection/disconnection events and forces you to recopy again the gamepad object
  71895. GamepadManager.prototype._updateGamepadObjects = function () {
  71896. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71897. for (var i = 0; i < gamepads.length; i++) {
  71898. var gamepad = gamepads[i];
  71899. if (gamepad) {
  71900. if (!this._babylonGamepads[gamepad.index]) {
  71901. var newGamepad = this._addNewGamepad(gamepad);
  71902. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71903. }
  71904. else {
  71905. // Forced to copy again this object for Chrome for unknown reason
  71906. this._babylonGamepads[i].browserGamepad = gamepad;
  71907. if (!this._babylonGamepads[i].isConnected) {
  71908. this._babylonGamepads[i]._isConnected = true;
  71909. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71910. }
  71911. }
  71912. }
  71913. }
  71914. };
  71915. return GamepadManager;
  71916. }());
  71917. BABYLON.GamepadManager = GamepadManager;
  71918. })(BABYLON || (BABYLON = {}));
  71919. //# sourceMappingURL=babylon.gamepadManager.js.map
  71920. var BABYLON;
  71921. (function (BABYLON) {
  71922. var StickValues = /** @class */ (function () {
  71923. function StickValues(x, y) {
  71924. this.x = x;
  71925. this.y = y;
  71926. }
  71927. return StickValues;
  71928. }());
  71929. BABYLON.StickValues = StickValues;
  71930. var Gamepad = /** @class */ (function () {
  71931. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71932. if (leftStickX === void 0) { leftStickX = 0; }
  71933. if (leftStickY === void 0) { leftStickY = 1; }
  71934. if (rightStickX === void 0) { rightStickX = 2; }
  71935. if (rightStickY === void 0) { rightStickY = 3; }
  71936. this.id = id;
  71937. this.index = index;
  71938. this.browserGamepad = browserGamepad;
  71939. this._isConnected = true;
  71940. this._invertLeftStickY = false;
  71941. this.type = Gamepad.GAMEPAD;
  71942. this._leftStickAxisX = leftStickX;
  71943. this._leftStickAxisY = leftStickY;
  71944. this._rightStickAxisX = rightStickX;
  71945. this._rightStickAxisY = rightStickY;
  71946. if (this.browserGamepad.axes.length >= 2) {
  71947. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71948. }
  71949. if (this.browserGamepad.axes.length >= 4) {
  71950. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71951. }
  71952. }
  71953. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71954. get: function () {
  71955. return this._isConnected;
  71956. },
  71957. enumerable: true,
  71958. configurable: true
  71959. });
  71960. Gamepad.prototype.onleftstickchanged = function (callback) {
  71961. this._onleftstickchanged = callback;
  71962. };
  71963. Gamepad.prototype.onrightstickchanged = function (callback) {
  71964. this._onrightstickchanged = callback;
  71965. };
  71966. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71967. get: function () {
  71968. return this._leftStick;
  71969. },
  71970. set: function (newValues) {
  71971. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71972. this._onleftstickchanged(newValues);
  71973. }
  71974. this._leftStick = newValues;
  71975. },
  71976. enumerable: true,
  71977. configurable: true
  71978. });
  71979. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71980. get: function () {
  71981. return this._rightStick;
  71982. },
  71983. set: function (newValues) {
  71984. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71985. this._onrightstickchanged(newValues);
  71986. }
  71987. this._rightStick = newValues;
  71988. },
  71989. enumerable: true,
  71990. configurable: true
  71991. });
  71992. Gamepad.prototype.update = function () {
  71993. if (this._leftStick) {
  71994. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71995. if (this._invertLeftStickY) {
  71996. this.leftStick.y *= -1;
  71997. }
  71998. }
  71999. if (this._rightStick) {
  72000. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72001. }
  72002. };
  72003. Gamepad.prototype.dispose = function () {
  72004. };
  72005. Gamepad.GAMEPAD = 0;
  72006. Gamepad.GENERIC = 1;
  72007. Gamepad.XBOX = 2;
  72008. Gamepad.POSE_ENABLED = 3;
  72009. return Gamepad;
  72010. }());
  72011. BABYLON.Gamepad = Gamepad;
  72012. var GenericPad = /** @class */ (function (_super) {
  72013. __extends(GenericPad, _super);
  72014. function GenericPad(id, index, browserGamepad) {
  72015. var _this = _super.call(this, id, index, browserGamepad) || this;
  72016. _this.onButtonDownObservable = new BABYLON.Observable();
  72017. _this.onButtonUpObservable = new BABYLON.Observable();
  72018. _this.type = Gamepad.GENERIC;
  72019. _this._buttons = new Array(browserGamepad.buttons.length);
  72020. return _this;
  72021. }
  72022. GenericPad.prototype.onbuttondown = function (callback) {
  72023. this._onbuttondown = callback;
  72024. };
  72025. GenericPad.prototype.onbuttonup = function (callback) {
  72026. this._onbuttonup = callback;
  72027. };
  72028. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72029. if (newValue !== currentValue) {
  72030. if (newValue === 1) {
  72031. if (this._onbuttondown) {
  72032. this._onbuttondown(buttonIndex);
  72033. }
  72034. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72035. }
  72036. if (newValue === 0) {
  72037. if (this._onbuttonup) {
  72038. this._onbuttonup(buttonIndex);
  72039. }
  72040. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72041. }
  72042. }
  72043. return newValue;
  72044. };
  72045. GenericPad.prototype.update = function () {
  72046. _super.prototype.update.call(this);
  72047. for (var index = 0; index < this._buttons.length; index++) {
  72048. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72049. }
  72050. };
  72051. GenericPad.prototype.dispose = function () {
  72052. _super.prototype.dispose.call(this);
  72053. this.onButtonDownObservable.clear();
  72054. this.onButtonUpObservable.clear();
  72055. };
  72056. return GenericPad;
  72057. }(Gamepad));
  72058. BABYLON.GenericPad = GenericPad;
  72059. })(BABYLON || (BABYLON = {}));
  72060. //# sourceMappingURL=babylon.gamepad.js.map
  72061. var BABYLON;
  72062. (function (BABYLON) {
  72063. /**
  72064. * Defines supported buttons for XBox360 compatible gamepads
  72065. */
  72066. var Xbox360Button;
  72067. (function (Xbox360Button) {
  72068. /** A */
  72069. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72070. /** B */
  72071. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72072. /** X */
  72073. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72074. /** Y */
  72075. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72076. /** Start */
  72077. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72078. /** Back */
  72079. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72080. /** Left button */
  72081. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72082. /** Right button */
  72083. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72084. /** Left stick */
  72085. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72086. /** Right stick */
  72087. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72088. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72089. /** Defines values for XBox360 DPad */
  72090. var Xbox360Dpad;
  72091. (function (Xbox360Dpad) {
  72092. /** Up */
  72093. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72094. /** Down */
  72095. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72096. /** Left */
  72097. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72098. /** Right */
  72099. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72100. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72101. /**
  72102. * Defines a XBox360 gamepad
  72103. */
  72104. var Xbox360Pad = /** @class */ (function (_super) {
  72105. __extends(Xbox360Pad, _super);
  72106. /**
  72107. * Creates a new XBox360 gamepad object
  72108. * @param id defines the id of this gamepad
  72109. * @param index defines its index
  72110. * @param gamepad defines the internal HTML gamepad object
  72111. * @param xboxOne defines if it is a XBox One gamepad
  72112. */
  72113. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72114. if (xboxOne === void 0) { xboxOne = false; }
  72115. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72116. _this._leftTrigger = 0;
  72117. _this._rightTrigger = 0;
  72118. /** Observable raised when a button is pressed */
  72119. _this.onButtonDownObservable = new BABYLON.Observable();
  72120. /** Observable raised when a button is released */
  72121. _this.onButtonUpObservable = new BABYLON.Observable();
  72122. /** Observable raised when a pad is pressed */
  72123. _this.onPadDownObservable = new BABYLON.Observable();
  72124. /** Observable raised when a pad is released */
  72125. _this.onPadUpObservable = new BABYLON.Observable();
  72126. _this._buttonA = 0;
  72127. _this._buttonB = 0;
  72128. _this._buttonX = 0;
  72129. _this._buttonY = 0;
  72130. _this._buttonBack = 0;
  72131. _this._buttonStart = 0;
  72132. _this._buttonLB = 0;
  72133. _this._buttonRB = 0;
  72134. _this._buttonLeftStick = 0;
  72135. _this._buttonRightStick = 0;
  72136. _this._dPadUp = 0;
  72137. _this._dPadDown = 0;
  72138. _this._dPadLeft = 0;
  72139. _this._dPadRight = 0;
  72140. _this._isXboxOnePad = false;
  72141. _this.type = BABYLON.Gamepad.XBOX;
  72142. _this._isXboxOnePad = xboxOne;
  72143. return _this;
  72144. }
  72145. /**
  72146. * Defines the callback to call when left trigger is pressed
  72147. * @param callback defines the callback to use
  72148. */
  72149. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72150. this._onlefttriggerchanged = callback;
  72151. };
  72152. /**
  72153. * Defines the callback to call when right trigger is pressed
  72154. * @param callback defines the callback to use
  72155. */
  72156. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72157. this._onrighttriggerchanged = callback;
  72158. };
  72159. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72160. /**
  72161. * Gets or sets left trigger value
  72162. */
  72163. get: function () {
  72164. return this._leftTrigger;
  72165. },
  72166. set: function (newValue) {
  72167. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72168. this._onlefttriggerchanged(newValue);
  72169. }
  72170. this._leftTrigger = newValue;
  72171. },
  72172. enumerable: true,
  72173. configurable: true
  72174. });
  72175. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72176. /**
  72177. * Gets or sets right trigger value
  72178. */
  72179. get: function () {
  72180. return this._rightTrigger;
  72181. },
  72182. set: function (newValue) {
  72183. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72184. this._onrighttriggerchanged(newValue);
  72185. }
  72186. this._rightTrigger = newValue;
  72187. },
  72188. enumerable: true,
  72189. configurable: true
  72190. });
  72191. /**
  72192. * Defines the callback to call when a button is pressed
  72193. * @param callback defines the callback to use
  72194. */
  72195. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72196. this._onbuttondown = callback;
  72197. };
  72198. /**
  72199. * Defines the callback to call when a button is released
  72200. * @param callback defines the callback to use
  72201. */
  72202. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72203. this._onbuttonup = callback;
  72204. };
  72205. /**
  72206. * Defines the callback to call when a pad is pressed
  72207. * @param callback defines the callback to use
  72208. */
  72209. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72210. this._ondpaddown = callback;
  72211. };
  72212. /**
  72213. * Defines the callback to call when a pad is released
  72214. * @param callback defines the callback to use
  72215. */
  72216. Xbox360Pad.prototype.ondpadup = function (callback) {
  72217. this._ondpadup = callback;
  72218. };
  72219. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72220. if (newValue !== currentValue) {
  72221. if (newValue === 1) {
  72222. if (this._onbuttondown) {
  72223. this._onbuttondown(buttonType);
  72224. }
  72225. this.onButtonDownObservable.notifyObservers(buttonType);
  72226. }
  72227. if (newValue === 0) {
  72228. if (this._onbuttonup) {
  72229. this._onbuttonup(buttonType);
  72230. }
  72231. this.onButtonUpObservable.notifyObservers(buttonType);
  72232. }
  72233. }
  72234. return newValue;
  72235. };
  72236. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72237. if (newValue !== currentValue) {
  72238. if (newValue === 1) {
  72239. if (this._ondpaddown) {
  72240. this._ondpaddown(buttonType);
  72241. }
  72242. this.onPadDownObservable.notifyObservers(buttonType);
  72243. }
  72244. if (newValue === 0) {
  72245. if (this._ondpadup) {
  72246. this._ondpadup(buttonType);
  72247. }
  72248. this.onPadUpObservable.notifyObservers(buttonType);
  72249. }
  72250. }
  72251. return newValue;
  72252. };
  72253. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72254. /** Gets or sets value of A button */
  72255. get: function () {
  72256. return this._buttonA;
  72257. },
  72258. set: function (value) {
  72259. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72260. },
  72261. enumerable: true,
  72262. configurable: true
  72263. });
  72264. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72265. /** Gets or sets value of B button */
  72266. get: function () {
  72267. return this._buttonB;
  72268. },
  72269. set: function (value) {
  72270. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72271. },
  72272. enumerable: true,
  72273. configurable: true
  72274. });
  72275. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72276. /** Gets or sets value of X button */
  72277. get: function () {
  72278. return this._buttonX;
  72279. },
  72280. set: function (value) {
  72281. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72282. },
  72283. enumerable: true,
  72284. configurable: true
  72285. });
  72286. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72287. /** Gets or sets value of Y button */
  72288. get: function () {
  72289. return this._buttonY;
  72290. },
  72291. set: function (value) {
  72292. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72293. },
  72294. enumerable: true,
  72295. configurable: true
  72296. });
  72297. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72298. /** Gets or sets value of Start button */
  72299. get: function () {
  72300. return this._buttonStart;
  72301. },
  72302. set: function (value) {
  72303. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72304. },
  72305. enumerable: true,
  72306. configurable: true
  72307. });
  72308. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72309. /** Gets or sets value of Back button */
  72310. get: function () {
  72311. return this._buttonBack;
  72312. },
  72313. set: function (value) {
  72314. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72320. /** Gets or sets value of Left button */
  72321. get: function () {
  72322. return this._buttonLB;
  72323. },
  72324. set: function (value) {
  72325. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72326. },
  72327. enumerable: true,
  72328. configurable: true
  72329. });
  72330. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72331. /** Gets or sets value of Right button */
  72332. get: function () {
  72333. return this._buttonRB;
  72334. },
  72335. set: function (value) {
  72336. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72337. },
  72338. enumerable: true,
  72339. configurable: true
  72340. });
  72341. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72342. /** Gets or sets value of left stick */
  72343. get: function () {
  72344. return this._buttonLeftStick;
  72345. },
  72346. set: function (value) {
  72347. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72348. },
  72349. enumerable: true,
  72350. configurable: true
  72351. });
  72352. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72353. /** Gets or sets value of right stick */
  72354. get: function () {
  72355. return this._buttonRightStick;
  72356. },
  72357. set: function (value) {
  72358. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72359. },
  72360. enumerable: true,
  72361. configurable: true
  72362. });
  72363. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72364. /** Gets or sets value of DPad up */
  72365. get: function () {
  72366. return this._dPadUp;
  72367. },
  72368. set: function (value) {
  72369. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72370. },
  72371. enumerable: true,
  72372. configurable: true
  72373. });
  72374. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72375. /** Gets or sets value of DPad down */
  72376. get: function () {
  72377. return this._dPadDown;
  72378. },
  72379. set: function (value) {
  72380. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72381. },
  72382. enumerable: true,
  72383. configurable: true
  72384. });
  72385. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72386. /** Gets or sets value of DPad left */
  72387. get: function () {
  72388. return this._dPadLeft;
  72389. },
  72390. set: function (value) {
  72391. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72392. },
  72393. enumerable: true,
  72394. configurable: true
  72395. });
  72396. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72397. /** Gets or sets value of DPad right */
  72398. get: function () {
  72399. return this._dPadRight;
  72400. },
  72401. set: function (value) {
  72402. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72403. },
  72404. enumerable: true,
  72405. configurable: true
  72406. });
  72407. /**
  72408. * Force the gamepad to synchronize with device values
  72409. */
  72410. Xbox360Pad.prototype.update = function () {
  72411. _super.prototype.update.call(this);
  72412. if (this._isXboxOnePad) {
  72413. this.buttonA = this.browserGamepad.buttons[0].value;
  72414. this.buttonB = this.browserGamepad.buttons[1].value;
  72415. this.buttonX = this.browserGamepad.buttons[2].value;
  72416. this.buttonY = this.browserGamepad.buttons[3].value;
  72417. this.buttonLB = this.browserGamepad.buttons[4].value;
  72418. this.buttonRB = this.browserGamepad.buttons[5].value;
  72419. this.leftTrigger = this.browserGamepad.axes[2];
  72420. this.rightTrigger = this.browserGamepad.axes[5];
  72421. this.buttonBack = this.browserGamepad.buttons[9].value;
  72422. this.buttonStart = this.browserGamepad.buttons[8].value;
  72423. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72424. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72425. this.dPadUp = this.browserGamepad.buttons[11].value;
  72426. this.dPadDown = this.browserGamepad.buttons[12].value;
  72427. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72428. this.dPadRight = this.browserGamepad.buttons[14].value;
  72429. }
  72430. else {
  72431. this.buttonA = this.browserGamepad.buttons[0].value;
  72432. this.buttonB = this.browserGamepad.buttons[1].value;
  72433. this.buttonX = this.browserGamepad.buttons[2].value;
  72434. this.buttonY = this.browserGamepad.buttons[3].value;
  72435. this.buttonLB = this.browserGamepad.buttons[4].value;
  72436. this.buttonRB = this.browserGamepad.buttons[5].value;
  72437. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72438. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72439. this.buttonBack = this.browserGamepad.buttons[8].value;
  72440. this.buttonStart = this.browserGamepad.buttons[9].value;
  72441. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72442. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72443. this.dPadUp = this.browserGamepad.buttons[12].value;
  72444. this.dPadDown = this.browserGamepad.buttons[13].value;
  72445. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72446. this.dPadRight = this.browserGamepad.buttons[15].value;
  72447. }
  72448. };
  72449. Xbox360Pad.prototype.dispose = function () {
  72450. _super.prototype.dispose.call(this);
  72451. this.onButtonDownObservable.clear();
  72452. this.onButtonUpObservable.clear();
  72453. this.onPadDownObservable.clear();
  72454. this.onPadUpObservable.clear();
  72455. };
  72456. return Xbox360Pad;
  72457. }(BABYLON.Gamepad));
  72458. BABYLON.Xbox360Pad = Xbox360Pad;
  72459. })(BABYLON || (BABYLON = {}));
  72460. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72461. var BABYLON;
  72462. (function (BABYLON) {
  72463. /**
  72464. * Defines the types of pose enabled controllers that are supported
  72465. */
  72466. var PoseEnabledControllerType;
  72467. (function (PoseEnabledControllerType) {
  72468. /**
  72469. * HTC Vive
  72470. */
  72471. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72472. /**
  72473. * Oculus Rift
  72474. */
  72475. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72476. /**
  72477. * Windows mixed reality
  72478. */
  72479. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72480. /**
  72481. * Samsung gear VR
  72482. */
  72483. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72484. /**
  72485. * Google Daydream
  72486. */
  72487. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72488. /**
  72489. * Generic
  72490. */
  72491. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72492. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72493. /**
  72494. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72495. */
  72496. var PoseEnabledControllerHelper = /** @class */ (function () {
  72497. function PoseEnabledControllerHelper() {
  72498. }
  72499. /**
  72500. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72501. * @param vrGamepad the gamepad to initialized
  72502. * @returns a vr controller of the type the gamepad identified as
  72503. */
  72504. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72505. // Oculus Touch
  72506. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72507. return new BABYLON.OculusTouchController(vrGamepad);
  72508. }
  72509. // Windows Mixed Reality controllers
  72510. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72511. return new BABYLON.WindowsMotionController(vrGamepad);
  72512. }
  72513. // HTC Vive
  72514. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72515. return new BABYLON.ViveController(vrGamepad);
  72516. }
  72517. // Samsung/Oculus Gear VR or Oculus Go
  72518. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72519. return new BABYLON.GearVRController(vrGamepad);
  72520. }
  72521. // Google Daydream
  72522. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72523. return new BABYLON.DaydreamController(vrGamepad);
  72524. }
  72525. // Generic
  72526. else {
  72527. return new BABYLON.GenericController(vrGamepad);
  72528. }
  72529. };
  72530. return PoseEnabledControllerHelper;
  72531. }());
  72532. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72533. /**
  72534. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72535. */
  72536. var PoseEnabledController = /** @class */ (function (_super) {
  72537. __extends(PoseEnabledController, _super);
  72538. /**
  72539. * Creates a new PoseEnabledController from a gamepad
  72540. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72541. */
  72542. function PoseEnabledController(browserGamepad) {
  72543. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72544. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72545. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72546. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72547. /**
  72548. * The device position in babylon space
  72549. */
  72550. _this.devicePosition = BABYLON.Vector3.Zero();
  72551. /**
  72552. * The device rotation in babylon space
  72553. */
  72554. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72555. /**
  72556. * The scale factor of the device in babylon space
  72557. */
  72558. _this.deviceScaleFactor = 1;
  72559. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72560. /**
  72561. * Internal, matrix used to convert room space to babylon space
  72562. */
  72563. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72564. /**
  72565. * Node to be used when casting a ray from the controller
  72566. */
  72567. _this._pointingPoseNode = null;
  72568. _this._workingMatrix = BABYLON.Matrix.Identity();
  72569. /**
  72570. * @hidden
  72571. */
  72572. _this._meshAttachedObservable = new BABYLON.Observable();
  72573. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72574. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72575. _this.position = BABYLON.Vector3.Zero();
  72576. _this.rotationQuaternion = new BABYLON.Quaternion();
  72577. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72578. _this._calculatedRotation = new BABYLON.Quaternion();
  72579. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72580. return _this;
  72581. }
  72582. /**
  72583. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72584. */
  72585. PoseEnabledController.prototype.update = function () {
  72586. _super.prototype.update.call(this);
  72587. this._updatePoseAndMesh();
  72588. };
  72589. /**
  72590. * Updates only the pose device and mesh without doing any button event checking
  72591. */
  72592. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72593. var pose = this.browserGamepad.pose;
  72594. this.updateFromDevice(pose);
  72595. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72596. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72597. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72598. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72599. if (this._mesh) {
  72600. this._mesh.position.copyFrom(this.devicePosition);
  72601. if (this._mesh.rotationQuaternion) {
  72602. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72603. }
  72604. }
  72605. };
  72606. /**
  72607. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72608. * @param poseData raw pose fromthe device
  72609. */
  72610. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72611. if (poseData) {
  72612. this.rawPose = poseData;
  72613. if (poseData.position) {
  72614. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72615. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72616. this._deviceRoomPosition.z *= -1;
  72617. }
  72618. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72619. this._calculatedPosition.addInPlace(this.position);
  72620. }
  72621. var pose = this.rawPose;
  72622. if (poseData.orientation && pose.orientation) {
  72623. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72624. if (this._mesh) {
  72625. if (this._mesh.getScene().useRightHandedSystem) {
  72626. this._deviceRoomRotationQuaternion.z *= -1;
  72627. this._deviceRoomRotationQuaternion.w *= -1;
  72628. }
  72629. else {
  72630. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72631. }
  72632. }
  72633. // if the camera is set, rotate to the camera's rotation
  72634. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72635. }
  72636. }
  72637. };
  72638. /**
  72639. * Attaches a mesh to the controller
  72640. * @param mesh the mesh to be attached
  72641. */
  72642. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72643. if (this._mesh) {
  72644. this._mesh.parent = null;
  72645. }
  72646. this._mesh = mesh;
  72647. if (this._poseControlledCamera) {
  72648. this._mesh.parent = this._poseControlledCamera;
  72649. }
  72650. if (!this._mesh.rotationQuaternion) {
  72651. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72652. }
  72653. // 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
  72654. this._updatePoseAndMesh();
  72655. if (this._pointingPoseNode) {
  72656. var parents = [];
  72657. var obj = this._pointingPoseNode;
  72658. while (obj.parent) {
  72659. parents.push(obj.parent);
  72660. obj = obj.parent;
  72661. }
  72662. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72663. }
  72664. this._meshAttachedObservable.notifyObservers(mesh);
  72665. };
  72666. /**
  72667. * Attaches the controllers mesh to a camera
  72668. * @param camera the camera the mesh should be attached to
  72669. */
  72670. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72671. this._poseControlledCamera = camera;
  72672. if (this._mesh) {
  72673. this._mesh.parent = this._poseControlledCamera;
  72674. }
  72675. };
  72676. /**
  72677. * Disposes of the controller
  72678. */
  72679. PoseEnabledController.prototype.dispose = function () {
  72680. if (this._mesh) {
  72681. this._mesh.dispose();
  72682. }
  72683. this._mesh = null;
  72684. _super.prototype.dispose.call(this);
  72685. };
  72686. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72687. /**
  72688. * The mesh that is attached to the controller
  72689. */
  72690. get: function () {
  72691. return this._mesh;
  72692. },
  72693. enumerable: true,
  72694. configurable: true
  72695. });
  72696. /**
  72697. * Gets the ray of the controller in the direction the controller is pointing
  72698. * @param length the length the resulting ray should be
  72699. * @returns a ray in the direction the controller is pointing
  72700. */
  72701. PoseEnabledController.prototype.getForwardRay = function (length) {
  72702. if (length === void 0) { length = 100; }
  72703. if (!this.mesh) {
  72704. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72705. }
  72706. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72707. var origin = m.getTranslation();
  72708. var forward = new BABYLON.Vector3(0, 0, -1);
  72709. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72710. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72711. return new BABYLON.Ray(origin, direction, length);
  72712. };
  72713. /**
  72714. * Name of the child mesh that can be used to cast a ray from the controller
  72715. */
  72716. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72717. return PoseEnabledController;
  72718. }(BABYLON.Gamepad));
  72719. BABYLON.PoseEnabledController = PoseEnabledController;
  72720. })(BABYLON || (BABYLON = {}));
  72721. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72722. var BABYLON;
  72723. (function (BABYLON) {
  72724. /**
  72725. * Defines the WebVRController object that represents controllers tracked in 3D space
  72726. */
  72727. var WebVRController = /** @class */ (function (_super) {
  72728. __extends(WebVRController, _super);
  72729. /**
  72730. * Creates a new WebVRController from a gamepad
  72731. * @param vrGamepad the gamepad that the WebVRController should be created from
  72732. */
  72733. function WebVRController(vrGamepad) {
  72734. var _this = _super.call(this, vrGamepad) || this;
  72735. // Observables
  72736. /**
  72737. * Fired when the trigger state has changed
  72738. */
  72739. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72740. /**
  72741. * Fired when the main button state has changed
  72742. */
  72743. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72744. /**
  72745. * Fired when the secondary button state has changed
  72746. */
  72747. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72748. /**
  72749. * Fired when the pad state has changed
  72750. */
  72751. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72752. /**
  72753. * Fired when controllers stick values have changed
  72754. */
  72755. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72756. /**
  72757. * X and Y axis corrisponding to the controllers joystick
  72758. */
  72759. _this.pad = { x: 0, y: 0 };
  72760. // avoid GC, store state in a tmp object
  72761. _this._changes = {
  72762. pressChanged: false,
  72763. touchChanged: false,
  72764. valueChanged: false,
  72765. changed: false
  72766. };
  72767. _this._buttons = new Array(vrGamepad.buttons.length);
  72768. _this.hand = vrGamepad.hand;
  72769. return _this;
  72770. }
  72771. /**
  72772. * Fired when a controller button's state has changed
  72773. * @param callback the callback containing the button that was modified
  72774. */
  72775. WebVRController.prototype.onButtonStateChange = function (callback) {
  72776. this._onButtonStateChange = callback;
  72777. };
  72778. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72779. /**
  72780. * The default controller model for the controller
  72781. */
  72782. get: function () {
  72783. return this._defaultModel;
  72784. },
  72785. enumerable: true,
  72786. configurable: true
  72787. });
  72788. /**
  72789. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72790. */
  72791. WebVRController.prototype.update = function () {
  72792. _super.prototype.update.call(this);
  72793. for (var index = 0; index < this._buttons.length; index++) {
  72794. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72795. }
  72796. ;
  72797. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72798. this.pad.x = this.leftStick.x;
  72799. this.pad.y = this.leftStick.y;
  72800. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72801. }
  72802. };
  72803. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72804. if (!newState) {
  72805. newState = {
  72806. pressed: false,
  72807. touched: false,
  72808. value: 0
  72809. };
  72810. }
  72811. if (!currentState) {
  72812. this._buttons[buttonIndex] = {
  72813. pressed: newState.pressed,
  72814. touched: newState.touched,
  72815. value: newState.value
  72816. };
  72817. return;
  72818. }
  72819. this._checkChanges(newState, currentState);
  72820. if (this._changes.changed) {
  72821. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72822. this._handleButtonChange(buttonIndex, newState, this._changes);
  72823. }
  72824. this._buttons[buttonIndex].pressed = newState.pressed;
  72825. this._buttons[buttonIndex].touched = newState.touched;
  72826. // oculus triggers are never 0, thou not touched.
  72827. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72828. };
  72829. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72830. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72831. this._changes.touchChanged = newState.touched !== currentState.touched;
  72832. this._changes.valueChanged = newState.value !== currentState.value;
  72833. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72834. return this._changes;
  72835. };
  72836. /**
  72837. * Disposes of th webVRCOntroller
  72838. */
  72839. WebVRController.prototype.dispose = function () {
  72840. _super.prototype.dispose.call(this);
  72841. this.onTriggerStateChangedObservable.clear();
  72842. this.onMainButtonStateChangedObservable.clear();
  72843. this.onSecondaryButtonStateChangedObservable.clear();
  72844. this.onPadStateChangedObservable.clear();
  72845. this.onPadValuesChangedObservable.clear();
  72846. };
  72847. return WebVRController;
  72848. }(BABYLON.PoseEnabledController));
  72849. BABYLON.WebVRController = WebVRController;
  72850. })(BABYLON || (BABYLON = {}));
  72851. //# sourceMappingURL=babylon.webVRController.js.map
  72852. var BABYLON;
  72853. (function (BABYLON) {
  72854. /**
  72855. * Oculus Touch Controller
  72856. */
  72857. var OculusTouchController = /** @class */ (function (_super) {
  72858. __extends(OculusTouchController, _super);
  72859. /**
  72860. * Creates a new OculusTouchController from a gamepad
  72861. * @param vrGamepad the gamepad that the controller should be created from
  72862. */
  72863. function OculusTouchController(vrGamepad) {
  72864. var _this = _super.call(this, vrGamepad) || this;
  72865. /**
  72866. * Fired when the secondary trigger on this controller is modified
  72867. */
  72868. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72869. /**
  72870. * Fired when the thumb rest on this controller is modified
  72871. */
  72872. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72873. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72874. return _this;
  72875. }
  72876. /**
  72877. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72878. * @param scene scene in which to add meshes
  72879. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72880. */
  72881. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72882. var _this = this;
  72883. var meshName;
  72884. // Hand
  72885. if (this.hand === 'left') {
  72886. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72887. }
  72888. else { // Right is the default if no hand is specified
  72889. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72890. }
  72891. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72892. /*
  72893. Parent Mesh name: oculus_touch_left
  72894. - body
  72895. - trigger
  72896. - thumbstick
  72897. - grip
  72898. - button_y
  72899. - button_x
  72900. - button_enter
  72901. */
  72902. _this._defaultModel = newMeshes[1];
  72903. _this.attachToMesh(_this._defaultModel);
  72904. if (meshLoaded) {
  72905. meshLoaded(_this._defaultModel);
  72906. }
  72907. });
  72908. };
  72909. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72910. /**
  72911. * Fired when the A button on this controller is modified
  72912. */
  72913. get: function () {
  72914. if (this.hand === 'right') {
  72915. return this.onMainButtonStateChangedObservable;
  72916. }
  72917. else {
  72918. throw new Error('No A button on left hand');
  72919. }
  72920. },
  72921. enumerable: true,
  72922. configurable: true
  72923. });
  72924. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72925. /**
  72926. * Fired when the B button on this controller is modified
  72927. */
  72928. get: function () {
  72929. if (this.hand === 'right') {
  72930. return this.onSecondaryButtonStateChangedObservable;
  72931. }
  72932. else {
  72933. throw new Error('No B button on left hand');
  72934. }
  72935. },
  72936. enumerable: true,
  72937. configurable: true
  72938. });
  72939. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72940. /**
  72941. * Fired when the X button on this controller is modified
  72942. */
  72943. get: function () {
  72944. if (this.hand === 'left') {
  72945. return this.onMainButtonStateChangedObservable;
  72946. }
  72947. else {
  72948. throw new Error('No X button on right hand');
  72949. }
  72950. },
  72951. enumerable: true,
  72952. configurable: true
  72953. });
  72954. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72955. /**
  72956. * Fired when the Y button on this controller is modified
  72957. */
  72958. get: function () {
  72959. if (this.hand === 'left') {
  72960. return this.onSecondaryButtonStateChangedObservable;
  72961. }
  72962. else {
  72963. throw new Error('No Y button on right hand');
  72964. }
  72965. },
  72966. enumerable: true,
  72967. configurable: true
  72968. });
  72969. /**
  72970. * Called once for each button that changed state since the last frame
  72971. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72972. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72973. * 2) secondary trigger (same)
  72974. * 3) A (right) X (left), touch, pressed = value
  72975. * 4) B / Y
  72976. * 5) thumb rest
  72977. * @param buttonIdx Which button index changed
  72978. * @param state New state of the button
  72979. * @param changes Which properties on the state changed since last frame
  72980. */
  72981. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72982. var notifyObject = state; //{ state: state, changes: changes };
  72983. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72984. switch (buttonIdx) {
  72985. case 0:
  72986. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72987. return;
  72988. case 1: // index trigger
  72989. if (this._defaultModel) {
  72990. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72991. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72992. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72993. }
  72994. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72995. return;
  72996. case 2: // secondary trigger
  72997. if (this._defaultModel) {
  72998. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72999. }
  73000. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73001. return;
  73002. case 3:
  73003. if (this._defaultModel) {
  73004. if (notifyObject.pressed) {
  73005. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73006. }
  73007. else {
  73008. (this._defaultModel.getChildren()[1]).position.y = 0;
  73009. }
  73010. }
  73011. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73012. return;
  73013. case 4:
  73014. if (this._defaultModel) {
  73015. if (notifyObject.pressed) {
  73016. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73017. }
  73018. else {
  73019. (this._defaultModel.getChildren()[2]).position.y = 0;
  73020. }
  73021. }
  73022. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73023. return;
  73024. case 5:
  73025. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73026. return;
  73027. }
  73028. };
  73029. /**
  73030. * Base Url for the controller model.
  73031. */
  73032. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73033. /**
  73034. * File name for the left controller model.
  73035. */
  73036. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73037. /**
  73038. * File name for the right controller model.
  73039. */
  73040. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73041. return OculusTouchController;
  73042. }(BABYLON.WebVRController));
  73043. BABYLON.OculusTouchController = OculusTouchController;
  73044. })(BABYLON || (BABYLON = {}));
  73045. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73046. var BABYLON;
  73047. (function (BABYLON) {
  73048. /**
  73049. * Vive Controller
  73050. */
  73051. var ViveController = /** @class */ (function (_super) {
  73052. __extends(ViveController, _super);
  73053. /**
  73054. * Creates a new ViveController from a gamepad
  73055. * @param vrGamepad the gamepad that the controller should be created from
  73056. */
  73057. function ViveController(vrGamepad) {
  73058. var _this = _super.call(this, vrGamepad) || this;
  73059. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73060. _this._invertLeftStickY = true;
  73061. return _this;
  73062. }
  73063. /**
  73064. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73065. * @param scene scene in which to add meshes
  73066. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73067. */
  73068. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73069. var _this = this;
  73070. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73071. /*
  73072. Parent Mesh name: ViveWand
  73073. - body
  73074. - r_gripper
  73075. - l_gripper
  73076. - menu_button
  73077. - system_button
  73078. - trackpad
  73079. - trigger
  73080. - LED
  73081. */
  73082. _this._defaultModel = newMeshes[1];
  73083. _this.attachToMesh(_this._defaultModel);
  73084. if (meshLoaded) {
  73085. meshLoaded(_this._defaultModel);
  73086. }
  73087. });
  73088. };
  73089. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73090. /**
  73091. * Fired when the left button on this controller is modified
  73092. */
  73093. get: function () {
  73094. return this.onMainButtonStateChangedObservable;
  73095. },
  73096. enumerable: true,
  73097. configurable: true
  73098. });
  73099. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73100. /**
  73101. * Fired when the right button on this controller is modified
  73102. */
  73103. get: function () {
  73104. return this.onMainButtonStateChangedObservable;
  73105. },
  73106. enumerable: true,
  73107. configurable: true
  73108. });
  73109. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73110. /**
  73111. * Fired when the menu button on this controller is modified
  73112. */
  73113. get: function () {
  73114. return this.onSecondaryButtonStateChangedObservable;
  73115. },
  73116. enumerable: true,
  73117. configurable: true
  73118. });
  73119. /**
  73120. * Called once for each button that changed state since the last frame
  73121. * Vive mapping:
  73122. * 0: touchpad
  73123. * 1: trigger
  73124. * 2: left AND right buttons
  73125. * 3: menu button
  73126. * @param buttonIdx Which button index changed
  73127. * @param state New state of the button
  73128. * @param changes Which properties on the state changed since last frame
  73129. */
  73130. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73131. var notifyObject = state; //{ state: state, changes: changes };
  73132. switch (buttonIdx) {
  73133. case 0:
  73134. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73135. return;
  73136. case 1: // index trigger
  73137. if (this._defaultModel) {
  73138. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73139. }
  73140. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73141. return;
  73142. case 2: // left AND right button
  73143. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73144. return;
  73145. case 3:
  73146. if (this._defaultModel) {
  73147. if (notifyObject.pressed) {
  73148. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73149. }
  73150. else {
  73151. (this._defaultModel.getChildren()[2]).position.y = 0;
  73152. }
  73153. }
  73154. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73155. return;
  73156. }
  73157. };
  73158. /**
  73159. * Base Url for the controller model.
  73160. */
  73161. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73162. /**
  73163. * File name for the controller model.
  73164. */
  73165. ViveController.MODEL_FILENAME = 'wand.babylon';
  73166. return ViveController;
  73167. }(BABYLON.WebVRController));
  73168. BABYLON.ViveController = ViveController;
  73169. })(BABYLON || (BABYLON = {}));
  73170. //# sourceMappingURL=babylon.viveController.js.map
  73171. var BABYLON;
  73172. (function (BABYLON) {
  73173. /**
  73174. * Generic Controller
  73175. */
  73176. var GenericController = /** @class */ (function (_super) {
  73177. __extends(GenericController, _super);
  73178. /**
  73179. * Creates a new GenericController from a gamepad
  73180. * @param vrGamepad the gamepad that the controller should be created from
  73181. */
  73182. function GenericController(vrGamepad) {
  73183. return _super.call(this, vrGamepad) || this;
  73184. }
  73185. /**
  73186. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73187. * @param scene scene in which to add meshes
  73188. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73189. */
  73190. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73191. var _this = this;
  73192. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73193. _this._defaultModel = newMeshes[1];
  73194. _this.attachToMesh(_this._defaultModel);
  73195. if (meshLoaded) {
  73196. meshLoaded(_this._defaultModel);
  73197. }
  73198. });
  73199. };
  73200. /**
  73201. * Called once for each button that changed state since the last frame
  73202. * @param buttonIdx Which button index changed
  73203. * @param state New state of the button
  73204. * @param changes Which properties on the state changed since last frame
  73205. */
  73206. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73207. console.log("Button id: " + buttonIdx + "state: ");
  73208. console.dir(state);
  73209. };
  73210. /**
  73211. * Base Url for the controller model.
  73212. */
  73213. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73214. /**
  73215. * File name for the controller model.
  73216. */
  73217. GenericController.MODEL_FILENAME = 'generic.babylon';
  73218. return GenericController;
  73219. }(BABYLON.WebVRController));
  73220. BABYLON.GenericController = GenericController;
  73221. })(BABYLON || (BABYLON = {}));
  73222. //# sourceMappingURL=babylon.genericController.js.map
  73223. var BABYLON;
  73224. (function (BABYLON) {
  73225. /**
  73226. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73227. */
  73228. var LoadedMeshInfo = /** @class */ (function () {
  73229. function LoadedMeshInfo() {
  73230. /**
  73231. * Map of the button meshes contained in the controller
  73232. */
  73233. this.buttonMeshes = {};
  73234. /**
  73235. * Map of the axis meshes contained in the controller
  73236. */
  73237. this.axisMeshes = {};
  73238. }
  73239. return LoadedMeshInfo;
  73240. }());
  73241. /**
  73242. * Defines the WindowsMotionController object that the state of the windows motion controller
  73243. */
  73244. var WindowsMotionController = /** @class */ (function (_super) {
  73245. __extends(WindowsMotionController, _super);
  73246. /**
  73247. * Creates a new WindowsMotionController from a gamepad
  73248. * @param vrGamepad the gamepad that the controller should be created from
  73249. */
  73250. function WindowsMotionController(vrGamepad) {
  73251. var _this = _super.call(this, vrGamepad) || this;
  73252. _this._mapping = {
  73253. // Semantic button names
  73254. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73255. // A mapping of the button name to glTF model node name
  73256. // that should be transformed by button value.
  73257. buttonMeshNames: {
  73258. 'trigger': 'SELECT',
  73259. 'menu': 'MENU',
  73260. 'grip': 'GRASP',
  73261. 'thumbstick': 'THUMBSTICK_PRESS',
  73262. 'trackpad': 'TOUCHPAD_PRESS'
  73263. },
  73264. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73265. buttonObservableNames: {
  73266. 'trigger': 'onTriggerStateChangedObservable',
  73267. 'menu': 'onSecondaryButtonStateChangedObservable',
  73268. 'grip': 'onMainButtonStateChangedObservable',
  73269. 'thumbstick': 'onPadStateChangedObservable',
  73270. 'trackpad': 'onTrackpadChangedObservable'
  73271. },
  73272. // A mapping of the axis name to glTF model node name
  73273. // that should be transformed by axis value.
  73274. // This array mirrors the browserGamepad.axes array, such that
  73275. // the mesh corresponding to axis 0 is in this array index 0.
  73276. axisMeshNames: [
  73277. 'THUMBSTICK_X',
  73278. 'THUMBSTICK_Y',
  73279. 'TOUCHPAD_TOUCH_X',
  73280. 'TOUCHPAD_TOUCH_Y'
  73281. ],
  73282. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73283. };
  73284. /**
  73285. * Fired when the trackpad on this controller is clicked
  73286. */
  73287. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73288. /**
  73289. * Fired when the trackpad on this controller is modified
  73290. */
  73291. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73292. /**
  73293. * The current x and y values of this controller's trackpad
  73294. */
  73295. _this.trackpad = { x: 0, y: 0 };
  73296. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73297. _this._loadedMeshInfo = null;
  73298. return _this;
  73299. }
  73300. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73301. /**
  73302. * Fired when the trigger on this controller is modified
  73303. */
  73304. get: function () {
  73305. return this.onTriggerStateChangedObservable;
  73306. },
  73307. enumerable: true,
  73308. configurable: true
  73309. });
  73310. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73311. /**
  73312. * Fired when the menu button on this controller is modified
  73313. */
  73314. get: function () {
  73315. return this.onSecondaryButtonStateChangedObservable;
  73316. },
  73317. enumerable: true,
  73318. configurable: true
  73319. });
  73320. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73321. /**
  73322. * Fired when the grip button on this controller is modified
  73323. */
  73324. get: function () {
  73325. return this.onMainButtonStateChangedObservable;
  73326. },
  73327. enumerable: true,
  73328. configurable: true
  73329. });
  73330. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73331. /**
  73332. * Fired when the thumbstick button on this controller is modified
  73333. */
  73334. get: function () {
  73335. return this.onPadStateChangedObservable;
  73336. },
  73337. enumerable: true,
  73338. configurable: true
  73339. });
  73340. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73341. /**
  73342. * Fired when the touchpad button on this controller is modified
  73343. */
  73344. get: function () {
  73345. return this.onTrackpadChangedObservable;
  73346. },
  73347. enumerable: true,
  73348. configurable: true
  73349. });
  73350. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73351. /**
  73352. * Fired when the touchpad values on this controller are modified
  73353. */
  73354. get: function () {
  73355. return this.onTrackpadValuesChangedObservable;
  73356. },
  73357. enumerable: true,
  73358. configurable: true
  73359. });
  73360. WindowsMotionController.prototype._updateTrackpad = function () {
  73361. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73362. this.trackpad.x = this.browserGamepad["axes"][2];
  73363. this.trackpad.y = this.browserGamepad["axes"][3];
  73364. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73365. }
  73366. };
  73367. /**
  73368. * Called once per frame by the engine.
  73369. */
  73370. WindowsMotionController.prototype.update = function () {
  73371. _super.prototype.update.call(this);
  73372. if (this.browserGamepad.axes) {
  73373. this._updateTrackpad();
  73374. // Only need to animate axes if there is a loaded mesh
  73375. if (this._loadedMeshInfo) {
  73376. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73377. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73378. }
  73379. }
  73380. }
  73381. };
  73382. /**
  73383. * Called once for each button that changed state since the last frame
  73384. * @param buttonIdx Which button index changed
  73385. * @param state New state of the button
  73386. * @param changes Which properties on the state changed since last frame
  73387. */
  73388. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73389. var buttonName = this._mapping.buttons[buttonIdx];
  73390. if (!buttonName) {
  73391. return;
  73392. }
  73393. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73394. this._updateTrackpad();
  73395. // Only emit events for buttons that we know how to map from index to name
  73396. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73397. if (observable) {
  73398. observable.notifyObservers(state);
  73399. }
  73400. this._lerpButtonTransform(buttonName, state.value);
  73401. };
  73402. /**
  73403. * Moves the buttons on the controller mesh based on their current state
  73404. * @param buttonName the name of the button to move
  73405. * @param buttonValue the value of the button which determines the buttons new position
  73406. */
  73407. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73408. // If there is no loaded mesh, there is nothing to transform.
  73409. if (!this._loadedMeshInfo) {
  73410. return;
  73411. }
  73412. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73413. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73414. return;
  73415. }
  73416. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73417. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73418. };
  73419. /**
  73420. * Moves the axis on the controller mesh based on its current state
  73421. * @param axis the index of the axis
  73422. * @param axisValue the value of the axis which determines the meshes new position
  73423. * @hidden
  73424. */
  73425. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73426. if (!this._loadedMeshInfo) {
  73427. return;
  73428. }
  73429. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73430. if (!meshInfo) {
  73431. return;
  73432. }
  73433. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73434. return;
  73435. }
  73436. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73437. var lerpValue = axisValue * 0.5 + 0.5;
  73438. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73439. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73440. };
  73441. /**
  73442. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73443. * @param scene scene in which to add meshes
  73444. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73445. */
  73446. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73447. var _this = this;
  73448. if (forceDefault === void 0) { forceDefault = false; }
  73449. var path;
  73450. var filename;
  73451. // Checking if GLB loader is present
  73452. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73453. // Determine the device specific folder based on the ID suffix
  73454. var device = 'default';
  73455. if (this.id && !forceDefault) {
  73456. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73457. device = ((match && match[0]) || device);
  73458. }
  73459. // Hand
  73460. if (this.hand === 'left') {
  73461. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73462. }
  73463. else { // Right is the default if no hand is specified
  73464. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73465. }
  73466. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73467. }
  73468. else {
  73469. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73470. path = BABYLON.GenericController.MODEL_BASE_URL;
  73471. filename = BABYLON.GenericController.MODEL_FILENAME;
  73472. }
  73473. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73474. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73475. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73476. if (!_this._loadedMeshInfo) {
  73477. return;
  73478. }
  73479. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73480. _this.attachToMesh(_this._defaultModel);
  73481. if (meshLoaded) {
  73482. meshLoaded(_this._defaultModel);
  73483. }
  73484. }, null, function (scene, message) {
  73485. BABYLON.Tools.Log(message);
  73486. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73487. if (!forceDefault) {
  73488. _this.initControllerMesh(scene, meshLoaded, true);
  73489. }
  73490. });
  73491. };
  73492. /**
  73493. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73494. * can be transformed by button presses and axes values, based on this._mapping.
  73495. *
  73496. * @param scene scene in which the meshes exist
  73497. * @param meshes list of meshes that make up the controller model to process
  73498. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73499. */
  73500. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73501. var loadedMeshInfo = null;
  73502. // Create a new mesh to contain the glTF hierarchy
  73503. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73504. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73505. var childMesh = null;
  73506. for (var i = 0; i < meshes.length; i++) {
  73507. var mesh = meshes[i];
  73508. if (!mesh.parent) {
  73509. // Exclude controller meshes from picking results
  73510. mesh.isPickable = false;
  73511. // Handle root node, attach to the new parentMesh
  73512. childMesh = mesh;
  73513. break;
  73514. }
  73515. }
  73516. if (childMesh) {
  73517. childMesh.setParent(parentMesh);
  73518. // Create our mesh info. Note that this method will always return non-null.
  73519. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73520. }
  73521. else {
  73522. BABYLON.Tools.Warn('Could not find root node in model file.');
  73523. }
  73524. return loadedMeshInfo;
  73525. };
  73526. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73527. var loadedMeshInfo = new LoadedMeshInfo();
  73528. var i;
  73529. loadedMeshInfo.rootNode = rootNode;
  73530. // Reset the caches
  73531. loadedMeshInfo.buttonMeshes = {};
  73532. loadedMeshInfo.axisMeshes = {};
  73533. // Button Meshes
  73534. for (i = 0; i < this._mapping.buttons.length; i++) {
  73535. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73536. if (!buttonMeshName) {
  73537. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73538. continue;
  73539. }
  73540. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73541. if (!buttonMesh) {
  73542. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73543. continue;
  73544. }
  73545. var buttonMeshInfo = {
  73546. index: i,
  73547. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73548. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73549. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73550. };
  73551. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73552. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73553. }
  73554. else {
  73555. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73556. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73557. '(VALUE: ' + !!buttonMeshInfo.value +
  73558. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73559. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73560. ')');
  73561. }
  73562. }
  73563. // Axis Meshes
  73564. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73565. var axisMeshName = this._mapping.axisMeshNames[i];
  73566. if (!axisMeshName) {
  73567. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73568. continue;
  73569. }
  73570. var axisMesh = getChildByName(rootNode, axisMeshName);
  73571. if (!axisMesh) {
  73572. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73573. continue;
  73574. }
  73575. var axisMeshInfo = {
  73576. index: i,
  73577. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73578. min: getImmediateChildByName(axisMesh, 'MIN'),
  73579. max: getImmediateChildByName(axisMesh, 'MAX')
  73580. };
  73581. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73582. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73583. }
  73584. else {
  73585. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73586. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73587. '(VALUE: ' + !!axisMeshInfo.value +
  73588. ', MIN: ' + !!axisMeshInfo.min +
  73589. ', MAX:' + !!axisMeshInfo.max +
  73590. ')');
  73591. }
  73592. }
  73593. // Pointing Ray
  73594. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73595. if (!loadedMeshInfo.pointingPoseNode) {
  73596. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73597. }
  73598. else {
  73599. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73600. }
  73601. return loadedMeshInfo;
  73602. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73603. function getChildByName(node, name) {
  73604. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73605. }
  73606. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73607. function getImmediateChildByName(node, name) {
  73608. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73609. }
  73610. };
  73611. /**
  73612. * Gets the ray of the controller in the direction the controller is pointing
  73613. * @param length the length the resulting ray should be
  73614. * @returns a ray in the direction the controller is pointing
  73615. */
  73616. WindowsMotionController.prototype.getForwardRay = function (length) {
  73617. if (length === void 0) { length = 100; }
  73618. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73619. return _super.prototype.getForwardRay.call(this, length);
  73620. }
  73621. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73622. var origin = m.getTranslation();
  73623. var forward = new BABYLON.Vector3(0, 0, -1);
  73624. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73625. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73626. return new BABYLON.Ray(origin, direction, length);
  73627. };
  73628. /**
  73629. * Disposes of the controller
  73630. */
  73631. WindowsMotionController.prototype.dispose = function () {
  73632. _super.prototype.dispose.call(this);
  73633. this.onTrackpadChangedObservable.clear();
  73634. };
  73635. /**
  73636. * The base url used to load the left and right controller models
  73637. */
  73638. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73639. /**
  73640. * The name of the left controller model file
  73641. */
  73642. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73643. /**
  73644. * The name of the right controller model file
  73645. */
  73646. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73647. /**
  73648. * The controller name prefix for this controller type
  73649. */
  73650. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73651. /**
  73652. * The controller id pattern for this controller type
  73653. */
  73654. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73655. return WindowsMotionController;
  73656. }(BABYLON.WebVRController));
  73657. BABYLON.WindowsMotionController = WindowsMotionController;
  73658. })(BABYLON || (BABYLON = {}));
  73659. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73660. var BABYLON;
  73661. (function (BABYLON) {
  73662. /**
  73663. * Gear VR Controller
  73664. */
  73665. var GearVRController = /** @class */ (function (_super) {
  73666. __extends(GearVRController, _super);
  73667. /**
  73668. * Creates a new GearVRController from a gamepad
  73669. * @param vrGamepad the gamepad that the controller should be created from
  73670. */
  73671. function GearVRController(vrGamepad) {
  73672. var _this = _super.call(this, vrGamepad) || this;
  73673. _this._maxRotationDistFromHeadset = Math.PI / 5;
  73674. _this._draggedRoomRotation = 0;
  73675. _this._tmpVector = new BABYLON.Vector3();
  73676. _this._buttonIndexToObservableNameMap = [
  73677. 'onTrackpadChangedObservable',
  73678. 'onTriggerStateChangedObservable' // Trigger
  73679. ];
  73680. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73681. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73682. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  73683. return _this;
  73684. }
  73685. /**
  73686. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73687. * @param poseData raw pose fromthe device
  73688. */
  73689. GearVRController.prototype.updateFromDevice = function (poseData) {
  73690. _super.prototype.updateFromDevice.call(this, poseData);
  73691. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  73692. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  73693. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  73694. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  73695. // Find the radian distance away that the headset is from the controllers rotation
  73696. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  73697. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  73698. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  73699. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  73700. this._draggedRoomRotation += rotationAmount;
  73701. // Rotate controller around headset
  73702. var sin = Math.sin(-rotationAmount);
  73703. var cos = Math.cos(-rotationAmount);
  73704. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  73705. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  73706. }
  73707. }
  73708. }
  73709. };
  73710. /**
  73711. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73712. * @param scene scene in which to add meshes
  73713. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73714. */
  73715. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73716. var _this = this;
  73717. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73718. // Offset the controller so it will rotate around the users wrist
  73719. var mesh = new BABYLON.Mesh("", scene);
  73720. newMeshes[1].parent = mesh;
  73721. newMeshes[1].position.z = -0.15;
  73722. _this._defaultModel = mesh;
  73723. _this.attachToMesh(_this._defaultModel);
  73724. if (meshLoaded) {
  73725. meshLoaded(_this._defaultModel);
  73726. }
  73727. });
  73728. };
  73729. /**
  73730. * Called once for each button that changed state since the last frame
  73731. * @param buttonIdx Which button index changed
  73732. * @param state New state of the button
  73733. * @param changes Which properties on the state changed since last frame
  73734. */
  73735. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73736. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73737. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73738. // Only emit events for buttons that we know how to map from index to observable
  73739. var observable = this[observableName];
  73740. if (observable) {
  73741. observable.notifyObservers(state);
  73742. }
  73743. }
  73744. };
  73745. /**
  73746. * Base Url for the controller model.
  73747. */
  73748. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73749. /**
  73750. * File name for the controller model.
  73751. */
  73752. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73753. /**
  73754. * Gamepad Id prefix used to identify this controller.
  73755. */
  73756. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73757. return GearVRController;
  73758. }(BABYLON.WebVRController));
  73759. BABYLON.GearVRController = GearVRController;
  73760. })(BABYLON || (BABYLON = {}));
  73761. //# sourceMappingURL=babylon.gearVRController.js.map
  73762. var BABYLON;
  73763. (function (BABYLON) {
  73764. /**
  73765. * Google Daydream controller
  73766. */
  73767. var DaydreamController = /** @class */ (function (_super) {
  73768. __extends(DaydreamController, _super);
  73769. /**
  73770. * Creates a new DaydreamController from a gamepad
  73771. * @param vrGamepad the gamepad that the controller should be created from
  73772. */
  73773. function DaydreamController(vrGamepad) {
  73774. var _this = _super.call(this, vrGamepad) || this;
  73775. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73776. return _this;
  73777. }
  73778. /**
  73779. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73780. * @param scene scene in which to add meshes
  73781. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73782. */
  73783. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73784. var _this = this;
  73785. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73786. _this._defaultModel = newMeshes[1];
  73787. _this.attachToMesh(_this._defaultModel);
  73788. if (meshLoaded) {
  73789. meshLoaded(_this._defaultModel);
  73790. }
  73791. });
  73792. };
  73793. /**
  73794. * Called once for each button that changed state since the last frame
  73795. * @param buttonIdx Which button index changed
  73796. * @param state New state of the button
  73797. * @param changes Which properties on the state changed since last frame
  73798. */
  73799. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73800. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73801. if (buttonIdx === 0) {
  73802. var observable = this.onTriggerStateChangedObservable;
  73803. if (observable) {
  73804. observable.notifyObservers(state);
  73805. }
  73806. }
  73807. else {
  73808. // If the app or home buttons are ever made available
  73809. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73810. }
  73811. };
  73812. /**
  73813. * Base Url for the controller model.
  73814. */
  73815. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73816. /**
  73817. * File name for the controller model.
  73818. */
  73819. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73820. /**
  73821. * Gamepad Id prefix used to identify Daydream Controller.
  73822. */
  73823. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73824. return DaydreamController;
  73825. }(BABYLON.WebVRController));
  73826. BABYLON.DaydreamController = DaydreamController;
  73827. })(BABYLON || (BABYLON = {}));
  73828. //# sourceMappingURL=babylon.daydreamController.js.map
  73829. var BABYLON;
  73830. (function (BABYLON) {
  73831. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  73832. get: function () {
  73833. if (!this._gamepadManager) {
  73834. this._gamepadManager = new BABYLON.GamepadManager(this);
  73835. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  73836. if (!component) {
  73837. component = new GamepadSystemSceneComponent(this);
  73838. this._addComponent(component);
  73839. }
  73840. }
  73841. return this._gamepadManager;
  73842. },
  73843. enumerable: true,
  73844. configurable: true
  73845. });
  73846. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  73847. this.add(new BABYLON.FreeCameraGamepadInput());
  73848. return this;
  73849. };
  73850. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  73851. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  73852. return this;
  73853. };
  73854. /**
  73855. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  73856. */
  73857. var GamepadSystemSceneComponent = /** @class */ (function () {
  73858. /**
  73859. * Creates a new instance of the component for the given scene
  73860. * @param scene Defines the scene to register the component in
  73861. */
  73862. function GamepadSystemSceneComponent(scene) {
  73863. /**
  73864. * The component name helpfull to identify the component in the list of scene components.
  73865. */
  73866. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  73867. this.scene = scene;
  73868. }
  73869. /**
  73870. * Registers the component in a given scene
  73871. */
  73872. GamepadSystemSceneComponent.prototype.register = function () {
  73873. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  73874. };
  73875. /**
  73876. * Rebuilds the elements related to this component in case of
  73877. * context lost for instance.
  73878. */
  73879. GamepadSystemSceneComponent.prototype.rebuild = function () {
  73880. // Nothing to do for gamepads
  73881. };
  73882. /**
  73883. * Disposes the component and the associated ressources
  73884. */
  73885. GamepadSystemSceneComponent.prototype.dispose = function () {
  73886. var gamepadManager = this.scene._gamepadManager;
  73887. if (gamepadManager) {
  73888. gamepadManager.dispose();
  73889. this.scene._gamepadManager = null;
  73890. }
  73891. };
  73892. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  73893. var gamepadManager = this.scene._gamepadManager;
  73894. if (gamepadManager && gamepadManager._isMonitoring) {
  73895. gamepadManager._checkGamepadsStatus();
  73896. }
  73897. };
  73898. return GamepadSystemSceneComponent;
  73899. }());
  73900. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  73901. })(BABYLON || (BABYLON = {}));
  73902. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  73903. var BABYLON;
  73904. (function (BABYLON) {
  73905. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  73906. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  73907. });
  73908. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  73909. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  73910. });
  73911. var FollowCamera = /** @class */ (function (_super) {
  73912. __extends(FollowCamera, _super);
  73913. function FollowCamera(name, position, scene, lockedTarget) {
  73914. if (lockedTarget === void 0) { lockedTarget = null; }
  73915. var _this = _super.call(this, name, position, scene) || this;
  73916. _this.radius = 12;
  73917. _this.rotationOffset = 0;
  73918. _this.heightOffset = 4;
  73919. _this.cameraAcceleration = 0.05;
  73920. _this.maxCameraSpeed = 20;
  73921. _this.lockedTarget = lockedTarget;
  73922. return _this;
  73923. }
  73924. FollowCamera.prototype.getRadians = function (degrees) {
  73925. return degrees * Math.PI / 180;
  73926. };
  73927. FollowCamera.prototype.follow = function (cameraTarget) {
  73928. if (!cameraTarget)
  73929. return;
  73930. var yRotation;
  73931. if (cameraTarget.rotationQuaternion) {
  73932. var rotMatrix = new BABYLON.Matrix();
  73933. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73934. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73935. }
  73936. else {
  73937. yRotation = cameraTarget.rotation.y;
  73938. }
  73939. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73940. var targetPosition = cameraTarget.getAbsolutePosition();
  73941. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73942. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73943. var dx = targetX - this.position.x;
  73944. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73945. var dz = (targetZ) - this.position.z;
  73946. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73947. var vy = dy * this.cameraAcceleration;
  73948. var vz = dz * this.cameraAcceleration * 2;
  73949. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73950. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73951. }
  73952. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73953. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73954. }
  73955. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73956. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73957. }
  73958. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73959. this.setTarget(targetPosition);
  73960. };
  73961. FollowCamera.prototype._checkInputs = function () {
  73962. _super.prototype._checkInputs.call(this);
  73963. if (this.lockedTarget) {
  73964. this.follow(this.lockedTarget);
  73965. }
  73966. };
  73967. FollowCamera.prototype.getClassName = function () {
  73968. return "FollowCamera";
  73969. };
  73970. __decorate([
  73971. BABYLON.serialize()
  73972. ], FollowCamera.prototype, "radius", void 0);
  73973. __decorate([
  73974. BABYLON.serialize()
  73975. ], FollowCamera.prototype, "rotationOffset", void 0);
  73976. __decorate([
  73977. BABYLON.serialize()
  73978. ], FollowCamera.prototype, "heightOffset", void 0);
  73979. __decorate([
  73980. BABYLON.serialize()
  73981. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73982. __decorate([
  73983. BABYLON.serialize()
  73984. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73985. __decorate([
  73986. BABYLON.serializeAsMeshReference("lockedTargetId")
  73987. ], FollowCamera.prototype, "lockedTarget", void 0);
  73988. return FollowCamera;
  73989. }(BABYLON.TargetCamera));
  73990. BABYLON.FollowCamera = FollowCamera;
  73991. var ArcFollowCamera = /** @class */ (function (_super) {
  73992. __extends(ArcFollowCamera, _super);
  73993. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73994. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73995. _this.alpha = alpha;
  73996. _this.beta = beta;
  73997. _this.radius = radius;
  73998. _this.target = target;
  73999. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74000. _this.follow();
  74001. return _this;
  74002. }
  74003. ArcFollowCamera.prototype.follow = function () {
  74004. if (!this.target) {
  74005. return;
  74006. }
  74007. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74008. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74009. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74010. var targetPosition = this.target.getAbsolutePosition();
  74011. this.position = targetPosition.add(this._cartesianCoordinates);
  74012. this.setTarget(targetPosition);
  74013. };
  74014. ArcFollowCamera.prototype._checkInputs = function () {
  74015. _super.prototype._checkInputs.call(this);
  74016. this.follow();
  74017. };
  74018. ArcFollowCamera.prototype.getClassName = function () {
  74019. return "ArcFollowCamera";
  74020. };
  74021. return ArcFollowCamera;
  74022. }(BABYLON.TargetCamera));
  74023. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74024. })(BABYLON || (BABYLON = {}));
  74025. //# sourceMappingURL=babylon.followCamera.js.map
  74026. var BABYLON;
  74027. (function (BABYLON) {
  74028. // We're mainly based on the logic defined into the FreeCamera code
  74029. var UniversalCamera = /** @class */ (function (_super) {
  74030. __extends(UniversalCamera, _super);
  74031. //-- end properties for backward compatibility for inputs
  74032. function UniversalCamera(name, position, scene) {
  74033. var _this = _super.call(this, name, position, scene) || this;
  74034. _this.inputs.addGamepad();
  74035. return _this;
  74036. }
  74037. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74038. //-- Begin properties for backward compatibility for inputs
  74039. get: function () {
  74040. var gamepad = this.inputs.attached["gamepad"];
  74041. if (gamepad)
  74042. return gamepad.gamepadAngularSensibility;
  74043. return 0;
  74044. },
  74045. set: function (value) {
  74046. var gamepad = this.inputs.attached["gamepad"];
  74047. if (gamepad)
  74048. gamepad.gamepadAngularSensibility = value;
  74049. },
  74050. enumerable: true,
  74051. configurable: true
  74052. });
  74053. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74054. get: function () {
  74055. var gamepad = this.inputs.attached["gamepad"];
  74056. if (gamepad)
  74057. return gamepad.gamepadMoveSensibility;
  74058. return 0;
  74059. },
  74060. set: function (value) {
  74061. var gamepad = this.inputs.attached["gamepad"];
  74062. if (gamepad)
  74063. gamepad.gamepadMoveSensibility = value;
  74064. },
  74065. enumerable: true,
  74066. configurable: true
  74067. });
  74068. UniversalCamera.prototype.getClassName = function () {
  74069. return "UniversalCamera";
  74070. };
  74071. return UniversalCamera;
  74072. }(BABYLON.TouchCamera));
  74073. BABYLON.UniversalCamera = UniversalCamera;
  74074. })(BABYLON || (BABYLON = {}));
  74075. //# sourceMappingURL=babylon.universalCamera.js.map
  74076. var BABYLON;
  74077. (function (BABYLON) {
  74078. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74079. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74080. });
  74081. // We're mainly based on the logic defined into the FreeCamera code
  74082. var GamepadCamera = /** @class */ (function (_super) {
  74083. __extends(GamepadCamera, _super);
  74084. //-- end properties for backward compatibility for inputs
  74085. function GamepadCamera(name, position, scene) {
  74086. return _super.call(this, name, position, scene) || this;
  74087. }
  74088. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74089. //-- Begin properties for backward compatibility for inputs
  74090. get: function () {
  74091. var gamepad = this.inputs.attached["gamepad"];
  74092. if (gamepad)
  74093. return gamepad.gamepadAngularSensibility;
  74094. return 0;
  74095. },
  74096. set: function (value) {
  74097. var gamepad = this.inputs.attached["gamepad"];
  74098. if (gamepad)
  74099. gamepad.gamepadAngularSensibility = value;
  74100. },
  74101. enumerable: true,
  74102. configurable: true
  74103. });
  74104. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74105. get: function () {
  74106. var gamepad = this.inputs.attached["gamepad"];
  74107. if (gamepad)
  74108. return gamepad.gamepadMoveSensibility;
  74109. return 0;
  74110. },
  74111. set: function (value) {
  74112. var gamepad = this.inputs.attached["gamepad"];
  74113. if (gamepad)
  74114. gamepad.gamepadMoveSensibility = value;
  74115. },
  74116. enumerable: true,
  74117. configurable: true
  74118. });
  74119. GamepadCamera.prototype.getClassName = function () {
  74120. return "GamepadCamera";
  74121. };
  74122. return GamepadCamera;
  74123. }(BABYLON.UniversalCamera));
  74124. BABYLON.GamepadCamera = GamepadCamera;
  74125. })(BABYLON || (BABYLON = {}));
  74126. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74127. var BABYLON;
  74128. (function (BABYLON) {
  74129. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74130. function PostProcessRenderPipelineManager() {
  74131. this._renderPipelines = {};
  74132. }
  74133. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74134. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74135. };
  74136. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74137. if (unique === void 0) { unique = false; }
  74138. var renderPipeline = this._renderPipelines[renderPipelineName];
  74139. if (!renderPipeline) {
  74140. return;
  74141. }
  74142. renderPipeline._attachCameras(cameras, unique);
  74143. };
  74144. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74145. var renderPipeline = this._renderPipelines[renderPipelineName];
  74146. if (!renderPipeline) {
  74147. return;
  74148. }
  74149. renderPipeline._detachCameras(cameras);
  74150. };
  74151. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74152. var renderPipeline = this._renderPipelines[renderPipelineName];
  74153. if (!renderPipeline) {
  74154. return;
  74155. }
  74156. renderPipeline._enableEffect(renderEffectName, cameras);
  74157. };
  74158. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74159. var renderPipeline = this._renderPipelines[renderPipelineName];
  74160. if (!renderPipeline) {
  74161. return;
  74162. }
  74163. renderPipeline._disableEffect(renderEffectName, cameras);
  74164. };
  74165. PostProcessRenderPipelineManager.prototype.update = function () {
  74166. for (var renderPipelineName in this._renderPipelines) {
  74167. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74168. var pipeline = this._renderPipelines[renderPipelineName];
  74169. if (!pipeline.isSupported) {
  74170. pipeline.dispose();
  74171. delete this._renderPipelines[renderPipelineName];
  74172. }
  74173. else {
  74174. pipeline._update();
  74175. }
  74176. }
  74177. }
  74178. };
  74179. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74180. for (var renderPipelineName in this._renderPipelines) {
  74181. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74182. var pipeline = this._renderPipelines[renderPipelineName];
  74183. pipeline._rebuild();
  74184. }
  74185. }
  74186. };
  74187. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74188. for (var renderPipelineName in this._renderPipelines) {
  74189. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74190. var pipeline = this._renderPipelines[renderPipelineName];
  74191. pipeline.dispose();
  74192. }
  74193. }
  74194. };
  74195. return PostProcessRenderPipelineManager;
  74196. }());
  74197. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74198. })(BABYLON || (BABYLON = {}));
  74199. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74200. var BABYLON;
  74201. (function (BABYLON) {
  74202. /**
  74203. * This represents a set of one or more post processes in Babylon.
  74204. * A post process can be used to apply a shader to a texture after it is rendered.
  74205. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74206. */
  74207. var PostProcessRenderEffect = /** @class */ (function () {
  74208. /**
  74209. * Instantiates a post process render effect.
  74210. * A post process can be used to apply a shader to a texture after it is rendered.
  74211. * @param engine The engine the effect is tied to
  74212. * @param name The name of the effect
  74213. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74214. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74215. */
  74216. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74217. this._name = name;
  74218. this._singleInstance = singleInstance || true;
  74219. this._getPostProcesses = getPostProcesses;
  74220. this._cameras = {};
  74221. this._indicesForCamera = {};
  74222. this._postProcesses = {};
  74223. }
  74224. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74225. /**
  74226. * Checks if all the post processes in the effect are supported.
  74227. */
  74228. get: function () {
  74229. for (var index in this._postProcesses) {
  74230. if (this._postProcesses.hasOwnProperty(index)) {
  74231. var pps = this._postProcesses[index];
  74232. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74233. if (!pps[ppIndex].isSupported) {
  74234. return false;
  74235. }
  74236. }
  74237. }
  74238. }
  74239. return true;
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. /**
  74245. * Updates the current state of the effect
  74246. */
  74247. PostProcessRenderEffect.prototype._update = function () {
  74248. };
  74249. /**
  74250. * Attaches the effect on cameras
  74251. * @param cameras The camera to attach to.
  74252. */
  74253. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74254. var _this = this;
  74255. var cameraKey;
  74256. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74257. if (!cams) {
  74258. return;
  74259. }
  74260. for (var i = 0; i < cams.length; i++) {
  74261. var camera = cams[i];
  74262. var cameraName = camera.name;
  74263. if (this._singleInstance) {
  74264. cameraKey = 0;
  74265. }
  74266. else {
  74267. cameraKey = cameraName;
  74268. }
  74269. if (!this._postProcesses[cameraKey]) {
  74270. var postProcess = this._getPostProcesses();
  74271. if (postProcess) {
  74272. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74273. }
  74274. }
  74275. if (!this._indicesForCamera[cameraName]) {
  74276. this._indicesForCamera[cameraName] = [];
  74277. }
  74278. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74279. var index = camera.attachPostProcess(postProcess);
  74280. _this._indicesForCamera[cameraName].push(index);
  74281. });
  74282. if (!this._cameras[cameraName]) {
  74283. this._cameras[cameraName] = camera;
  74284. }
  74285. }
  74286. };
  74287. /**
  74288. * Detatches the effect on cameras
  74289. * @param cameras The camera to detatch from.
  74290. */
  74291. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74292. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74293. if (!cams) {
  74294. return;
  74295. }
  74296. for (var i = 0; i < cams.length; i++) {
  74297. var camera = cams[i];
  74298. var cameraName = camera.name;
  74299. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74300. camera.detachPostProcess(postProcess);
  74301. });
  74302. if (this._cameras[cameraName]) {
  74303. //this._indicesForCamera.splice(index, 1);
  74304. this._cameras[cameraName] = null;
  74305. }
  74306. }
  74307. };
  74308. /**
  74309. * Enables the effect on given cameras
  74310. * @param cameras The camera to enable.
  74311. */
  74312. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74313. var _this = this;
  74314. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74315. if (!cams) {
  74316. return;
  74317. }
  74318. for (var i = 0; i < cams.length; i++) {
  74319. var camera = cams[i];
  74320. var cameraName = camera.name;
  74321. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74322. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74323. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74324. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74325. });
  74326. }
  74327. }
  74328. }
  74329. };
  74330. /**
  74331. * Disables the effect on the given cameras
  74332. * @param cameras The camera to disable.
  74333. */
  74334. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74335. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74336. if (!cams) {
  74337. return;
  74338. }
  74339. for (var i = 0; i < cams.length; i++) {
  74340. var camera = cams[i];
  74341. var cameraName = camera.name;
  74342. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74343. camera.detachPostProcess(postProcess);
  74344. });
  74345. }
  74346. };
  74347. /**
  74348. * Gets a list of the post processes contained in the effect.
  74349. * @param camera The camera to get the post processes on.
  74350. * @returns The list of the post processes in the effect.
  74351. */
  74352. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74353. if (this._singleInstance) {
  74354. return this._postProcesses[0];
  74355. }
  74356. else {
  74357. if (!camera) {
  74358. return null;
  74359. }
  74360. return this._postProcesses[camera.name];
  74361. }
  74362. };
  74363. return PostProcessRenderEffect;
  74364. }());
  74365. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74366. })(BABYLON || (BABYLON = {}));
  74367. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74368. var BABYLON;
  74369. (function (BABYLON) {
  74370. var PostProcessRenderPipeline = /** @class */ (function () {
  74371. function PostProcessRenderPipeline(engine, name) {
  74372. this.engine = engine;
  74373. this._name = name;
  74374. this._renderEffects = {};
  74375. this._renderEffectsForIsolatedPass = new Array();
  74376. this._cameras = [];
  74377. }
  74378. PostProcessRenderPipeline.prototype.getClassName = function () {
  74379. return "PostProcessRenderPipeline";
  74380. };
  74381. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74382. get: function () {
  74383. for (var renderEffectName in this._renderEffects) {
  74384. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74385. if (!this._renderEffects[renderEffectName].isSupported) {
  74386. return false;
  74387. }
  74388. }
  74389. }
  74390. return true;
  74391. },
  74392. enumerable: true,
  74393. configurable: true
  74394. });
  74395. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74396. this._renderEffects[renderEffect._name] = renderEffect;
  74397. };
  74398. // private
  74399. PostProcessRenderPipeline.prototype._rebuild = function () {
  74400. };
  74401. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74402. var renderEffects = this._renderEffects[renderEffectName];
  74403. if (!renderEffects) {
  74404. return;
  74405. }
  74406. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74407. };
  74408. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74409. var renderEffects = this._renderEffects[renderEffectName];
  74410. if (!renderEffects) {
  74411. return;
  74412. }
  74413. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74414. };
  74415. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74416. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74417. if (!cams) {
  74418. return;
  74419. }
  74420. var indicesToDelete = [];
  74421. var i;
  74422. for (i = 0; i < cams.length; i++) {
  74423. var camera = cams[i];
  74424. var cameraName = camera.name;
  74425. if (this._cameras.indexOf(camera) === -1) {
  74426. this._cameras[cameraName] = camera;
  74427. }
  74428. else if (unique) {
  74429. indicesToDelete.push(i);
  74430. }
  74431. }
  74432. for (i = 0; i < indicesToDelete.length; i++) {
  74433. cameras.splice(indicesToDelete[i], 1);
  74434. }
  74435. for (var renderEffectName in this._renderEffects) {
  74436. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74437. this._renderEffects[renderEffectName]._attachCameras(cams);
  74438. }
  74439. }
  74440. };
  74441. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74442. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74443. if (!cams) {
  74444. return;
  74445. }
  74446. for (var renderEffectName in this._renderEffects) {
  74447. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74448. this._renderEffects[renderEffectName]._detachCameras(cams);
  74449. }
  74450. }
  74451. for (var i = 0; i < cams.length; i++) {
  74452. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74453. }
  74454. };
  74455. PostProcessRenderPipeline.prototype._update = function () {
  74456. for (var renderEffectName in this._renderEffects) {
  74457. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74458. this._renderEffects[renderEffectName]._update();
  74459. }
  74460. }
  74461. for (var i = 0; i < this._cameras.length; i++) {
  74462. var cameraName = this._cameras[i].name;
  74463. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74464. this._renderEffectsForIsolatedPass[cameraName]._update();
  74465. }
  74466. }
  74467. };
  74468. PostProcessRenderPipeline.prototype._reset = function () {
  74469. this._renderEffects = {};
  74470. this._renderEffectsForIsolatedPass = new Array();
  74471. };
  74472. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74473. // 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)
  74474. var effectKeys = Object.keys(this._renderEffects);
  74475. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74476. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74477. if (postProcesses) {
  74478. postProcesses[0].samples = sampleCount;
  74479. return true;
  74480. }
  74481. }
  74482. return false;
  74483. };
  74484. PostProcessRenderPipeline.prototype.dispose = function () {
  74485. // Must be implemented by children
  74486. };
  74487. __decorate([
  74488. BABYLON.serialize()
  74489. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74490. return PostProcessRenderPipeline;
  74491. }());
  74492. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74493. })(BABYLON || (BABYLON = {}));
  74494. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74495. var BABYLON;
  74496. (function (BABYLON) {
  74497. /**
  74498. * This represents a depth renderer in Babylon.
  74499. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74500. */
  74501. var DepthRenderer = /** @class */ (function () {
  74502. /**
  74503. * Instantiates a depth renderer
  74504. * @param scene The scene the renderer belongs to
  74505. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74506. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74507. */
  74508. function DepthRenderer(scene, type, camera) {
  74509. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74510. if (camera === void 0) { camera = null; }
  74511. var _this = this;
  74512. this._scene = scene;
  74513. this._camera = camera;
  74514. var engine = scene.getEngine();
  74515. // Render target
  74516. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74517. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74518. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74519. this._depthMap.refreshRate = 1;
  74520. this._depthMap.renderParticles = false;
  74521. this._depthMap.renderList = null;
  74522. // Camera to get depth map from to support multiple concurrent cameras
  74523. this._depthMap.activeCamera = this._camera;
  74524. this._depthMap.ignoreCameraViewport = true;
  74525. this._depthMap.useCameraPostProcesses = false;
  74526. // set default depth value to 1.0 (far away)
  74527. this._depthMap.onClearObservable.add(function (engine) {
  74528. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74529. });
  74530. // Custom render function
  74531. var renderSubMesh = function (subMesh) {
  74532. var mesh = subMesh.getRenderingMesh();
  74533. var scene = _this._scene;
  74534. var engine = scene.getEngine();
  74535. var material = subMesh.getMaterial();
  74536. if (!material) {
  74537. return;
  74538. }
  74539. // Culling and reverse (right handed system)
  74540. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74541. // Managing instances
  74542. var batch = mesh._getInstancesRenderList(subMesh._id);
  74543. if (batch.mustReturn) {
  74544. return;
  74545. }
  74546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74547. var camera = _this._camera || scene.activeCamera;
  74548. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74549. engine.enableEffect(_this._effect);
  74550. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74551. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74552. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74553. // Alpha test
  74554. if (material && material.needAlphaTesting()) {
  74555. var alphaTexture = material.getAlphaTestTexture();
  74556. if (alphaTexture) {
  74557. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74558. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74559. }
  74560. }
  74561. // Bones
  74562. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74563. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74564. }
  74565. // Draw
  74566. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74567. }
  74568. };
  74569. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74570. var index;
  74571. if (depthOnlySubMeshes.length) {
  74572. engine.setColorWrite(false);
  74573. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74574. renderSubMesh(depthOnlySubMeshes.data[index]);
  74575. }
  74576. engine.setColorWrite(true);
  74577. }
  74578. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74579. renderSubMesh(opaqueSubMeshes.data[index]);
  74580. }
  74581. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74582. renderSubMesh(alphaTestSubMeshes.data[index]);
  74583. }
  74584. };
  74585. }
  74586. /**
  74587. * Creates the depth rendering effect and checks if the effect is ready.
  74588. * @param subMesh The submesh to be used to render the depth map of
  74589. * @param useInstances If multiple world instances should be used
  74590. * @returns if the depth renderer is ready to render the depth map
  74591. */
  74592. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74593. var material = subMesh.getMaterial();
  74594. if (material.disableDepthWrite) {
  74595. return false;
  74596. }
  74597. var defines = [];
  74598. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74599. var mesh = subMesh.getMesh();
  74600. // Alpha test
  74601. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74602. defines.push("#define ALPHATEST");
  74603. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74604. attribs.push(BABYLON.VertexBuffer.UVKind);
  74605. defines.push("#define UV1");
  74606. }
  74607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74608. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74609. defines.push("#define UV2");
  74610. }
  74611. }
  74612. // Bones
  74613. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74614. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74615. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74616. if (mesh.numBoneInfluencers > 4) {
  74617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74619. }
  74620. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74621. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74622. }
  74623. else {
  74624. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74625. }
  74626. // Instances
  74627. if (useInstances) {
  74628. defines.push("#define INSTANCES");
  74629. attribs.push("world0");
  74630. attribs.push("world1");
  74631. attribs.push("world2");
  74632. attribs.push("world3");
  74633. }
  74634. // Get correct effect
  74635. var join = defines.join("\n");
  74636. if (this._cachedDefines !== join) {
  74637. this._cachedDefines = join;
  74638. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  74639. }
  74640. return this._effect.isReady();
  74641. };
  74642. /**
  74643. * Gets the texture which the depth map will be written to.
  74644. * @returns The depth map texture
  74645. */
  74646. DepthRenderer.prototype.getDepthMap = function () {
  74647. return this._depthMap;
  74648. };
  74649. /**
  74650. * Disposes of the depth renderer.
  74651. */
  74652. DepthRenderer.prototype.dispose = function () {
  74653. this._depthMap.dispose();
  74654. };
  74655. return DepthRenderer;
  74656. }());
  74657. BABYLON.DepthRenderer = DepthRenderer;
  74658. })(BABYLON || (BABYLON = {}));
  74659. //# sourceMappingURL=babylon.depthRenderer.js.map
  74660. var BABYLON;
  74661. (function (BABYLON) {
  74662. var SSAORenderingPipeline = /** @class */ (function (_super) {
  74663. __extends(SSAORenderingPipeline, _super);
  74664. /**
  74665. * @constructor
  74666. * @param {string} name - The rendering pipeline name
  74667. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74668. * @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 }
  74669. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74670. */
  74671. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  74672. var _this = _super.call(this, scene.getEngine(), name) || this;
  74673. // Members
  74674. /**
  74675. * The PassPostProcess id in the pipeline that contains the original scene color
  74676. */
  74677. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74678. /**
  74679. * The SSAO PostProcess id in the pipeline
  74680. */
  74681. _this.SSAORenderEffect = "SSAORenderEffect";
  74682. /**
  74683. * The horizontal blur PostProcess id in the pipeline
  74684. */
  74685. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74686. /**
  74687. * The vertical blur PostProcess id in the pipeline
  74688. */
  74689. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74690. /**
  74691. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74692. */
  74693. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74694. /**
  74695. * The output strength of the SSAO post-process. Default value is 1.0.
  74696. */
  74697. _this.totalStrength = 1.0;
  74698. /**
  74699. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  74700. */
  74701. _this.radius = 0.0001;
  74702. /**
  74703. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  74704. * Must not be equal to fallOff and superior to fallOff.
  74705. * Default value is 0.975
  74706. */
  74707. _this.area = 0.0075;
  74708. /**
  74709. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  74710. * Must not be equal to area and inferior to area.
  74711. * Default value is 0.0
  74712. */
  74713. _this.fallOff = 0.000001;
  74714. /**
  74715. * The base color of the SSAO post-process
  74716. * The final result is "base + ssao" between [0, 1]
  74717. */
  74718. _this.base = 0.5;
  74719. _this._firstUpdate = true;
  74720. _this._scene = scene;
  74721. // Set up assets
  74722. _this._createRandomTexture();
  74723. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74724. var ssaoRatio = ratio.ssaoRatio || ratio;
  74725. var combineRatio = ratio.combineRatio || ratio;
  74726. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74727. _this._createSSAOPostProcess(ssaoRatio);
  74728. _this._createBlurPostProcess(ssaoRatio);
  74729. _this._createSSAOCombinePostProcess(combineRatio);
  74730. // Set up pipeline
  74731. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74732. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74733. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74734. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74735. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74736. // Finish
  74737. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74738. if (cameras)
  74739. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74740. return _this;
  74741. }
  74742. // Public Methods
  74743. /**
  74744. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74745. */
  74746. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74747. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74748. for (var i = 0; i < this._scene.cameras.length; i++) {
  74749. var camera = this._scene.cameras[i];
  74750. this._originalColorPostProcess.dispose(camera);
  74751. this._ssaoPostProcess.dispose(camera);
  74752. this._blurHPostProcess.dispose(camera);
  74753. this._blurVPostProcess.dispose(camera);
  74754. this._ssaoCombinePostProcess.dispose(camera);
  74755. }
  74756. this._randomTexture.dispose();
  74757. if (disableDepthRender)
  74758. this._scene.disableDepthRenderer();
  74759. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74760. _super.prototype.dispose.call(this);
  74761. };
  74762. // Private Methods
  74763. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74764. var _this = this;
  74765. var size = 16;
  74766. 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);
  74767. 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);
  74768. this._blurHPostProcess.onActivateObservable.add(function () {
  74769. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74770. _this._blurHPostProcess.kernel = size * dw;
  74771. });
  74772. this._blurVPostProcess.onActivateObservable.add(function () {
  74773. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74774. _this._blurVPostProcess.kernel = size * dw;
  74775. });
  74776. };
  74777. SSAORenderingPipeline.prototype._rebuild = function () {
  74778. this._firstUpdate = true;
  74779. _super.prototype._rebuild.call(this);
  74780. };
  74781. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74782. var _this = this;
  74783. var numSamples = 16;
  74784. var sampleSphere = [
  74785. 0.5381, 0.1856, -0.4319,
  74786. 0.1379, 0.2486, 0.4430,
  74787. 0.3371, 0.5679, -0.0057,
  74788. -0.6999, -0.0451, -0.0019,
  74789. 0.0689, -0.1598, -0.8547,
  74790. 0.0560, 0.0069, -0.1843,
  74791. -0.0146, 0.1402, 0.0762,
  74792. 0.0100, -0.1924, -0.0344,
  74793. -0.3577, -0.5301, -0.4358,
  74794. -0.3169, 0.1063, 0.0158,
  74795. 0.0103, -0.5869, 0.0046,
  74796. -0.0897, -0.4940, 0.3287,
  74797. 0.7119, -0.0154, -0.0918,
  74798. -0.0533, 0.0596, -0.5411,
  74799. 0.0352, -0.0631, 0.5460,
  74800. -0.4776, 0.2847, -0.0271
  74801. ];
  74802. var samplesFactor = 1.0 / numSamples;
  74803. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74804. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74805. "area", "fallOff", "base", "range", "viewport"
  74806. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74807. this._ssaoPostProcess.onApply = function (effect) {
  74808. if (_this._firstUpdate) {
  74809. effect.setArray3("sampleSphere", sampleSphere);
  74810. effect.setFloat("samplesFactor", samplesFactor);
  74811. effect.setFloat("randTextureTiles", 4.0);
  74812. }
  74813. effect.setFloat("totalStrength", _this.totalStrength);
  74814. effect.setFloat("radius", _this.radius);
  74815. effect.setFloat("area", _this.area);
  74816. effect.setFloat("fallOff", _this.fallOff);
  74817. effect.setFloat("base", _this.base);
  74818. effect.setTexture("textureSampler", _this._depthTexture);
  74819. effect.setTexture("randomSampler", _this._randomTexture);
  74820. };
  74821. };
  74822. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74823. var _this = this;
  74824. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74825. this._ssaoCombinePostProcess.onApply = function (effect) {
  74826. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74827. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74828. };
  74829. };
  74830. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74831. var size = 512;
  74832. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74833. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74834. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74835. var context = this._randomTexture.getContext();
  74836. var rand = function (min, max) {
  74837. return Math.random() * (max - min) + min;
  74838. };
  74839. var randVector = BABYLON.Vector3.Zero();
  74840. for (var x = 0; x < size; x++) {
  74841. for (var y = 0; y < size; y++) {
  74842. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74843. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74844. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74845. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74846. context.fillRect(x, y, 1, 1);
  74847. }
  74848. }
  74849. this._randomTexture.update(false);
  74850. };
  74851. __decorate([
  74852. BABYLON.serialize()
  74853. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74854. __decorate([
  74855. BABYLON.serialize()
  74856. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74857. __decorate([
  74858. BABYLON.serialize()
  74859. ], SSAORenderingPipeline.prototype, "area", void 0);
  74860. __decorate([
  74861. BABYLON.serialize()
  74862. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74863. __decorate([
  74864. BABYLON.serialize()
  74865. ], SSAORenderingPipeline.prototype, "base", void 0);
  74866. return SSAORenderingPipeline;
  74867. }(BABYLON.PostProcessRenderPipeline));
  74868. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74869. })(BABYLON || (BABYLON = {}));
  74870. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74871. var BABYLON;
  74872. (function (BABYLON) {
  74873. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74874. __extends(SSAO2RenderingPipeline, _super);
  74875. /**
  74876. * @constructor
  74877. * @param {string} name - The rendering pipeline name
  74878. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74879. * @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 }
  74880. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74881. */
  74882. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74883. var _this = _super.call(this, scene.getEngine(), name) || this;
  74884. // Members
  74885. /**
  74886. * The PassPostProcess id in the pipeline that contains the original scene color
  74887. */
  74888. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74889. /**
  74890. * The SSAO PostProcess id in the pipeline
  74891. */
  74892. _this.SSAORenderEffect = "SSAORenderEffect";
  74893. /**
  74894. * The horizontal blur PostProcess id in the pipeline
  74895. */
  74896. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74897. /**
  74898. * The vertical blur PostProcess id in the pipeline
  74899. */
  74900. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74901. /**
  74902. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74903. */
  74904. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74905. /**
  74906. * The output strength of the SSAO post-process. Default value is 1.0.
  74907. */
  74908. _this.totalStrength = 1.0;
  74909. /**
  74910. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74911. */
  74912. _this.maxZ = 100.0;
  74913. /**
  74914. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74915. */
  74916. _this.minZAspect = 0.2;
  74917. /**
  74918. * Number of samples used for the SSAO calculations. Default value is 8
  74919. */
  74920. _this._samples = 8;
  74921. /**
  74922. * Are we using bilateral blur ?
  74923. */
  74924. _this._expensiveBlur = true;
  74925. /**
  74926. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74927. */
  74928. _this.radius = 2.0;
  74929. /**
  74930. * The base color of the SSAO post-process
  74931. * The final result is "base + ssao" between [0, 1]
  74932. */
  74933. _this.base = 0.1;
  74934. _this._firstUpdate = true;
  74935. _this._scene = scene;
  74936. _this._ratio = ratio;
  74937. if (!_this.isSupported) {
  74938. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74939. return _this;
  74940. }
  74941. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74942. var blurRatio = _this._ratio.blurRatio || ratio;
  74943. // Set up assets
  74944. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74945. _this._createRandomTexture();
  74946. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74947. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74948. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74949. _this._createSSAOPostProcess(1.0);
  74950. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74951. _this._createSSAOCombinePostProcess(blurRatio);
  74952. // Set up pipeline
  74953. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74954. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74958. // Finish
  74959. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74960. if (cameras)
  74961. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74962. return _this;
  74963. }
  74964. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74965. get: function () {
  74966. return this._samples;
  74967. },
  74968. set: function (n) {
  74969. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74970. this._samples = n;
  74971. this._sampleSphere = this._generateHemisphere();
  74972. this._firstUpdate = true;
  74973. },
  74974. enumerable: true,
  74975. configurable: true
  74976. });
  74977. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74978. get: function () {
  74979. return this._expensiveBlur;
  74980. },
  74981. set: function (b) {
  74982. 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"]);
  74983. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74984. this._expensiveBlur = b;
  74985. this._firstUpdate = true;
  74986. },
  74987. enumerable: true,
  74988. configurable: true
  74989. });
  74990. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74991. /**
  74992. * Support test.
  74993. */
  74994. get: function () {
  74995. var engine = BABYLON.Engine.LastCreatedEngine;
  74996. if (!engine) {
  74997. return false;
  74998. }
  74999. return engine.getCaps().drawBuffersExtension;
  75000. },
  75001. enumerable: true,
  75002. configurable: true
  75003. });
  75004. // Public Methods
  75005. /**
  75006. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75007. */
  75008. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75009. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75010. for (var i = 0; i < this._scene.cameras.length; i++) {
  75011. var camera = this._scene.cameras[i];
  75012. this._originalColorPostProcess.dispose(camera);
  75013. this._ssaoPostProcess.dispose(camera);
  75014. this._blurHPostProcess.dispose(camera);
  75015. this._blurVPostProcess.dispose(camera);
  75016. this._ssaoCombinePostProcess.dispose(camera);
  75017. }
  75018. this._randomTexture.dispose();
  75019. if (disableGeometryBufferRenderer)
  75020. this._scene.disableGeometryBufferRenderer();
  75021. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75022. _super.prototype.dispose.call(this);
  75023. };
  75024. // Private Methods
  75025. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75026. var _this = this;
  75027. this._samplerOffsets = [];
  75028. var expensive = this.expensiveBlur;
  75029. for (var i = -8; i < 8; i++) {
  75030. this._samplerOffsets.push(i * 2 + 0.5);
  75031. }
  75032. 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");
  75033. this._blurHPostProcess.onApply = function (effect) {
  75034. if (!_this._scene.activeCamera) {
  75035. return;
  75036. }
  75037. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75038. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75039. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75040. effect.setFloat("radius", _this.radius);
  75041. effect.setTexture("depthSampler", _this._depthTexture);
  75042. if (_this._firstUpdate) {
  75043. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75044. }
  75045. };
  75046. 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");
  75047. this._blurVPostProcess.onApply = function (effect) {
  75048. if (!_this._scene.activeCamera) {
  75049. return;
  75050. }
  75051. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75052. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75053. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75054. effect.setFloat("radius", _this.radius);
  75055. effect.setTexture("depthSampler", _this._depthTexture);
  75056. if (_this._firstUpdate) {
  75057. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75058. _this._firstUpdate = false;
  75059. }
  75060. };
  75061. };
  75062. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75063. this._firstUpdate = true;
  75064. _super.prototype._rebuild.call(this);
  75065. };
  75066. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75067. var numSamples = this.samples;
  75068. var result = [];
  75069. var vector, scale;
  75070. var rand = function (min, max) {
  75071. return Math.random() * (max - min) + min;
  75072. };
  75073. var i = 0;
  75074. while (i < numSamples) {
  75075. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75076. vector.normalize();
  75077. scale = i / numSamples;
  75078. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75079. vector.scaleInPlace(scale);
  75080. result.push(vector.x, vector.y, vector.z);
  75081. i++;
  75082. }
  75083. return result;
  75084. };
  75085. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75086. var _this = this;
  75087. var numSamples = this.samples;
  75088. this._sampleSphere = this._generateHemisphere();
  75089. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75090. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75091. "base", "range", "projection", "near", "far", "texelSize",
  75092. "xViewport", "yViewport", "maxZ", "minZAspect"
  75093. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75094. this._ssaoPostProcess.onApply = function (effect) {
  75095. if (_this._firstUpdate) {
  75096. effect.setArray3("sampleSphere", _this._sampleSphere);
  75097. effect.setFloat("randTextureTiles", 4.0);
  75098. }
  75099. if (!_this._scene.activeCamera) {
  75100. return;
  75101. }
  75102. effect.setFloat("samplesFactor", 1 / _this.samples);
  75103. effect.setFloat("totalStrength", _this.totalStrength);
  75104. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75105. effect.setFloat("radius", _this.radius);
  75106. effect.setFloat("maxZ", _this.maxZ);
  75107. effect.setFloat("minZAspect", _this.minZAspect);
  75108. effect.setFloat("base", _this.base);
  75109. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75110. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75111. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75112. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75113. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75114. effect.setTexture("textureSampler", _this._depthTexture);
  75115. effect.setTexture("normalSampler", _this._normalTexture);
  75116. effect.setTexture("randomSampler", _this._randomTexture);
  75117. };
  75118. };
  75119. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75120. var _this = this;
  75121. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75122. this._ssaoCombinePostProcess.onApply = function (effect) {
  75123. var viewport = _this._scene.activeCamera.viewport;
  75124. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75125. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75126. };
  75127. };
  75128. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75129. var size = 512;
  75130. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75131. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75132. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75133. var context = this._randomTexture.getContext();
  75134. var rand = function (min, max) {
  75135. return Math.random() * (max - min) + min;
  75136. };
  75137. var randVector = BABYLON.Vector3.Zero();
  75138. for (var x = 0; x < size; x++) {
  75139. for (var y = 0; y < size; y++) {
  75140. randVector.x = rand(0.0, 1.0);
  75141. randVector.y = rand(0.0, 1.0);
  75142. randVector.z = 0.0;
  75143. randVector.normalize();
  75144. randVector.scaleInPlace(255);
  75145. randVector.x = Math.floor(randVector.x);
  75146. randVector.y = Math.floor(randVector.y);
  75147. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75148. context.fillRect(x, y, 1, 1);
  75149. }
  75150. }
  75151. this._randomTexture.update(false);
  75152. };
  75153. /**
  75154. * Serialize the rendering pipeline (Used when exporting)
  75155. * @returns the serialized object
  75156. */
  75157. SSAO2RenderingPipeline.prototype.serialize = function () {
  75158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75159. serializationObject.customType = "SSAO2RenderingPipeline";
  75160. return serializationObject;
  75161. };
  75162. /**
  75163. * Parse the serialized pipeline
  75164. * @param source Source pipeline.
  75165. * @param scene The scene to load the pipeline to.
  75166. * @param rootUrl The URL of the serialized pipeline.
  75167. * @returns An instantiated pipeline from the serialized object.
  75168. */
  75169. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75170. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75171. };
  75172. __decorate([
  75173. BABYLON.serialize()
  75174. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75175. __decorate([
  75176. BABYLON.serialize()
  75177. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75178. __decorate([
  75179. BABYLON.serialize()
  75180. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75181. __decorate([
  75182. BABYLON.serialize("samples")
  75183. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75184. __decorate([
  75185. BABYLON.serialize()
  75186. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75187. __decorate([
  75188. BABYLON.serialize("expensiveBlur")
  75189. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75190. __decorate([
  75191. BABYLON.serialize()
  75192. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75193. __decorate([
  75194. BABYLON.serialize()
  75195. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75196. return SSAO2RenderingPipeline;
  75197. }(BABYLON.PostProcessRenderPipeline));
  75198. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75199. })(BABYLON || (BABYLON = {}));
  75200. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75201. // BABYLON.JS Chromatic Aberration GLSL Shader
  75202. // Author: Olivier Guyot
  75203. // Separates very slightly R, G and B colors on the edges of the screen
  75204. // Inspired by Francois Tarlier & Martins Upitis
  75205. var BABYLON;
  75206. (function (BABYLON) {
  75207. var LensRenderingPipeline = /** @class */ (function (_super) {
  75208. __extends(LensRenderingPipeline, _super);
  75209. /**
  75210. * @constructor
  75211. *
  75212. * Effect parameters are as follow:
  75213. * {
  75214. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75215. * edge_blur: number; // from 0 to x (1 for realism)
  75216. * distortion: number; // from 0 to x (1 for realism)
  75217. * grain_amount: number; // from 0 to 1
  75218. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75219. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75220. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75221. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75222. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75223. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75224. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75225. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75226. * }
  75227. * Note: if an effect parameter is unset, effect is disabled
  75228. *
  75229. * @param {string} name - The rendering pipeline name
  75230. * @param {object} parameters - An object containing all parameters (see above)
  75231. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75232. * @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)
  75233. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75234. */
  75235. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75236. if (ratio === void 0) { ratio = 1.0; }
  75237. var _this = _super.call(this, scene.getEngine(), name) || this;
  75238. // Lens effects can be of the following:
  75239. // - chromatic aberration (slight shift of RGB colors)
  75240. // - blur on the edge of the lens
  75241. // - lens distortion
  75242. // - depth-of-field blur & highlights enhancing
  75243. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75244. // - grain effect (noise or custom texture)
  75245. // Two additional texture samplers are needed:
  75246. // - depth map (for depth-of-field)
  75247. // - grain texture
  75248. /**
  75249. * The chromatic aberration PostProcess id in the pipeline
  75250. */
  75251. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75252. /**
  75253. * The highlights enhancing PostProcess id in the pipeline
  75254. */
  75255. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75256. /**
  75257. * The depth-of-field PostProcess id in the pipeline
  75258. */
  75259. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75260. _this._scene = scene;
  75261. // Fetch texture samplers
  75262. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75263. if (parameters.grain_texture) {
  75264. _this._grainTexture = parameters.grain_texture;
  75265. }
  75266. else {
  75267. _this._createGrainTexture();
  75268. }
  75269. // save parameters
  75270. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75271. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75272. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75273. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75274. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75275. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75276. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75277. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75278. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75279. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75280. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75281. // Create effects
  75282. _this._createChromaticAberrationPostProcess(ratio);
  75283. _this._createHighlightsPostProcess(ratio);
  75284. _this._createDepthOfFieldPostProcess(ratio / 4);
  75285. // Set up pipeline
  75286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75289. if (_this._highlightsGain === -1) {
  75290. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75291. }
  75292. // Finish
  75293. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75294. if (cameras) {
  75295. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75296. }
  75297. return _this;
  75298. }
  75299. // public methods (self explanatory)
  75300. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75301. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75302. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75303. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75304. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75305. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75306. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75307. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75308. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75309. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75310. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75311. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75312. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75313. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75314. };
  75315. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75316. this._highlightsPostProcess.updateEffect();
  75317. };
  75318. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75319. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75320. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75321. this._highlightsGain = amount;
  75322. };
  75323. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75324. if (this._highlightsGain === -1) {
  75325. this._highlightsGain = 1.0;
  75326. }
  75327. this._highlightsThreshold = amount;
  75328. };
  75329. LensRenderingPipeline.prototype.disableHighlights = function () {
  75330. this._highlightsGain = -1;
  75331. };
  75332. /**
  75333. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75334. */
  75335. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75336. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75337. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75338. this._chromaticAberrationPostProcess = null;
  75339. this._highlightsPostProcess = null;
  75340. this._depthOfFieldPostProcess = null;
  75341. this._grainTexture.dispose();
  75342. if (disableDepthRender)
  75343. this._scene.disableDepthRenderer();
  75344. };
  75345. // colors shifting and distortion
  75346. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75347. var _this = this;
  75348. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75349. [], // samplers
  75350. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75351. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75352. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75353. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75354. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75355. effect.setFloat('radialIntensity', 1);
  75356. effect.setFloat2('direction', 17, 17);
  75357. effect.setFloat2('centerPosition', 0.5, 0.5);
  75358. };
  75359. };
  75360. // highlights enhancing
  75361. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75362. var _this = this;
  75363. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75364. [], // samplers
  75365. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75366. this._highlightsPostProcess.onApply = function (effect) {
  75367. effect.setFloat('gain', _this._highlightsGain);
  75368. effect.setFloat('threshold', _this._highlightsThreshold);
  75369. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75370. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75371. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75372. };
  75373. };
  75374. // colors shifting and distortion
  75375. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75376. var _this = this;
  75377. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75378. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75379. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75380. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75381. this._depthOfFieldPostProcess.onApply = function (effect) {
  75382. effect.setTexture("depthSampler", _this._depthTexture);
  75383. effect.setTexture("grainSampler", _this._grainTexture);
  75384. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75385. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75386. effect.setFloat('grain_amount', _this._grainAmount);
  75387. effect.setBool('blur_noise', _this._blurNoise);
  75388. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75389. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75390. effect.setFloat('distortion', _this._distortion);
  75391. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75392. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75393. effect.setFloat('aperture', _this._dofAperture);
  75394. effect.setFloat('darken', _this._dofDarken);
  75395. effect.setFloat('edge_blur', _this._edgeBlur);
  75396. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75397. if (_this._scene.activeCamera) {
  75398. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75399. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75400. }
  75401. };
  75402. };
  75403. // creates a black and white random noise texture, 512x512
  75404. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75405. var size = 512;
  75406. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75407. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75408. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75409. var context = this._grainTexture.getContext();
  75410. var rand = function (min, max) {
  75411. return Math.random() * (max - min) + min;
  75412. };
  75413. var value;
  75414. for (var x = 0; x < size; x++) {
  75415. for (var y = 0; y < size; y++) {
  75416. value = Math.floor(rand(0.42, 0.58) * 255);
  75417. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75418. context.fillRect(x, y, 1, 1);
  75419. }
  75420. }
  75421. this._grainTexture.update(false);
  75422. };
  75423. return LensRenderingPipeline;
  75424. }(BABYLON.PostProcessRenderPipeline));
  75425. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75426. })(BABYLON || (BABYLON = {}));
  75427. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75428. var BABYLON;
  75429. (function (BABYLON) {
  75430. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75431. __extends(StandardRenderingPipeline, _super);
  75432. /**
  75433. * @constructor
  75434. * @param {string} name - The rendering pipeline name
  75435. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75436. * @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)
  75437. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75438. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75439. */
  75440. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75441. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75442. var _this = _super.call(this, scene.getEngine(), name) || this;
  75443. _this.downSampleX4PostProcess = null;
  75444. _this.brightPassPostProcess = null;
  75445. _this.blurHPostProcesses = [];
  75446. _this.blurVPostProcesses = [];
  75447. _this.textureAdderPostProcess = null;
  75448. _this.volumetricLightPostProcess = null;
  75449. _this.volumetricLightSmoothXPostProcess = null;
  75450. _this.volumetricLightSmoothYPostProcess = null;
  75451. _this.volumetricLightMergePostProces = null;
  75452. _this.volumetricLightFinalPostProcess = null;
  75453. _this.luminancePostProcess = null;
  75454. _this.luminanceDownSamplePostProcesses = [];
  75455. _this.hdrPostProcess = null;
  75456. _this.textureAdderFinalPostProcess = null;
  75457. _this.lensFlareFinalPostProcess = null;
  75458. _this.hdrFinalPostProcess = null;
  75459. _this.lensFlarePostProcess = null;
  75460. _this.lensFlareComposePostProcess = null;
  75461. _this.motionBlurPostProcess = null;
  75462. _this.depthOfFieldPostProcess = null;
  75463. // Values
  75464. _this.brightThreshold = 1.0;
  75465. _this.blurWidth = 512.0;
  75466. _this.horizontalBlur = false;
  75467. _this.exposure = 1.0;
  75468. _this.lensTexture = null;
  75469. _this.volumetricLightCoefficient = 0.2;
  75470. _this.volumetricLightPower = 4.0;
  75471. _this.volumetricLightBlurScale = 64.0;
  75472. _this.sourceLight = null;
  75473. _this.hdrMinimumLuminance = 1.0;
  75474. _this.hdrDecreaseRate = 0.5;
  75475. _this.hdrIncreaseRate = 0.5;
  75476. _this.lensColorTexture = null;
  75477. _this.lensFlareStrength = 20.0;
  75478. _this.lensFlareGhostDispersal = 1.4;
  75479. _this.lensFlareHaloWidth = 0.7;
  75480. _this.lensFlareDistortionStrength = 16.0;
  75481. _this.lensStarTexture = null;
  75482. _this.lensFlareDirtTexture = null;
  75483. _this.depthOfFieldDistance = 10.0;
  75484. _this.depthOfFieldBlurWidth = 64.0;
  75485. _this.motionStrength = 1.0;
  75486. // IAnimatable
  75487. _this.animations = [];
  75488. _this._currentDepthOfFieldSource = null;
  75489. _this._hdrCurrentLuminance = 1.0;
  75490. // Getters and setters
  75491. _this._bloomEnabled = true;
  75492. _this._depthOfFieldEnabled = false;
  75493. _this._vlsEnabled = false;
  75494. _this._lensFlareEnabled = false;
  75495. _this._hdrEnabled = false;
  75496. _this._motionBlurEnabled = false;
  75497. _this._motionBlurSamples = 64.0;
  75498. _this._volumetricLightStepsCount = 50.0;
  75499. _this._cameras = cameras || [];
  75500. // Initialize
  75501. _this._scene = scene;
  75502. _this._basePostProcess = originalPostProcess;
  75503. _this._ratio = ratio;
  75504. // Misc
  75505. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75506. // Finish
  75507. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75508. _this._buildPipeline();
  75509. return _this;
  75510. }
  75511. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75512. get: function () {
  75513. return this._bloomEnabled;
  75514. },
  75515. set: function (enabled) {
  75516. if (this._bloomEnabled === enabled) {
  75517. return;
  75518. }
  75519. this._bloomEnabled = enabled;
  75520. this._buildPipeline();
  75521. },
  75522. enumerable: true,
  75523. configurable: true
  75524. });
  75525. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75526. get: function () {
  75527. return this._depthOfFieldEnabled;
  75528. },
  75529. set: function (enabled) {
  75530. if (this._depthOfFieldEnabled === enabled) {
  75531. return;
  75532. }
  75533. this._depthOfFieldEnabled = enabled;
  75534. this._buildPipeline();
  75535. },
  75536. enumerable: true,
  75537. configurable: true
  75538. });
  75539. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75540. get: function () {
  75541. return this._lensFlareEnabled;
  75542. },
  75543. set: function (enabled) {
  75544. if (this._lensFlareEnabled === enabled) {
  75545. return;
  75546. }
  75547. this._lensFlareEnabled = enabled;
  75548. this._buildPipeline();
  75549. },
  75550. enumerable: true,
  75551. configurable: true
  75552. });
  75553. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75554. get: function () {
  75555. return this._hdrEnabled;
  75556. },
  75557. set: function (enabled) {
  75558. if (this._hdrEnabled === enabled) {
  75559. return;
  75560. }
  75561. this._hdrEnabled = enabled;
  75562. this._buildPipeline();
  75563. },
  75564. enumerable: true,
  75565. configurable: true
  75566. });
  75567. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75568. get: function () {
  75569. return this._vlsEnabled;
  75570. },
  75571. set: function (enabled) {
  75572. if (this._vlsEnabled === enabled) {
  75573. return;
  75574. }
  75575. if (enabled) {
  75576. var geometry = this._scene.enableGeometryBufferRenderer();
  75577. if (!geometry) {
  75578. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75579. return;
  75580. }
  75581. }
  75582. this._vlsEnabled = enabled;
  75583. this._buildPipeline();
  75584. },
  75585. enumerable: true,
  75586. configurable: true
  75587. });
  75588. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75589. get: function () {
  75590. return this._motionBlurEnabled;
  75591. },
  75592. set: function (enabled) {
  75593. if (this._motionBlurEnabled === enabled) {
  75594. return;
  75595. }
  75596. this._motionBlurEnabled = enabled;
  75597. this._buildPipeline();
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75603. get: function () {
  75604. return this._volumetricLightStepsCount;
  75605. },
  75606. set: function (count) {
  75607. if (this.volumetricLightPostProcess) {
  75608. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75609. }
  75610. this._volumetricLightStepsCount = count;
  75611. },
  75612. enumerable: true,
  75613. configurable: true
  75614. });
  75615. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  75616. get: function () {
  75617. return this._motionBlurSamples;
  75618. },
  75619. set: function (samples) {
  75620. if (this.motionBlurPostProcess) {
  75621. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  75622. }
  75623. this._motionBlurSamples = samples;
  75624. },
  75625. enumerable: true,
  75626. configurable: true
  75627. });
  75628. StandardRenderingPipeline.prototype._buildPipeline = function () {
  75629. var _this = this;
  75630. var ratio = this._ratio;
  75631. var scene = this._scene;
  75632. this._disposePostProcesses();
  75633. this._reset();
  75634. // Create pass post-process
  75635. if (!this._basePostProcess) {
  75636. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  75637. this.originalPostProcess.onApply = function (effect) {
  75638. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  75639. };
  75640. }
  75641. else {
  75642. this.originalPostProcess = this._basePostProcess;
  75643. }
  75644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  75645. this._currentDepthOfFieldSource = this.originalPostProcess;
  75646. if (this._bloomEnabled) {
  75647. // Create down sample X4 post-process
  75648. this._createDownSampleX4PostProcess(scene, ratio / 2);
  75649. // Create bright pass post-process
  75650. this._createBrightPassPostProcess(scene, ratio / 2);
  75651. // Create gaussian blur post-processes (down sampling blurs)
  75652. this._createBlurPostProcesses(scene, ratio / 4, 1);
  75653. // Create texture adder post-process
  75654. this._createTextureAdderPostProcess(scene, ratio);
  75655. // Create depth-of-field source post-process
  75656. 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);
  75657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  75658. }
  75659. if (this._vlsEnabled) {
  75660. // Create volumetric light
  75661. this._createVolumetricLightPostProcess(scene, ratio);
  75662. // Create volumetric light final post-process
  75663. 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);
  75664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  75665. }
  75666. if (this._lensFlareEnabled) {
  75667. // Create lens flare post-process
  75668. this._createLensFlarePostProcess(scene, ratio);
  75669. // Create depth-of-field source post-process post lens-flare and disable it now
  75670. 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);
  75671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  75672. }
  75673. if (this._hdrEnabled) {
  75674. // Create luminance
  75675. this._createLuminancePostProcesses(scene, this._floatTextureType);
  75676. // Create HDR
  75677. this._createHdrPostProcess(scene, ratio);
  75678. // Create depth-of-field source post-process post hdr and disable it now
  75679. 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);
  75680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  75681. }
  75682. if (this._depthOfFieldEnabled) {
  75683. // Create gaussian blur used by depth-of-field
  75684. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  75685. // Create depth-of-field post-process
  75686. this._createDepthOfFieldPostProcess(scene, ratio);
  75687. }
  75688. if (this._motionBlurEnabled) {
  75689. // Create motion blur post-process
  75690. this._createMotionBlurPostProcess(scene, ratio);
  75691. }
  75692. if (this._cameras !== null) {
  75693. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75694. }
  75695. };
  75696. // Down Sample X4 Post-Processs
  75697. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  75698. var _this = this;
  75699. var downSampleX4Offsets = new Array(32);
  75700. 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);
  75701. this.downSampleX4PostProcess.onApply = function (effect) {
  75702. var id = 0;
  75703. var width = _this.downSampleX4PostProcess.width;
  75704. var height = _this.downSampleX4PostProcess.height;
  75705. for (var i = -2; i < 2; i++) {
  75706. for (var j = -2; j < 2; j++) {
  75707. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  75708. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  75709. id += 2;
  75710. }
  75711. }
  75712. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75713. };
  75714. // Add to pipeline
  75715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75716. };
  75717. // Brightpass Post-Process
  75718. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75719. var _this = this;
  75720. var brightOffsets = new Array(8);
  75721. 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);
  75722. this.brightPassPostProcess.onApply = function (effect) {
  75723. var sU = (1.0 / _this.brightPassPostProcess.width);
  75724. var sV = (1.0 / _this.brightPassPostProcess.height);
  75725. brightOffsets[0] = -0.5 * sU;
  75726. brightOffsets[1] = 0.5 * sV;
  75727. brightOffsets[2] = 0.5 * sU;
  75728. brightOffsets[3] = 0.5 * sV;
  75729. brightOffsets[4] = -0.5 * sU;
  75730. brightOffsets[5] = -0.5 * sV;
  75731. brightOffsets[6] = 0.5 * sU;
  75732. brightOffsets[7] = -0.5 * sV;
  75733. effect.setArray2("dsOffsets", brightOffsets);
  75734. effect.setFloat("brightThreshold", _this.brightThreshold);
  75735. };
  75736. // Add to pipeline
  75737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75738. };
  75739. // Create blur H&V post-processes
  75740. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75741. var _this = this;
  75742. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75743. var engine = scene.getEngine();
  75744. 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);
  75745. 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);
  75746. blurX.onActivateObservable.add(function () {
  75747. var dw = blurX.width / engine.getRenderWidth();
  75748. blurX.kernel = _this[blurWidthKey] * dw;
  75749. });
  75750. blurY.onActivateObservable.add(function () {
  75751. var dw = blurY.height / engine.getRenderHeight();
  75752. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75753. });
  75754. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75756. this.blurHPostProcesses.push(blurX);
  75757. this.blurVPostProcesses.push(blurY);
  75758. };
  75759. // Create texture adder post-process
  75760. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75761. var _this = this;
  75762. 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);
  75763. this.textureAdderPostProcess.onApply = function (effect) {
  75764. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75765. effect.setTexture("lensSampler", _this.lensTexture);
  75766. effect.setFloat("exposure", _this.exposure);
  75767. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75768. };
  75769. // Add to pipeline
  75770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75771. };
  75772. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75773. var _this = this;
  75774. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75775. geometryRenderer.enablePosition = true;
  75776. var geometry = geometryRenderer.getGBuffer();
  75777. // Base post-process
  75778. 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));
  75779. var depthValues = BABYLON.Vector2.Zero();
  75780. this.volumetricLightPostProcess.onApply = function (effect) {
  75781. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75782. var generator = _this.sourceLight.getShadowGenerator();
  75783. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75784. effect.setTexture("positionSampler", geometry.textures[2]);
  75785. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75786. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75787. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75788. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75789. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75790. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75791. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75792. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75793. effect.setVector2("depthValues", depthValues);
  75794. }
  75795. };
  75796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75797. // Smooth
  75798. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75799. // Merge
  75800. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75801. this.volumetricLightMergePostProces.onApply = function (effect) {
  75802. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75803. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75804. };
  75805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75806. };
  75807. // Create luminance
  75808. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75809. var _this = this;
  75810. // Create luminance
  75811. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75812. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75813. var offsets = [];
  75814. this.luminancePostProcess.onApply = function (effect) {
  75815. var sU = (1.0 / _this.luminancePostProcess.width);
  75816. var sV = (1.0 / _this.luminancePostProcess.height);
  75817. offsets[0] = -0.5 * sU;
  75818. offsets[1] = 0.5 * sV;
  75819. offsets[2] = 0.5 * sU;
  75820. offsets[3] = 0.5 * sV;
  75821. offsets[4] = -0.5 * sU;
  75822. offsets[5] = -0.5 * sV;
  75823. offsets[6] = 0.5 * sU;
  75824. offsets[7] = -0.5 * sV;
  75825. effect.setArray2("lumOffsets", offsets);
  75826. };
  75827. // Add to pipeline
  75828. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75829. // Create down sample luminance
  75830. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75831. var size = Math.pow(3, i);
  75832. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75833. if (i === 0) {
  75834. defines += "#define FINAL_DOWN_SAMPLER";
  75835. }
  75836. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75837. this.luminanceDownSamplePostProcesses.push(postProcess);
  75838. }
  75839. // Create callbacks and add effects
  75840. var lastLuminance = this.luminancePostProcess;
  75841. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75842. var downSampleOffsets = new Array(18);
  75843. pp.onApply = function (effect) {
  75844. if (!lastLuminance) {
  75845. return;
  75846. }
  75847. var id = 0;
  75848. for (var x = -1; x < 2; x++) {
  75849. for (var y = -1; y < 2; y++) {
  75850. downSampleOffsets[id] = x / lastLuminance.width;
  75851. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75852. id += 2;
  75853. }
  75854. }
  75855. effect.setArray2("dsOffsets", downSampleOffsets);
  75856. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75857. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75858. lastLuminance = _this.luminancePostProcess;
  75859. }
  75860. else {
  75861. lastLuminance = pp;
  75862. }
  75863. };
  75864. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75865. pp.onAfterRender = function (effect) {
  75866. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75867. 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);
  75868. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75869. };
  75870. }
  75871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75872. });
  75873. };
  75874. // Create HDR post-process
  75875. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75876. var _this = this;
  75877. 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);
  75878. var outputLiminance = 1;
  75879. var time = 0;
  75880. var lastTime = 0;
  75881. this.hdrPostProcess.onApply = function (effect) {
  75882. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75883. time += scene.getEngine().getDeltaTime();
  75884. if (outputLiminance < 0) {
  75885. outputLiminance = _this._hdrCurrentLuminance;
  75886. }
  75887. else {
  75888. var dt = (lastTime - time) / 1000.0;
  75889. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75890. outputLiminance += _this.hdrDecreaseRate * dt;
  75891. }
  75892. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75893. outputLiminance -= _this.hdrIncreaseRate * dt;
  75894. }
  75895. else {
  75896. outputLiminance = _this._hdrCurrentLuminance;
  75897. }
  75898. }
  75899. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75900. effect.setFloat("averageLuminance", outputLiminance);
  75901. lastTime = time;
  75902. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75903. };
  75904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75905. };
  75906. // Create lens flare post-process
  75907. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75908. var _this = this;
  75909. 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);
  75910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75911. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75912. 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);
  75913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75914. var resolution = new BABYLON.Vector2(0, 0);
  75915. // Lens flare
  75916. this.lensFlarePostProcess.onApply = function (effect) {
  75917. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75918. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75919. effect.setFloat("strength", _this.lensFlareStrength);
  75920. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75921. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75922. // Shift
  75923. resolution.x = _this.lensFlarePostProcess.width;
  75924. resolution.y = _this.lensFlarePostProcess.height;
  75925. effect.setVector2("resolution", resolution);
  75926. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75927. };
  75928. // Compose
  75929. 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);
  75930. 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);
  75931. this.lensFlareComposePostProcess.onApply = function (effect) {
  75932. if (!_this._scene.activeCamera) {
  75933. return;
  75934. }
  75935. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75936. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75937. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75938. // Lens start rotation matrix
  75939. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75940. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75941. 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));
  75942. camRot *= 4.0;
  75943. 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);
  75944. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75945. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75946. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75947. };
  75948. };
  75949. // Create depth-of-field post-process
  75950. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75951. var _this = this;
  75952. 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);
  75953. this.depthOfFieldPostProcess.onApply = function (effect) {
  75954. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75955. effect.setTexture("depthSampler", _this._getDepthTexture());
  75956. effect.setFloat("distance", _this.depthOfFieldDistance);
  75957. };
  75958. // Add to pipeline
  75959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75960. };
  75961. // Create motion blur post-process
  75962. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75963. var _this = this;
  75964. 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);
  75965. var motionScale = 0;
  75966. var prevViewProjection = BABYLON.Matrix.Identity();
  75967. var invViewProjection = BABYLON.Matrix.Identity();
  75968. var viewProjection = BABYLON.Matrix.Identity();
  75969. var screenSize = BABYLON.Vector2.Zero();
  75970. this.motionBlurPostProcess.onApply = function (effect) {
  75971. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75972. viewProjection.invertToRef(invViewProjection);
  75973. effect.setMatrix("inverseViewProjection", invViewProjection);
  75974. effect.setMatrix("prevViewProjection", prevViewProjection);
  75975. prevViewProjection = viewProjection;
  75976. screenSize.x = _this.motionBlurPostProcess.width;
  75977. screenSize.y = _this.motionBlurPostProcess.height;
  75978. effect.setVector2("screenSize", screenSize);
  75979. motionScale = scene.getEngine().getFps() / 60.0;
  75980. effect.setFloat("motionScale", motionScale);
  75981. effect.setFloat("motionStrength", _this.motionStrength);
  75982. effect.setTexture("depthSampler", _this._getDepthTexture());
  75983. };
  75984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75985. };
  75986. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75987. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75988. var renderer = this._scene.enableGeometryBufferRenderer();
  75989. return renderer.getGBuffer().textures[0];
  75990. }
  75991. return this._scene.enableDepthRenderer().getDepthMap();
  75992. };
  75993. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75994. for (var i = 0; i < this._cameras.length; i++) {
  75995. var camera = this._cameras[i];
  75996. if (this.originalPostProcess) {
  75997. this.originalPostProcess.dispose(camera);
  75998. }
  75999. if (this.downSampleX4PostProcess) {
  76000. this.downSampleX4PostProcess.dispose(camera);
  76001. }
  76002. if (this.brightPassPostProcess) {
  76003. this.brightPassPostProcess.dispose(camera);
  76004. }
  76005. if (this.textureAdderPostProcess) {
  76006. this.textureAdderPostProcess.dispose(camera);
  76007. }
  76008. if (this.textureAdderFinalPostProcess) {
  76009. this.textureAdderFinalPostProcess.dispose(camera);
  76010. }
  76011. if (this.volumetricLightPostProcess) {
  76012. this.volumetricLightPostProcess.dispose(camera);
  76013. }
  76014. if (this.volumetricLightSmoothXPostProcess) {
  76015. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76016. }
  76017. if (this.volumetricLightSmoothYPostProcess) {
  76018. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76019. }
  76020. if (this.volumetricLightMergePostProces) {
  76021. this.volumetricLightMergePostProces.dispose(camera);
  76022. }
  76023. if (this.volumetricLightFinalPostProcess) {
  76024. this.volumetricLightFinalPostProcess.dispose(camera);
  76025. }
  76026. if (this.lensFlarePostProcess) {
  76027. this.lensFlarePostProcess.dispose(camera);
  76028. }
  76029. if (this.lensFlareComposePostProcess) {
  76030. this.lensFlareComposePostProcess.dispose(camera);
  76031. }
  76032. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76033. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76034. }
  76035. if (this.luminancePostProcess) {
  76036. this.luminancePostProcess.dispose(camera);
  76037. }
  76038. if (this.hdrPostProcess) {
  76039. this.hdrPostProcess.dispose(camera);
  76040. }
  76041. if (this.hdrFinalPostProcess) {
  76042. this.hdrFinalPostProcess.dispose(camera);
  76043. }
  76044. if (this.depthOfFieldPostProcess) {
  76045. this.depthOfFieldPostProcess.dispose(camera);
  76046. }
  76047. if (this.motionBlurPostProcess) {
  76048. this.motionBlurPostProcess.dispose(camera);
  76049. }
  76050. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76051. this.blurHPostProcesses[j].dispose(camera);
  76052. }
  76053. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76054. this.blurVPostProcesses[j].dispose(camera);
  76055. }
  76056. }
  76057. this.originalPostProcess = null;
  76058. this.downSampleX4PostProcess = null;
  76059. this.brightPassPostProcess = null;
  76060. this.textureAdderPostProcess = null;
  76061. this.textureAdderFinalPostProcess = null;
  76062. this.volumetricLightPostProcess = null;
  76063. this.volumetricLightSmoothXPostProcess = null;
  76064. this.volumetricLightSmoothYPostProcess = null;
  76065. this.volumetricLightMergePostProces = null;
  76066. this.volumetricLightFinalPostProcess = null;
  76067. this.lensFlarePostProcess = null;
  76068. this.lensFlareComposePostProcess = null;
  76069. this.luminancePostProcess = null;
  76070. this.hdrPostProcess = null;
  76071. this.hdrFinalPostProcess = null;
  76072. this.depthOfFieldPostProcess = null;
  76073. this.motionBlurPostProcess = null;
  76074. this.luminanceDownSamplePostProcesses = [];
  76075. this.blurHPostProcesses = [];
  76076. this.blurVPostProcesses = [];
  76077. };
  76078. /**
  76079. * Dispose of the pipeline and stop all post processes
  76080. */
  76081. StandardRenderingPipeline.prototype.dispose = function () {
  76082. this._disposePostProcesses();
  76083. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76084. _super.prototype.dispose.call(this);
  76085. };
  76086. /**
  76087. * Serialize the rendering pipeline (Used when exporting)
  76088. * @returns the serialized object
  76089. */
  76090. StandardRenderingPipeline.prototype.serialize = function () {
  76091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76092. if (this.sourceLight) {
  76093. serializationObject.sourceLightId = this.sourceLight.id;
  76094. }
  76095. serializationObject.customType = "StandardRenderingPipeline";
  76096. return serializationObject;
  76097. };
  76098. /**
  76099. * Parse the serialized pipeline
  76100. * @param source Source pipeline.
  76101. * @param scene The scene to load the pipeline to.
  76102. * @param rootUrl The URL of the serialized pipeline.
  76103. * @returns An instantiated pipeline from the serialized object.
  76104. */
  76105. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76106. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76107. if (source.sourceLightId) {
  76108. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76109. }
  76110. return p;
  76111. };
  76112. // Luminance steps
  76113. StandardRenderingPipeline.LuminanceSteps = 6;
  76114. __decorate([
  76115. BABYLON.serialize()
  76116. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76117. __decorate([
  76118. BABYLON.serialize()
  76119. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76120. __decorate([
  76121. BABYLON.serialize()
  76122. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76123. __decorate([
  76124. BABYLON.serialize()
  76125. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76126. __decorate([
  76127. BABYLON.serializeAsTexture("lensTexture")
  76128. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76129. __decorate([
  76130. BABYLON.serialize()
  76131. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76132. __decorate([
  76133. BABYLON.serialize()
  76134. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76135. __decorate([
  76136. BABYLON.serialize()
  76137. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76138. __decorate([
  76139. BABYLON.serialize()
  76140. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76141. __decorate([
  76142. BABYLON.serialize()
  76143. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76144. __decorate([
  76145. BABYLON.serialize()
  76146. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76147. __decorate([
  76148. BABYLON.serializeAsTexture("lensColorTexture")
  76149. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76150. __decorate([
  76151. BABYLON.serialize()
  76152. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76153. __decorate([
  76154. BABYLON.serialize()
  76155. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76156. __decorate([
  76157. BABYLON.serialize()
  76158. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76159. __decorate([
  76160. BABYLON.serialize()
  76161. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76162. __decorate([
  76163. BABYLON.serializeAsTexture("lensStarTexture")
  76164. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76165. __decorate([
  76166. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76167. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76168. __decorate([
  76169. BABYLON.serialize()
  76170. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76171. __decorate([
  76172. BABYLON.serialize()
  76173. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76174. __decorate([
  76175. BABYLON.serialize()
  76176. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76177. __decorate([
  76178. BABYLON.serialize()
  76179. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76180. __decorate([
  76181. BABYLON.serialize()
  76182. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76183. __decorate([
  76184. BABYLON.serialize()
  76185. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76186. __decorate([
  76187. BABYLON.serialize()
  76188. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76189. __decorate([
  76190. BABYLON.serialize()
  76191. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76192. __decorate([
  76193. BABYLON.serialize()
  76194. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76195. __decorate([
  76196. BABYLON.serialize()
  76197. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76198. __decorate([
  76199. BABYLON.serialize()
  76200. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76201. __decorate([
  76202. BABYLON.serialize()
  76203. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76204. return StandardRenderingPipeline;
  76205. }(BABYLON.PostProcessRenderPipeline));
  76206. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76207. })(BABYLON || (BABYLON = {}));
  76208. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76209. var BABYLON;
  76210. (function (BABYLON) {
  76211. var FxaaPostProcess = /** @class */ (function (_super) {
  76212. __extends(FxaaPostProcess, _super);
  76213. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76214. if (camera === void 0) { camera = null; }
  76215. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76216. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76217. var defines = _this._getDefines();
  76218. _this.updateEffect(defines);
  76219. _this.onApplyObservable.add(function (effect) {
  76220. var texelSize = _this.texelSize;
  76221. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76222. });
  76223. return _this;
  76224. }
  76225. FxaaPostProcess.prototype._getDefines = function () {
  76226. var engine = this.getEngine();
  76227. if (!engine) {
  76228. return null;
  76229. }
  76230. var glInfo = engine.getGlInfo();
  76231. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76232. return "#define MALI 1\n";
  76233. }
  76234. return null;
  76235. };
  76236. return FxaaPostProcess;
  76237. }(BABYLON.PostProcess));
  76238. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76239. })(BABYLON || (BABYLON = {}));
  76240. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76241. var BABYLON;
  76242. (function (BABYLON) {
  76243. /**
  76244. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76245. */
  76246. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76247. __extends(ChromaticAberrationPostProcess, _super);
  76248. /**
  76249. * Creates a new instance ChromaticAberrationPostProcess
  76250. * @param name The name of the effect.
  76251. * @param screenWidth The width of the screen to apply the effect on.
  76252. * @param screenHeight The height of the screen to apply the effect on.
  76253. * @param options The required width/height ratio to downsize to before computing the render pass.
  76254. * @param camera The camera to apply the render pass to.
  76255. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76256. * @param engine The engine which the post process will be applied. (default: current engine)
  76257. * @param reusable If the post process can be reused on the same frame. (default: false)
  76258. * @param textureType Type of textures used when performing the post process. (default: 0)
  76259. * @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)
  76260. */
  76261. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76262. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76263. if (blockCompilation === void 0) { blockCompilation = false; }
  76264. 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;
  76265. /**
  76266. * The amount of seperation of rgb channels (default: 30)
  76267. */
  76268. _this.aberrationAmount = 30;
  76269. /**
  76270. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76271. */
  76272. _this.radialIntensity = 0;
  76273. /**
  76274. * 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))
  76275. */
  76276. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76277. /**
  76278. * 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))
  76279. */
  76280. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76281. _this.onApplyObservable.add(function (effect) {
  76282. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76283. effect.setFloat('screen_width', screenWidth);
  76284. effect.setFloat('screen_height', screenHeight);
  76285. effect.setFloat('radialIntensity', _this.radialIntensity);
  76286. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76287. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76288. });
  76289. return _this;
  76290. }
  76291. return ChromaticAberrationPostProcess;
  76292. }(BABYLON.PostProcess));
  76293. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76294. })(BABYLON || (BABYLON = {}));
  76295. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76296. var BABYLON;
  76297. (function (BABYLON) {
  76298. /**
  76299. * The GrainPostProcess adds noise to the image at mid luminance levels
  76300. */
  76301. var GrainPostProcess = /** @class */ (function (_super) {
  76302. __extends(GrainPostProcess, _super);
  76303. /**
  76304. * Creates a new instance of @see GrainPostProcess
  76305. * @param name The name of the effect.
  76306. * @param options The required width/height ratio to downsize to before computing the render pass.
  76307. * @param camera The camera to apply the render pass to.
  76308. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76309. * @param engine The engine which the post process will be applied. (default: current engine)
  76310. * @param reusable If the post process can be reused on the same frame. (default: false)
  76311. * @param textureType Type of textures used when performing the post process. (default: 0)
  76312. * @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)
  76313. */
  76314. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76316. if (blockCompilation === void 0) { blockCompilation = false; }
  76317. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76318. /**
  76319. * The intensity of the grain added (default: 30)
  76320. */
  76321. _this.intensity = 30;
  76322. /**
  76323. * If the grain should be randomized on every frame
  76324. */
  76325. _this.animated = false;
  76326. _this.onApplyObservable.add(function (effect) {
  76327. effect.setFloat('intensity', _this.intensity);
  76328. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76329. });
  76330. return _this;
  76331. }
  76332. return GrainPostProcess;
  76333. }(BABYLON.PostProcess));
  76334. BABYLON.GrainPostProcess = GrainPostProcess;
  76335. })(BABYLON || (BABYLON = {}));
  76336. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76337. var BABYLON;
  76338. (function (BABYLON) {
  76339. /**
  76340. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76341. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76342. */
  76343. var SharpenPostProcess = /** @class */ (function (_super) {
  76344. __extends(SharpenPostProcess, _super);
  76345. /**
  76346. * Creates a new instance ConvolutionPostProcess
  76347. * @param name The name of the effect.
  76348. * @param options The required width/height ratio to downsize to before computing the render pass.
  76349. * @param camera The camera to apply the render pass to.
  76350. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76351. * @param engine The engine which the post process will be applied. (default: current engine)
  76352. * @param reusable If the post process can be reused on the same frame. (default: false)
  76353. * @param textureType Type of textures used when performing the post process. (default: 0)
  76354. * @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)
  76355. */
  76356. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76358. if (blockCompilation === void 0) { blockCompilation = false; }
  76359. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76360. /**
  76361. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76362. */
  76363. _this.colorAmount = 1.0;
  76364. /**
  76365. * How much sharpness should be applied (default: 0.3)
  76366. */
  76367. _this.edgeAmount = 0.3;
  76368. _this.onApply = function (effect) {
  76369. effect.setFloat2("screenSize", _this.width, _this.height);
  76370. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76371. };
  76372. return _this;
  76373. }
  76374. return SharpenPostProcess;
  76375. }(BABYLON.PostProcess));
  76376. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76377. })(BABYLON || (BABYLON = {}));
  76378. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76379. var BABYLON;
  76380. (function (BABYLON) {
  76381. /**
  76382. * The Blur Post Process which blurs an image based on a kernel and direction.
  76383. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76384. */
  76385. var BlurPostProcess = /** @class */ (function (_super) {
  76386. __extends(BlurPostProcess, _super);
  76387. /**
  76388. * Creates a new instance BlurPostProcess
  76389. * @param name The name of the effect.
  76390. * @param direction The direction in which to blur the image.
  76391. * @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.
  76392. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76393. * @param camera The camera to apply the render pass to.
  76394. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76395. * @param engine The engine which the post process will be applied. (default: current engine)
  76396. * @param reusable If the post process can be reused on the same frame. (default: false)
  76397. * @param textureType Type of textures used when performing the post process. (default: 0)
  76398. * @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)
  76399. */
  76400. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76402. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76403. if (defines === void 0) { defines = ""; }
  76404. if (blockCompilation === void 0) { blockCompilation = false; }
  76405. 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;
  76406. _this.direction = direction;
  76407. _this.blockCompilation = blockCompilation;
  76408. _this._packedFloat = false;
  76409. _this._staticDefines = "";
  76410. _this._staticDefines = defines;
  76411. _this.onApplyObservable.add(function (effect) {
  76412. if (_this._outputTexture) {
  76413. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76414. }
  76415. else {
  76416. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76417. }
  76418. });
  76419. _this.kernel = kernel;
  76420. return _this;
  76421. }
  76422. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76423. /**
  76424. * Gets the length in pixels of the blur sample region
  76425. */
  76426. get: function () {
  76427. return this._idealKernel;
  76428. },
  76429. /**
  76430. * Sets the length in pixels of the blur sample region
  76431. */
  76432. set: function (v) {
  76433. if (this._idealKernel === v) {
  76434. return;
  76435. }
  76436. v = Math.max(v, 1);
  76437. this._idealKernel = v;
  76438. this._kernel = this._nearestBestKernel(v);
  76439. if (!this.blockCompilation) {
  76440. this._updateParameters();
  76441. }
  76442. },
  76443. enumerable: true,
  76444. configurable: true
  76445. });
  76446. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76447. /**
  76448. * Gets wether or not the blur is unpacking/repacking floats
  76449. */
  76450. get: function () {
  76451. return this._packedFloat;
  76452. },
  76453. /**
  76454. * Sets wether or not the blur needs to unpack/repack floats
  76455. */
  76456. set: function (v) {
  76457. if (this._packedFloat === v) {
  76458. return;
  76459. }
  76460. this._packedFloat = v;
  76461. if (!this.blockCompilation) {
  76462. this._updateParameters();
  76463. }
  76464. },
  76465. enumerable: true,
  76466. configurable: true
  76467. });
  76468. /**
  76469. * Updates the effect with the current post process compile time values and recompiles the shader.
  76470. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76471. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76472. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76473. * @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
  76474. * @param onCompiled Called when the shader has been compiled.
  76475. * @param onError Called if there is an error when compiling a shader.
  76476. */
  76477. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76478. if (defines === void 0) { defines = null; }
  76479. if (uniforms === void 0) { uniforms = null; }
  76480. if (samplers === void 0) { samplers = null; }
  76481. this._updateParameters(onCompiled, onError);
  76482. };
  76483. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76484. // Generate sampling offsets and weights
  76485. var N = this._kernel;
  76486. var centerIndex = (N - 1) / 2;
  76487. // Generate Gaussian sampling weights over kernel
  76488. var offsets = [];
  76489. var weights = [];
  76490. var totalWeight = 0;
  76491. for (var i = 0; i < N; i++) {
  76492. var u = i / (N - 1);
  76493. var w = this._gaussianWeight(u * 2.0 - 1);
  76494. offsets[i] = (i - centerIndex);
  76495. weights[i] = w;
  76496. totalWeight += w;
  76497. }
  76498. // Normalize weights
  76499. for (var i = 0; i < weights.length; i++) {
  76500. weights[i] /= totalWeight;
  76501. }
  76502. // Optimize: combine samples to take advantage of hardware linear sampling
  76503. // Walk from left to center, combining pairs (symmetrically)
  76504. var linearSamplingWeights = [];
  76505. var linearSamplingOffsets = [];
  76506. var linearSamplingMap = [];
  76507. for (var i = 0; i <= centerIndex; i += 2) {
  76508. var j = Math.min(i + 1, Math.floor(centerIndex));
  76509. var singleCenterSample = i === j;
  76510. if (singleCenterSample) {
  76511. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76512. }
  76513. else {
  76514. var sharedCell = j === centerIndex;
  76515. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76516. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76517. if (offsetLinear === 0) {
  76518. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76519. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76520. }
  76521. else {
  76522. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76523. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76524. }
  76525. }
  76526. }
  76527. for (var i = 0; i < linearSamplingMap.length; i++) {
  76528. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76529. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76530. }
  76531. // Replace with optimized
  76532. offsets = linearSamplingOffsets;
  76533. weights = linearSamplingWeights;
  76534. // Generate shaders
  76535. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76536. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76537. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76538. var defines = "";
  76539. defines += this._staticDefines;
  76540. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76541. if (this._staticDefines.indexOf("DOF") != -1) {
  76542. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76543. varyingCount--;
  76544. }
  76545. for (var i = 0; i < varyingCount; i++) {
  76546. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76547. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76548. }
  76549. var depCount = 0;
  76550. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76551. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76552. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76553. depCount++;
  76554. }
  76555. if (this.packedFloat) {
  76556. defines += "#define PACKEDFLOAT 1";
  76557. }
  76558. this.blockCompilation = false;
  76559. _super.prototype.updateEffect.call(this, defines, null, null, {
  76560. varyingCount: varyingCount,
  76561. depCount: depCount
  76562. }, onCompiled, onError);
  76563. };
  76564. /**
  76565. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76566. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76567. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76568. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76569. * The gaps between physical kernels are compensated for in the weighting of the samples
  76570. * @param idealKernel Ideal blur kernel.
  76571. * @return Nearest best kernel.
  76572. */
  76573. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76574. var v = Math.round(idealKernel);
  76575. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76576. var k = _a[_i];
  76577. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76578. return Math.max(k, 3);
  76579. }
  76580. }
  76581. return Math.max(v, 3);
  76582. };
  76583. /**
  76584. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76585. * @param x The point on the Gaussian distribution to sample.
  76586. * @return the value of the Gaussian function at x.
  76587. */
  76588. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76589. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76590. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76591. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76592. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76593. // truncated at around 1.3% of peak strength.
  76594. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76595. var sigma = (1 / 3);
  76596. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76597. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76598. var weight = (1.0 / denominator) * Math.exp(exponent);
  76599. return weight;
  76600. };
  76601. /**
  76602. * Generates a string that can be used as a floating point number in GLSL.
  76603. * @param x Value to print.
  76604. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76605. * @return GLSL float string.
  76606. */
  76607. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76608. if (decimalFigures === void 0) { decimalFigures = 8; }
  76609. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76610. };
  76611. return BlurPostProcess;
  76612. }(BABYLON.PostProcess));
  76613. BABYLON.BlurPostProcess = BlurPostProcess;
  76614. })(BABYLON || (BABYLON = {}));
  76615. //# sourceMappingURL=babylon.blurPostProcess.js.map
  76616. var BABYLON;
  76617. (function (BABYLON) {
  76618. /**
  76619. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  76620. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  76621. * based on samples that have a large difference in distance than the center pixel.
  76622. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76623. */
  76624. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  76625. __extends(DepthOfFieldBlurPostProcess, _super);
  76626. /**
  76627. * Creates a new instance CircleOfConfusionPostProcess
  76628. * @param name The name of the effect.
  76629. * @param scene The scene the effect belongs to.
  76630. * @param direction The direction the blur should be applied.
  76631. * @param kernel The size of the kernel used to blur.
  76632. * @param options The required width/height ratio to downsize to before computing the render pass.
  76633. * @param camera The camera to apply the render pass to.
  76634. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  76635. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  76636. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76637. * @param engine The engine which the post process will be applied. (default: current engine)
  76638. * @param reusable If the post process can be reused on the same frame. (default: false)
  76639. * @param textureType Type of textures used when performing the post process. (default: 0)
  76640. * @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)
  76641. */
  76642. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  76643. if (imageToBlur === void 0) { imageToBlur = null; }
  76644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76645. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76646. if (blockCompilation === void 0) { blockCompilation = false; }
  76647. 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;
  76648. _this.direction = direction;
  76649. _this.onApplyObservable.add(function (effect) {
  76650. if (imageToBlur != null) {
  76651. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  76652. }
  76653. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76654. if (scene.activeCamera) {
  76655. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76656. }
  76657. });
  76658. return _this;
  76659. }
  76660. return DepthOfFieldBlurPostProcess;
  76661. }(BABYLON.BlurPostProcess));
  76662. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  76663. })(BABYLON || (BABYLON = {}));
  76664. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  76665. var BABYLON;
  76666. (function (BABYLON) {
  76667. /**
  76668. * Options to be set when merging outputs from the default pipeline.
  76669. */
  76670. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  76671. function DepthOfFieldMergePostProcessOptions() {
  76672. }
  76673. return DepthOfFieldMergePostProcessOptions;
  76674. }());
  76675. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  76676. /**
  76677. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76678. */
  76679. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  76680. __extends(DepthOfFieldMergePostProcess, _super);
  76681. /**
  76682. * Creates a new instance of DepthOfFieldMergePostProcess
  76683. * @param name The name of the effect.
  76684. * @param originalFromInput Post process which's input will be used for the merge.
  76685. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  76686. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  76687. * @param options The required width/height ratio to downsize to before computing the render pass.
  76688. * @param camera The camera to apply the render pass to.
  76689. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76690. * @param engine The engine which the post process will be applied. (default: current engine)
  76691. * @param reusable If the post process can be reused on the same frame. (default: false)
  76692. * @param textureType Type of textures used when performing the post process. (default: 0)
  76693. * @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)
  76694. */
  76695. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76696. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76697. if (blockCompilation === void 0) { blockCompilation = false; }
  76698. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76699. _this.blurSteps = blurSteps;
  76700. _this.onApplyObservable.add(function (effect) {
  76701. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76702. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76703. blurSteps.forEach(function (step, index) {
  76704. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  76705. });
  76706. });
  76707. if (!blockCompilation) {
  76708. _this.updateEffect();
  76709. }
  76710. return _this;
  76711. }
  76712. /**
  76713. * Updates the effect with the current post process compile time values and recompiles the shader.
  76714. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76715. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76716. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76717. * @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
  76718. * @param onCompiled Called when the shader has been compiled.
  76719. * @param onError Called if there is an error when compiling a shader.
  76720. */
  76721. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76722. if (defines === void 0) { defines = null; }
  76723. if (uniforms === void 0) { uniforms = null; }
  76724. if (samplers === void 0) { samplers = null; }
  76725. if (!defines) {
  76726. defines = "";
  76727. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76728. }
  76729. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76730. };
  76731. return DepthOfFieldMergePostProcess;
  76732. }(BABYLON.PostProcess));
  76733. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76734. })(BABYLON || (BABYLON = {}));
  76735. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76736. var BABYLON;
  76737. (function (BABYLON) {
  76738. /**
  76739. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76740. */
  76741. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76742. __extends(CircleOfConfusionPostProcess, _super);
  76743. /**
  76744. * Creates a new instance CircleOfConfusionPostProcess
  76745. * @param name The name of the effect.
  76746. * @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.
  76747. * @param options The required width/height ratio to downsize to before computing the render pass.
  76748. * @param camera The camera to apply the render pass to.
  76749. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76750. * @param engine The engine which the post process will be applied. (default: current engine)
  76751. * @param reusable If the post process can be reused on the same frame. (default: false)
  76752. * @param textureType Type of textures used when performing the post process. (default: 0)
  76753. * @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)
  76754. */
  76755. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76756. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76757. if (blockCompilation === void 0) { blockCompilation = false; }
  76758. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76759. /**
  76760. * 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.
  76761. */
  76762. _this.lensSize = 50;
  76763. /**
  76764. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76765. */
  76766. _this.fStop = 1.4;
  76767. /**
  76768. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76769. */
  76770. _this.focusDistance = 2000;
  76771. /**
  76772. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76773. */
  76774. _this.focalLength = 50;
  76775. _this._depthTexture = null;
  76776. _this._depthTexture = depthTexture;
  76777. _this.onApplyObservable.add(function (effect) {
  76778. if (!_this._depthTexture) {
  76779. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76780. return;
  76781. }
  76782. effect.setTexture("depthSampler", _this._depthTexture);
  76783. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76784. var aperture = _this.lensSize / _this.fStop;
  76785. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76786. effect.setFloat('focusDistance', _this.focusDistance);
  76787. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76788. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76789. });
  76790. return _this;
  76791. }
  76792. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76793. /**
  76794. * 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.
  76795. */
  76796. set: function (value) {
  76797. this._depthTexture = value;
  76798. },
  76799. enumerable: true,
  76800. configurable: true
  76801. });
  76802. return CircleOfConfusionPostProcess;
  76803. }(BABYLON.PostProcess));
  76804. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76805. })(BABYLON || (BABYLON = {}));
  76806. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76807. var BABYLON;
  76808. (function (BABYLON) {
  76809. /**
  76810. * Specifies the level of max blur that should be applied when using the depth of field effect
  76811. */
  76812. var DepthOfFieldEffectBlurLevel;
  76813. (function (DepthOfFieldEffectBlurLevel) {
  76814. /**
  76815. * Subtle blur
  76816. */
  76817. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76818. /**
  76819. * Medium blur
  76820. */
  76821. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76822. /**
  76823. * Large blur
  76824. */
  76825. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76826. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76827. ;
  76828. /**
  76829. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76830. */
  76831. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76832. __extends(DepthOfFieldEffect, _super);
  76833. /**
  76834. * Creates a new instance DepthOfFieldEffect
  76835. * @param scene The scene the effect belongs to.
  76836. * @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.
  76837. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76838. * @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)
  76839. */
  76840. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76841. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76842. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76843. if (blockCompilation === void 0) { blockCompilation = false; }
  76844. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76845. return _this._effects;
  76846. }, true) || this;
  76847. /**
  76848. * Internal post processes in depth of field effect
  76849. */
  76850. _this._effects = [];
  76851. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76852. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76853. // 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)
  76854. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76855. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76856. _this._depthOfFieldBlurY = [];
  76857. _this._depthOfFieldBlurX = [];
  76858. var blurCount = 1;
  76859. var kernelSize = 15;
  76860. switch (blurLevel) {
  76861. case DepthOfFieldEffectBlurLevel.High: {
  76862. blurCount = 3;
  76863. kernelSize = 51;
  76864. break;
  76865. }
  76866. case DepthOfFieldEffectBlurLevel.Medium: {
  76867. blurCount = 2;
  76868. kernelSize = 31;
  76869. break;
  76870. }
  76871. default: {
  76872. kernelSize = 15;
  76873. blurCount = 1;
  76874. break;
  76875. }
  76876. }
  76877. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76878. var ratio = 1.0;
  76879. for (var i = 0; i < blurCount; i++) {
  76880. 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);
  76881. blurY.autoClear = false;
  76882. ratio = 0.75 / Math.pow(2, i);
  76883. 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);
  76884. blurX.autoClear = false;
  76885. _this._depthOfFieldBlurY.push(blurY);
  76886. _this._depthOfFieldBlurX.push(blurX);
  76887. }
  76888. // Set all post processes on the effect.
  76889. _this._effects = [_this._circleOfConfusion];
  76890. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76891. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76892. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76893. }
  76894. // Merge blurred images with original image based on circleOfConfusion
  76895. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76896. _this._dofMerge.autoClear = false;
  76897. _this._effects.push(_this._dofMerge);
  76898. return _this;
  76899. }
  76900. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76901. get: function () {
  76902. return this._circleOfConfusion.focalLength;
  76903. },
  76904. /**
  76905. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76906. */
  76907. set: function (value) {
  76908. this._circleOfConfusion.focalLength = value;
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76914. get: function () {
  76915. return this._circleOfConfusion.fStop;
  76916. },
  76917. /**
  76918. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76919. */
  76920. set: function (value) {
  76921. this._circleOfConfusion.fStop = value;
  76922. },
  76923. enumerable: true,
  76924. configurable: true
  76925. });
  76926. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76927. get: function () {
  76928. return this._circleOfConfusion.focusDistance;
  76929. },
  76930. /**
  76931. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76932. */
  76933. set: function (value) {
  76934. this._circleOfConfusion.focusDistance = value;
  76935. },
  76936. enumerable: true,
  76937. configurable: true
  76938. });
  76939. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76940. get: function () {
  76941. return this._circleOfConfusion.lensSize;
  76942. },
  76943. /**
  76944. * 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.
  76945. */
  76946. set: function (value) {
  76947. this._circleOfConfusion.lensSize = value;
  76948. },
  76949. enumerable: true,
  76950. configurable: true
  76951. });
  76952. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76953. /**
  76954. * 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.
  76955. */
  76956. set: function (value) {
  76957. this._circleOfConfusion.depthTexture = value;
  76958. },
  76959. enumerable: true,
  76960. configurable: true
  76961. });
  76962. /**
  76963. * Disposes each of the internal effects for a given camera.
  76964. * @param camera The camera to dispose the effect on.
  76965. */
  76966. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76967. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76968. this._effects[effectIndex].dispose(camera);
  76969. }
  76970. };
  76971. /**
  76972. * Internal
  76973. */
  76974. DepthOfFieldEffect.prototype._updateEffects = function () {
  76975. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76976. this._effects[effectIndex].updateEffect();
  76977. }
  76978. };
  76979. /**
  76980. * Internal
  76981. * @returns if all the contained post processes are ready.
  76982. */
  76983. DepthOfFieldEffect.prototype._isReady = function () {
  76984. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76985. if (!this._effects[effectIndex].isReady()) {
  76986. return false;
  76987. }
  76988. }
  76989. return true;
  76990. };
  76991. return DepthOfFieldEffect;
  76992. }(BABYLON.PostProcessRenderEffect));
  76993. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76994. })(BABYLON || (BABYLON = {}));
  76995. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76996. var BABYLON;
  76997. (function (BABYLON) {
  76998. /**
  76999. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77000. */
  77001. var BloomMergePostProcess = /** @class */ (function (_super) {
  77002. __extends(BloomMergePostProcess, _super);
  77003. /**
  77004. * Creates a new instance of @see BloomMergePostProcess
  77005. * @param name The name of the effect.
  77006. * @param originalFromInput Post process which's input will be used for the merge.
  77007. * @param blurred Blurred highlights post process which's output will be used.
  77008. * @param weight Weight of the bloom to be added to the original input.
  77009. * @param options The required width/height ratio to downsize to before computing the render pass.
  77010. * @param camera The camera to apply the render pass to.
  77011. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77012. * @param engine The engine which the post process will be applied. (default: current engine)
  77013. * @param reusable If the post process can be reused on the same frame. (default: false)
  77014. * @param textureType Type of textures used when performing the post process. (default: 0)
  77015. * @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)
  77016. */
  77017. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77018. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77019. if (blockCompilation === void 0) { blockCompilation = false; }
  77020. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77021. _this.weight = weight;
  77022. _this.onApplyObservable.add(function (effect) {
  77023. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77024. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77025. effect.setFloat("bloomWeight", _this.weight);
  77026. });
  77027. if (!blockCompilation) {
  77028. _this.updateEffect();
  77029. }
  77030. return _this;
  77031. }
  77032. return BloomMergePostProcess;
  77033. }(BABYLON.PostProcess));
  77034. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77035. })(BABYLON || (BABYLON = {}));
  77036. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77037. var BABYLON;
  77038. (function (BABYLON) {
  77039. /**
  77040. * 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.
  77041. */
  77042. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77043. __extends(ExtractHighlightsPostProcess, _super);
  77044. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77045. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77046. if (blockCompilation === void 0) { blockCompilation = false; }
  77047. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77048. /**
  77049. * The luminance threshold, pixels below this value will be set to black.
  77050. */
  77051. _this.threshold = 0.9;
  77052. /**
  77053. * Internal
  77054. */
  77055. _this._exposure = 1;
  77056. /**
  77057. * Post process which has the input texture to be used when performing highlight extraction
  77058. */
  77059. _this._inputPostProcess = null;
  77060. _this.onApplyObservable.add(function (effect) {
  77061. if (_this._inputPostProcess) {
  77062. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77063. }
  77064. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77065. effect.setFloat('exposure', _this._exposure);
  77066. });
  77067. return _this;
  77068. }
  77069. return ExtractHighlightsPostProcess;
  77070. }(BABYLON.PostProcess));
  77071. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77072. })(BABYLON || (BABYLON = {}));
  77073. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77074. var BABYLON;
  77075. (function (BABYLON) {
  77076. /**
  77077. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77078. */
  77079. var BloomEffect = /** @class */ (function (_super) {
  77080. __extends(BloomEffect, _super);
  77081. /**
  77082. * Creates a new instance of @see BloomEffect
  77083. * @param scene The scene the effect belongs to.
  77084. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77085. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77086. * @param bloomWeight The the strength of bloom.
  77087. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77088. * @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)
  77089. */
  77090. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77091. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77092. if (blockCompilation === void 0) { blockCompilation = false; }
  77093. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77094. return _this._effects;
  77095. }, true) || this;
  77096. _this.bloomScale = bloomScale;
  77097. /**
  77098. * Internal
  77099. */
  77100. _this._effects = [];
  77101. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77102. _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);
  77103. _this._blurX.alwaysForcePOT = true;
  77104. _this._blurX.autoClear = false;
  77105. _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);
  77106. _this._blurY.alwaysForcePOT = true;
  77107. _this._blurY.autoClear = false;
  77108. _this.kernel = bloomKernel;
  77109. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77110. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77111. _this._merge.autoClear = false;
  77112. _this._effects.push(_this._merge);
  77113. return _this;
  77114. }
  77115. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77116. /**
  77117. * The luminance threshold to find bright areas of the image to bloom.
  77118. */
  77119. get: function () {
  77120. return this._downscale.threshold;
  77121. },
  77122. set: function (value) {
  77123. this._downscale.threshold = value;
  77124. },
  77125. enumerable: true,
  77126. configurable: true
  77127. });
  77128. Object.defineProperty(BloomEffect.prototype, "weight", {
  77129. /**
  77130. * The strength of the bloom.
  77131. */
  77132. get: function () {
  77133. return this._merge.weight;
  77134. },
  77135. set: function (value) {
  77136. this._merge.weight = value;
  77137. },
  77138. enumerable: true,
  77139. configurable: true
  77140. });
  77141. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77142. /**
  77143. * Specifies the size of the bloom blur kernel, relative to the final output size
  77144. */
  77145. get: function () {
  77146. return this._blurX.kernel / this.bloomScale;
  77147. },
  77148. set: function (value) {
  77149. this._blurX.kernel = value * this.bloomScale;
  77150. this._blurY.kernel = value * this.bloomScale;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. /**
  77156. * Disposes each of the internal effects for a given camera.
  77157. * @param camera The camera to dispose the effect on.
  77158. */
  77159. BloomEffect.prototype.disposeEffects = function (camera) {
  77160. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77161. this._effects[effectIndex].dispose(camera);
  77162. }
  77163. };
  77164. /**
  77165. * Internal
  77166. */
  77167. BloomEffect.prototype._updateEffects = function () {
  77168. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77169. this._effects[effectIndex].updateEffect();
  77170. }
  77171. };
  77172. /**
  77173. * Internal
  77174. * @returns if all the contained post processes are ready.
  77175. */
  77176. BloomEffect.prototype._isReady = function () {
  77177. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77178. if (!this._effects[effectIndex].isReady()) {
  77179. return false;
  77180. }
  77181. }
  77182. return true;
  77183. };
  77184. return BloomEffect;
  77185. }(BABYLON.PostProcessRenderEffect));
  77186. BABYLON.BloomEffect = BloomEffect;
  77187. })(BABYLON || (BABYLON = {}));
  77188. //# sourceMappingURL=babylon.bloomEffect.js.map
  77189. var BABYLON;
  77190. (function (BABYLON) {
  77191. /**
  77192. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77193. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77194. */
  77195. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77196. __extends(DefaultRenderingPipeline, _super);
  77197. /**
  77198. * @constructor
  77199. * @param {string} name - The rendering pipeline name (default: "")
  77200. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77201. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77202. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77203. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77204. */
  77205. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77206. if (name === void 0) { name = ""; }
  77207. if (hdr === void 0) { hdr = true; }
  77208. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77209. if (automaticBuild === void 0) { automaticBuild = true; }
  77210. var _this = _super.call(this, scene.getEngine(), name) || this;
  77211. _this._camerasToBeAttached = [];
  77212. /**
  77213. * ID of the sharpen post process,
  77214. */
  77215. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77216. /**
  77217. * ID of the image processing post process;
  77218. */
  77219. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77220. /**
  77221. * ID of the Fast Approximate Anti-Aliasing post process;
  77222. */
  77223. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77224. /**
  77225. * ID of the chromatic aberration post process,
  77226. */
  77227. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77228. /**
  77229. * ID of the grain post process
  77230. */
  77231. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77232. /**
  77233. * Glow post process which adds a glow to emmisive areas of the image
  77234. */
  77235. _this._glowLayer = null;
  77236. /**
  77237. * Animations which can be used to tweak settings over a period of time
  77238. */
  77239. _this.animations = [];
  77240. _this._imageProcessingConfigurationObserver = null;
  77241. // Values
  77242. _this._sharpenEnabled = false;
  77243. _this._bloomEnabled = false;
  77244. _this._depthOfFieldEnabled = false;
  77245. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77246. _this._fxaaEnabled = false;
  77247. _this._imageProcessingEnabled = true;
  77248. _this._bloomScale = 0.5;
  77249. _this._chromaticAberrationEnabled = false;
  77250. _this._grainEnabled = false;
  77251. _this._buildAllowed = true;
  77252. _this._resizeObserver = null;
  77253. _this._hardwareScaleLevel = 1.0;
  77254. _this._bloomKernel = 64;
  77255. /**
  77256. * Specifies the weight of the bloom in the final rendering
  77257. */
  77258. _this._bloomWeight = 0.15;
  77259. /**
  77260. * Specifies the luma threshold for the area that will be blurred by the bloom
  77261. */
  77262. _this._bloomThreshold = 0.9;
  77263. _this._samples = 1;
  77264. _this._hasCleared = false;
  77265. _this._prevPostProcess = null;
  77266. _this._prevPrevPostProcess = null;
  77267. _this._cameras = cameras || scene.cameras;
  77268. _this._camerasToBeAttached = _this._cameras.slice();
  77269. _this._buildAllowed = automaticBuild;
  77270. // Initialize
  77271. _this._scene = scene;
  77272. var caps = _this._scene.getEngine().getCaps();
  77273. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77274. // Misc
  77275. if (_this._hdr) {
  77276. if (caps.textureHalfFloatRender) {
  77277. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77278. }
  77279. else if (caps.textureFloatRender) {
  77280. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77281. }
  77282. }
  77283. else {
  77284. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77285. }
  77286. // Attach
  77287. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77288. var engine = _this._scene.getEngine();
  77289. // Create post processes before hand so they can be modified before enabled.
  77290. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77291. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77292. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77293. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77294. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77295. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77296. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77297. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77298. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77299. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77300. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77301. _this.bloomKernel = _this.bloomKernel;
  77302. });
  77303. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77304. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77305. });
  77306. _this._buildPipeline();
  77307. return _this;
  77308. }
  77309. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77310. get: function () {
  77311. return this._sharpenEnabled;
  77312. },
  77313. /**
  77314. * Enable or disable the sharpen process from the pipeline
  77315. */
  77316. set: function (enabled) {
  77317. if (this._sharpenEnabled === enabled) {
  77318. return;
  77319. }
  77320. this._sharpenEnabled = enabled;
  77321. this._buildPipeline();
  77322. },
  77323. enumerable: true,
  77324. configurable: true
  77325. });
  77326. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77327. /**
  77328. * Specifies the size of the bloom blur kernel, relative to the final output size
  77329. */
  77330. get: function () {
  77331. return this._bloomKernel;
  77332. },
  77333. set: function (value) {
  77334. this._bloomKernel = value;
  77335. this.bloom.kernel = value / this._hardwareScaleLevel;
  77336. },
  77337. enumerable: true,
  77338. configurable: true
  77339. });
  77340. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77341. get: function () {
  77342. return this._bloomWeight;
  77343. },
  77344. /**
  77345. * The strength of the bloom.
  77346. */
  77347. set: function (value) {
  77348. if (this._bloomWeight === value) {
  77349. return;
  77350. }
  77351. this.bloom.weight = value;
  77352. this._bloomWeight = value;
  77353. },
  77354. enumerable: true,
  77355. configurable: true
  77356. });
  77357. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77358. get: function () {
  77359. return this._bloomThreshold;
  77360. },
  77361. /**
  77362. * The strength of the bloom.
  77363. */
  77364. set: function (value) {
  77365. if (this._bloomThreshold === value) {
  77366. return;
  77367. }
  77368. this.bloom.threshold = value;
  77369. this._bloomThreshold = value;
  77370. },
  77371. enumerable: true,
  77372. configurable: true
  77373. });
  77374. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77375. get: function () {
  77376. return this._bloomScale;
  77377. },
  77378. /**
  77379. * The scale of the bloom, lower value will provide better performance.
  77380. */
  77381. set: function (value) {
  77382. if (this._bloomScale === value) {
  77383. return;
  77384. }
  77385. this._bloomScale = value;
  77386. // recreate bloom and dispose old as this setting is not dynamic
  77387. this._rebuildBloom();
  77388. this._buildPipeline();
  77389. },
  77390. enumerable: true,
  77391. configurable: true
  77392. });
  77393. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77394. get: function () {
  77395. return this._bloomEnabled;
  77396. },
  77397. /**
  77398. * Enable or disable the bloom from the pipeline
  77399. */
  77400. set: function (enabled) {
  77401. if (this._bloomEnabled === enabled) {
  77402. return;
  77403. }
  77404. this._bloomEnabled = enabled;
  77405. this._buildPipeline();
  77406. },
  77407. enumerable: true,
  77408. configurable: true
  77409. });
  77410. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77411. // recreate bloom and dispose old as this setting is not dynamic
  77412. var oldBloom = this.bloom;
  77413. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77414. this.bloom.threshold = oldBloom.threshold;
  77415. for (var i = 0; i < this._cameras.length; i++) {
  77416. oldBloom.disposeEffects(this._cameras[i]);
  77417. }
  77418. };
  77419. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77420. /**
  77421. * If the depth of field is enabled.
  77422. */
  77423. get: function () {
  77424. return this._depthOfFieldEnabled;
  77425. },
  77426. set: function (enabled) {
  77427. if (this._depthOfFieldEnabled === enabled) {
  77428. return;
  77429. }
  77430. this._depthOfFieldEnabled = enabled;
  77431. this._buildPipeline();
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77437. /**
  77438. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77439. */
  77440. get: function () {
  77441. return this._depthOfFieldBlurLevel;
  77442. },
  77443. set: function (value) {
  77444. if (this._depthOfFieldBlurLevel === value) {
  77445. return;
  77446. }
  77447. this._depthOfFieldBlurLevel = value;
  77448. // recreate dof and dispose old as this setting is not dynamic
  77449. var oldDof = this.depthOfField;
  77450. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77451. this.depthOfField.focalLength = oldDof.focalLength;
  77452. this.depthOfField.focusDistance = oldDof.focusDistance;
  77453. this.depthOfField.fStop = oldDof.fStop;
  77454. this.depthOfField.lensSize = oldDof.lensSize;
  77455. for (var i = 0; i < this._cameras.length; i++) {
  77456. oldDof.disposeEffects(this._cameras[i]);
  77457. }
  77458. this._buildPipeline();
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77464. get: function () {
  77465. return this._fxaaEnabled;
  77466. },
  77467. /**
  77468. * If the anti aliasing is enabled.
  77469. */
  77470. set: function (enabled) {
  77471. if (this._fxaaEnabled === enabled) {
  77472. return;
  77473. }
  77474. this._fxaaEnabled = enabled;
  77475. this._buildPipeline();
  77476. },
  77477. enumerable: true,
  77478. configurable: true
  77479. });
  77480. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77481. get: function () {
  77482. return this._samples;
  77483. },
  77484. /**
  77485. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77486. */
  77487. set: function (sampleCount) {
  77488. if (this._samples === sampleCount) {
  77489. return;
  77490. }
  77491. this._samples = sampleCount;
  77492. this._buildPipeline();
  77493. },
  77494. enumerable: true,
  77495. configurable: true
  77496. });
  77497. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77498. get: function () {
  77499. return this._imageProcessingEnabled;
  77500. },
  77501. /**
  77502. * If image processing is enabled.
  77503. */
  77504. set: function (enabled) {
  77505. if (this._imageProcessingEnabled === enabled) {
  77506. return;
  77507. }
  77508. this._imageProcessingEnabled = enabled;
  77509. this._buildPipeline();
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77515. get: function () {
  77516. return this._glowLayer == null;
  77517. },
  77518. /**
  77519. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77520. */
  77521. set: function (enabled) {
  77522. if (enabled && !this._glowLayer) {
  77523. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77524. }
  77525. else if (!enabled && this._glowLayer) {
  77526. this._glowLayer.dispose();
  77527. this._glowLayer = null;
  77528. }
  77529. },
  77530. enumerable: true,
  77531. configurable: true
  77532. });
  77533. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77534. get: function () {
  77535. return this._chromaticAberrationEnabled;
  77536. },
  77537. /**
  77538. * Enable or disable the chromaticAberration process from the pipeline
  77539. */
  77540. set: function (enabled) {
  77541. if (this._chromaticAberrationEnabled === enabled) {
  77542. return;
  77543. }
  77544. this._chromaticAberrationEnabled = enabled;
  77545. this._buildPipeline();
  77546. },
  77547. enumerable: true,
  77548. configurable: true
  77549. });
  77550. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77551. get: function () {
  77552. return this._grainEnabled;
  77553. },
  77554. /**
  77555. * Enable or disable the grain process from the pipeline
  77556. */
  77557. set: function (enabled) {
  77558. if (this._grainEnabled === enabled) {
  77559. return;
  77560. }
  77561. this._grainEnabled = enabled;
  77562. this._buildPipeline();
  77563. },
  77564. enumerable: true,
  77565. configurable: true
  77566. });
  77567. /**
  77568. * Force the compilation of the entire pipeline.
  77569. */
  77570. DefaultRenderingPipeline.prototype.prepare = function () {
  77571. var previousState = this._buildAllowed;
  77572. this._buildAllowed = true;
  77573. this._buildPipeline();
  77574. this._buildAllowed = previousState;
  77575. };
  77576. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77577. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77578. if (this._hasCleared) {
  77579. postProcess.autoClear = false;
  77580. }
  77581. else {
  77582. postProcess.autoClear = true;
  77583. this._scene.autoClear = false;
  77584. this._hasCleared = true;
  77585. }
  77586. if (!skipTextureSharing) {
  77587. if (this._prevPrevPostProcess) {
  77588. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77589. }
  77590. else {
  77591. postProcess.useOwnOutput();
  77592. }
  77593. if (this._prevPostProcess) {
  77594. this._prevPrevPostProcess = this._prevPostProcess;
  77595. }
  77596. this._prevPostProcess = postProcess;
  77597. }
  77598. };
  77599. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77600. var _this = this;
  77601. if (!this._buildAllowed) {
  77602. return;
  77603. }
  77604. this._scene.autoClear = true;
  77605. var engine = this._scene.getEngine();
  77606. this._disposePostProcesses();
  77607. if (this._cameras !== null) {
  77608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77609. // get back cameras to be used to reattach pipeline
  77610. this._cameras = this._camerasToBeAttached.slice();
  77611. }
  77612. this._reset();
  77613. this._prevPostProcess = null;
  77614. this._prevPrevPostProcess = null;
  77615. this._hasCleared = false;
  77616. if (this.depthOfFieldEnabled) {
  77617. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  77618. this.depthOfField.depthTexture = depthTexture;
  77619. if (!this.depthOfField._isReady()) {
  77620. this.depthOfField._updateEffects();
  77621. }
  77622. this.addEffect(this.depthOfField);
  77623. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  77624. }
  77625. if (this.bloomEnabled) {
  77626. if (!this.bloom._isReady()) {
  77627. this.bloom._updateEffects();
  77628. }
  77629. this.addEffect(this.bloom);
  77630. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  77631. }
  77632. if (this._imageProcessingEnabled) {
  77633. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77634. if (this._hdr) {
  77635. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  77636. this._setAutoClearAndTextureSharing(this.imageProcessing);
  77637. }
  77638. else {
  77639. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  77640. }
  77641. }
  77642. if (this.sharpenEnabled) {
  77643. if (!this.sharpen.isReady()) {
  77644. this.sharpen.updateEffect();
  77645. }
  77646. this.addEffect(this._sharpenEffect);
  77647. this._setAutoClearAndTextureSharing(this.sharpen);
  77648. }
  77649. if (this.grainEnabled) {
  77650. if (!this.grain.isReady()) {
  77651. this.grain.updateEffect();
  77652. }
  77653. this.addEffect(this._grainEffect);
  77654. this._setAutoClearAndTextureSharing(this.grain);
  77655. }
  77656. if (this.chromaticAberrationEnabled) {
  77657. if (!this.chromaticAberration.isReady()) {
  77658. this.chromaticAberration.updateEffect();
  77659. }
  77660. this.addEffect(this._chromaticAberrationEffect);
  77661. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  77662. }
  77663. if (this.fxaaEnabled) {
  77664. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  77666. this._setAutoClearAndTextureSharing(this.fxaa, true);
  77667. }
  77668. if (this._cameras !== null) {
  77669. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  77670. }
  77671. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  77672. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  77673. }
  77674. };
  77675. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  77676. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  77677. for (var i = 0; i < this._cameras.length; i++) {
  77678. var camera = this._cameras[i];
  77679. if (this.imageProcessing) {
  77680. this.imageProcessing.dispose(camera);
  77681. }
  77682. if (this.fxaa) {
  77683. this.fxaa.dispose(camera);
  77684. }
  77685. // These are created in the constructor and should not be disposed on every pipeline change
  77686. if (disposeNonRecreated) {
  77687. if (this.sharpen) {
  77688. this.sharpen.dispose(camera);
  77689. }
  77690. if (this.depthOfField) {
  77691. this.depthOfField.disposeEffects(camera);
  77692. }
  77693. if (this.bloom) {
  77694. this.bloom.disposeEffects(camera);
  77695. }
  77696. if (this.chromaticAberration) {
  77697. this.chromaticAberration.dispose(camera);
  77698. }
  77699. if (this.grain) {
  77700. this.grain.dispose(camera);
  77701. }
  77702. if (this._glowLayer) {
  77703. this._glowLayer.dispose();
  77704. }
  77705. }
  77706. }
  77707. this.imageProcessing = null;
  77708. this.fxaa = null;
  77709. if (disposeNonRecreated) {
  77710. this.sharpen = null;
  77711. this._sharpenEffect = null;
  77712. this.depthOfField = null;
  77713. this.bloom = null;
  77714. this.chromaticAberration = null;
  77715. this._chromaticAberrationEffect = null;
  77716. this.grain = null;
  77717. this._grainEffect = null;
  77718. this._glowLayer = null;
  77719. }
  77720. };
  77721. /**
  77722. * Adds a camera to the pipeline
  77723. * @param camera the camera to be added
  77724. */
  77725. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77726. this._camerasToBeAttached.push(camera);
  77727. this._buildPipeline();
  77728. };
  77729. /**
  77730. * Removes a camera from the pipeline
  77731. * @param camera the camera to remove
  77732. */
  77733. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77734. var index = this._camerasToBeAttached.indexOf(camera);
  77735. this._camerasToBeAttached.splice(index, 1);
  77736. this._buildPipeline();
  77737. };
  77738. /**
  77739. * Dispose of the pipeline and stop all post processes
  77740. */
  77741. DefaultRenderingPipeline.prototype.dispose = function () {
  77742. this._disposePostProcesses(true);
  77743. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77744. this._scene.autoClear = true;
  77745. if (this._resizeObserver) {
  77746. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77747. this._resizeObserver = null;
  77748. }
  77749. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77750. _super.prototype.dispose.call(this);
  77751. };
  77752. /**
  77753. * Serialize the rendering pipeline (Used when exporting)
  77754. * @returns the serialized object
  77755. */
  77756. DefaultRenderingPipeline.prototype.serialize = function () {
  77757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77758. serializationObject.customType = "DefaultRenderingPipeline";
  77759. return serializationObject;
  77760. };
  77761. /**
  77762. * Parse the serialized pipeline
  77763. * @param source Source pipeline.
  77764. * @param scene The scene to load the pipeline to.
  77765. * @param rootUrl The URL of the serialized pipeline.
  77766. * @returns An instantiated pipeline from the serialized object.
  77767. */
  77768. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77769. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77770. };
  77771. __decorate([
  77772. BABYLON.serialize()
  77773. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77774. __decorate([
  77775. BABYLON.serialize()
  77776. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77777. __decorate([
  77778. BABYLON.serialize()
  77779. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77780. __decorate([
  77781. BABYLON.serialize()
  77782. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77783. __decorate([
  77784. BABYLON.serialize()
  77785. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77786. __decorate([
  77787. BABYLON.serialize()
  77788. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77789. __decorate([
  77790. BABYLON.serialize()
  77791. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77792. __decorate([
  77793. BABYLON.serialize()
  77794. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77795. __decorate([
  77796. BABYLON.serialize()
  77797. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77798. __decorate([
  77799. BABYLON.serialize()
  77800. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77801. __decorate([
  77802. BABYLON.serialize()
  77803. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77804. __decorate([
  77805. BABYLON.serialize()
  77806. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77807. __decorate([
  77808. BABYLON.serialize()
  77809. ], DefaultRenderingPipeline.prototype, "samples", null);
  77810. __decorate([
  77811. BABYLON.serialize()
  77812. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77813. __decorate([
  77814. BABYLON.serialize()
  77815. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77816. __decorate([
  77817. BABYLON.serialize()
  77818. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77819. __decorate([
  77820. BABYLON.serialize()
  77821. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77822. return DefaultRenderingPipeline;
  77823. }(BABYLON.PostProcessRenderPipeline));
  77824. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77825. })(BABYLON || (BABYLON = {}));
  77826. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77827. var BABYLON;
  77828. (function (BABYLON) {
  77829. /**
  77830. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77831. */
  77832. var GeometryBufferRenderer = /** @class */ (function () {
  77833. /**
  77834. * Creates a new G Buffer for the scene
  77835. * @param scene The scene the buffer belongs to
  77836. * @param ratio How big is the buffer related to the main canvas.
  77837. */
  77838. function GeometryBufferRenderer(scene, ratio) {
  77839. if (ratio === void 0) { ratio = 1; }
  77840. this._enablePosition = false;
  77841. this._scene = scene;
  77842. this._ratio = ratio;
  77843. // Render target
  77844. this._createRenderTargets();
  77845. }
  77846. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77847. /**
  77848. * Set the render list (meshes to be rendered) used in the G buffer.
  77849. */
  77850. set: function (meshes) {
  77851. this._multiRenderTarget.renderList = meshes;
  77852. },
  77853. enumerable: true,
  77854. configurable: true
  77855. });
  77856. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77857. /**
  77858. * Gets wether or not G buffer are supported by the running hardware.
  77859. * This requires draw buffer supports
  77860. */
  77861. get: function () {
  77862. return this._multiRenderTarget.isSupported;
  77863. },
  77864. enumerable: true,
  77865. configurable: true
  77866. });
  77867. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77868. /**
  77869. * Gets wether or not position are enabled for the G buffer.
  77870. */
  77871. get: function () {
  77872. return this._enablePosition;
  77873. },
  77874. /**
  77875. * Sets wether or not position are enabled for the G buffer.
  77876. */
  77877. set: function (enable) {
  77878. this._enablePosition = enable;
  77879. this.dispose();
  77880. this._createRenderTargets();
  77881. },
  77882. enumerable: true,
  77883. configurable: true
  77884. });
  77885. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77886. /**
  77887. * Gets the scene associated with the buffer.
  77888. */
  77889. get: function () {
  77890. return this._scene;
  77891. },
  77892. enumerable: true,
  77893. configurable: true
  77894. });
  77895. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77896. /**
  77897. * Gets the ratio used by the buffer during its creation.
  77898. * How big is the buffer related to the main canvas.
  77899. */
  77900. get: function () {
  77901. return this._ratio;
  77902. },
  77903. enumerable: true,
  77904. configurable: true
  77905. });
  77906. /**
  77907. * Checks wether everything is ready to render a submesh to the G buffer.
  77908. * @param subMesh the submesh to check readiness for
  77909. * @param useInstances is the mesh drawn using instance or not
  77910. * @returns true if ready otherwise false
  77911. */
  77912. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77913. var material = subMesh.getMaterial();
  77914. if (material && material.disableDepthWrite) {
  77915. return false;
  77916. }
  77917. var defines = [];
  77918. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77919. var mesh = subMesh.getMesh();
  77920. // Alpha test
  77921. if (material && material.needAlphaTesting()) {
  77922. defines.push("#define ALPHATEST");
  77923. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77924. attribs.push(BABYLON.VertexBuffer.UVKind);
  77925. defines.push("#define UV1");
  77926. }
  77927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77928. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77929. defines.push("#define UV2");
  77930. }
  77931. }
  77932. // Buffers
  77933. if (this._enablePosition) {
  77934. defines.push("#define POSITION");
  77935. }
  77936. // Bones
  77937. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77940. if (mesh.numBoneInfluencers > 4) {
  77941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77943. }
  77944. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77945. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77946. }
  77947. else {
  77948. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77949. }
  77950. // Instances
  77951. if (useInstances) {
  77952. defines.push("#define INSTANCES");
  77953. attribs.push("world0");
  77954. attribs.push("world1");
  77955. attribs.push("world2");
  77956. attribs.push("world3");
  77957. }
  77958. // Get correct effect
  77959. var join = defines.join("\n");
  77960. if (this._cachedDefines !== join) {
  77961. this._cachedDefines = join;
  77962. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77963. }
  77964. return this._effect.isReady();
  77965. };
  77966. /**
  77967. * Gets the current underlying G Buffer.
  77968. * @returns the buffer
  77969. */
  77970. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77971. return this._multiRenderTarget;
  77972. };
  77973. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77974. /**
  77975. * Gets the number of samples used to render the buffer (anti aliasing).
  77976. */
  77977. get: function () {
  77978. return this._multiRenderTarget.samples;
  77979. },
  77980. /**
  77981. * Sets the number of samples used to render the buffer (anti aliasing).
  77982. */
  77983. set: function (value) {
  77984. this._multiRenderTarget.samples = value;
  77985. },
  77986. enumerable: true,
  77987. configurable: true
  77988. });
  77989. /**
  77990. * Disposes the renderer and frees up associated resources.
  77991. */
  77992. GeometryBufferRenderer.prototype.dispose = function () {
  77993. this.getGBuffer().dispose();
  77994. };
  77995. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77996. var _this = this;
  77997. var engine = this._scene.getEngine();
  77998. var count = this._enablePosition ? 3 : 2;
  77999. 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 });
  78000. if (!this.isSupported) {
  78001. return;
  78002. }
  78003. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78004. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78005. this._multiRenderTarget.refreshRate = 1;
  78006. this._multiRenderTarget.renderParticles = false;
  78007. this._multiRenderTarget.renderList = null;
  78008. // set default depth value to 1.0 (far away)
  78009. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78010. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78011. });
  78012. // Custom render function
  78013. var renderSubMesh = function (subMesh) {
  78014. var mesh = subMesh.getRenderingMesh();
  78015. var scene = _this._scene;
  78016. var engine = scene.getEngine();
  78017. var material = subMesh.getMaterial();
  78018. if (!material) {
  78019. return;
  78020. }
  78021. // Culling
  78022. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78023. // Managing instances
  78024. var batch = mesh._getInstancesRenderList(subMesh._id);
  78025. if (batch.mustReturn) {
  78026. return;
  78027. }
  78028. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78029. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78030. engine.enableEffect(_this._effect);
  78031. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78032. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78033. _this._effect.setMatrix("view", scene.getViewMatrix());
  78034. // Alpha test
  78035. if (material && material.needAlphaTesting()) {
  78036. var alphaTexture = material.getAlphaTestTexture();
  78037. if (alphaTexture) {
  78038. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78039. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78040. }
  78041. }
  78042. // Bones
  78043. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78044. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78045. }
  78046. // Draw
  78047. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78048. }
  78049. };
  78050. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78051. var index;
  78052. if (depthOnlySubMeshes.length) {
  78053. engine.setColorWrite(false);
  78054. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78055. renderSubMesh(depthOnlySubMeshes.data[index]);
  78056. }
  78057. engine.setColorWrite(true);
  78058. }
  78059. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78060. renderSubMesh(opaqueSubMeshes.data[index]);
  78061. }
  78062. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78063. renderSubMesh(alphaTestSubMeshes.data[index]);
  78064. }
  78065. };
  78066. };
  78067. return GeometryBufferRenderer;
  78068. }());
  78069. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78070. })(BABYLON || (BABYLON = {}));
  78071. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78072. var BABYLON;
  78073. (function (BABYLON) {
  78074. /**
  78075. * This groups together the common properties used for image processing either in direct forward pass
  78076. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78077. * or not.
  78078. */
  78079. var ImageProcessingConfiguration = /** @class */ (function () {
  78080. function ImageProcessingConfiguration() {
  78081. /**
  78082. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78083. */
  78084. this.colorCurves = new BABYLON.ColorCurves();
  78085. this._colorCurvesEnabled = false;
  78086. this._colorGradingEnabled = false;
  78087. this._colorGradingWithGreenDepth = true;
  78088. this._colorGradingBGR = true;
  78089. this._exposure = 1.0;
  78090. this._toneMappingEnabled = false;
  78091. this._contrast = 1.0;
  78092. /**
  78093. * Vignette stretch size.
  78094. */
  78095. this.vignetteStretch = 0;
  78096. /**
  78097. * Vignette centre X Offset.
  78098. */
  78099. this.vignetteCentreX = 0;
  78100. /**
  78101. * Vignette centre Y Offset.
  78102. */
  78103. this.vignetteCentreY = 0;
  78104. /**
  78105. * Vignette weight or intensity of the vignette effect.
  78106. */
  78107. this.vignetteWeight = 1.5;
  78108. /**
  78109. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78110. * if vignetteEnabled is set to true.
  78111. */
  78112. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78113. /**
  78114. * Camera field of view used by the Vignette effect.
  78115. */
  78116. this.vignetteCameraFov = 0.5;
  78117. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78118. this._vignetteEnabled = false;
  78119. this._applyByPostProcess = false;
  78120. this._isEnabled = true;
  78121. /**
  78122. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78123. */
  78124. this.onUpdateParameters = new BABYLON.Observable();
  78125. }
  78126. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78127. /**
  78128. * Gets wether the color curves effect is enabled.
  78129. */
  78130. get: function () {
  78131. return this._colorCurvesEnabled;
  78132. },
  78133. /**
  78134. * Sets wether the color curves effect is enabled.
  78135. */
  78136. set: function (value) {
  78137. if (this._colorCurvesEnabled === value) {
  78138. return;
  78139. }
  78140. this._colorCurvesEnabled = value;
  78141. this._updateParameters();
  78142. },
  78143. enumerable: true,
  78144. configurable: true
  78145. });
  78146. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78147. /**
  78148. * Gets wether the color grading effect is enabled.
  78149. */
  78150. get: function () {
  78151. return this._colorGradingEnabled;
  78152. },
  78153. /**
  78154. * Sets wether the color grading effect is enabled.
  78155. */
  78156. set: function (value) {
  78157. if (this._colorGradingEnabled === value) {
  78158. return;
  78159. }
  78160. this._colorGradingEnabled = value;
  78161. this._updateParameters();
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78167. /**
  78168. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78169. */
  78170. get: function () {
  78171. return this._colorGradingWithGreenDepth;
  78172. },
  78173. /**
  78174. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78175. */
  78176. set: function (value) {
  78177. if (this._colorGradingWithGreenDepth === value) {
  78178. return;
  78179. }
  78180. this._colorGradingWithGreenDepth = value;
  78181. this._updateParameters();
  78182. },
  78183. enumerable: true,
  78184. configurable: true
  78185. });
  78186. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78187. /**
  78188. * Gets wether the color grading texture contains BGR values.
  78189. */
  78190. get: function () {
  78191. return this._colorGradingBGR;
  78192. },
  78193. /**
  78194. * Sets wether the color grading texture contains BGR values.
  78195. */
  78196. set: function (value) {
  78197. if (this._colorGradingBGR === value) {
  78198. return;
  78199. }
  78200. this._colorGradingBGR = value;
  78201. this._updateParameters();
  78202. },
  78203. enumerable: true,
  78204. configurable: true
  78205. });
  78206. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78207. /**
  78208. * Gets the Exposure used in the effect.
  78209. */
  78210. get: function () {
  78211. return this._exposure;
  78212. },
  78213. /**
  78214. * Sets the Exposure used in the effect.
  78215. */
  78216. set: function (value) {
  78217. if (this._exposure === value) {
  78218. return;
  78219. }
  78220. this._exposure = value;
  78221. this._updateParameters();
  78222. },
  78223. enumerable: true,
  78224. configurable: true
  78225. });
  78226. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78227. /**
  78228. * Gets wether the tone mapping effect is enabled.
  78229. */
  78230. get: function () {
  78231. return this._toneMappingEnabled;
  78232. },
  78233. /**
  78234. * Sets wether the tone mapping effect is enabled.
  78235. */
  78236. set: function (value) {
  78237. if (this._toneMappingEnabled === value) {
  78238. return;
  78239. }
  78240. this._toneMappingEnabled = value;
  78241. this._updateParameters();
  78242. },
  78243. enumerable: true,
  78244. configurable: true
  78245. });
  78246. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78247. /**
  78248. * Gets the contrast used in the effect.
  78249. */
  78250. get: function () {
  78251. return this._contrast;
  78252. },
  78253. /**
  78254. * Sets the contrast used in the effect.
  78255. */
  78256. set: function (value) {
  78257. if (this._contrast === value) {
  78258. return;
  78259. }
  78260. this._contrast = value;
  78261. this._updateParameters();
  78262. },
  78263. enumerable: true,
  78264. configurable: true
  78265. });
  78266. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78267. /**
  78268. * Gets the vignette blend mode allowing different kind of effect.
  78269. */
  78270. get: function () {
  78271. return this._vignetteBlendMode;
  78272. },
  78273. /**
  78274. * Sets the vignette blend mode allowing different kind of effect.
  78275. */
  78276. set: function (value) {
  78277. if (this._vignetteBlendMode === value) {
  78278. return;
  78279. }
  78280. this._vignetteBlendMode = value;
  78281. this._updateParameters();
  78282. },
  78283. enumerable: true,
  78284. configurable: true
  78285. });
  78286. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78287. /**
  78288. * Gets wether the vignette effect is enabled.
  78289. */
  78290. get: function () {
  78291. return this._vignetteEnabled;
  78292. },
  78293. /**
  78294. * Sets wether the vignette effect is enabled.
  78295. */
  78296. set: function (value) {
  78297. if (this._vignetteEnabled === value) {
  78298. return;
  78299. }
  78300. this._vignetteEnabled = value;
  78301. this._updateParameters();
  78302. },
  78303. enumerable: true,
  78304. configurable: true
  78305. });
  78306. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78307. /**
  78308. * Gets wether the image processing is applied through a post process or not.
  78309. */
  78310. get: function () {
  78311. return this._applyByPostProcess;
  78312. },
  78313. /**
  78314. * Sets wether the image processing is applied through a post process or not.
  78315. */
  78316. set: function (value) {
  78317. if (this._applyByPostProcess === value) {
  78318. return;
  78319. }
  78320. this._applyByPostProcess = value;
  78321. this._updateParameters();
  78322. },
  78323. enumerable: true,
  78324. configurable: true
  78325. });
  78326. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78327. /**
  78328. * Gets wether the image processing is enabled or not.
  78329. */
  78330. get: function () {
  78331. return this._isEnabled;
  78332. },
  78333. /**
  78334. * Sets wether the image processing is enabled or not.
  78335. */
  78336. set: function (value) {
  78337. if (this._isEnabled === value) {
  78338. return;
  78339. }
  78340. this._isEnabled = value;
  78341. this._updateParameters();
  78342. },
  78343. enumerable: true,
  78344. configurable: true
  78345. });
  78346. /**
  78347. * Method called each time the image processing information changes requires to recompile the effect.
  78348. */
  78349. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78350. this.onUpdateParameters.notifyObservers(this);
  78351. };
  78352. ImageProcessingConfiguration.prototype.getClassName = function () {
  78353. return "ImageProcessingConfiguration";
  78354. };
  78355. /**
  78356. * Prepare the list of uniforms associated with the Image Processing effects.
  78357. * @param uniformsList The list of uniforms used in the effect
  78358. * @param defines the list of defines currently in use
  78359. */
  78360. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78361. if (defines.EXPOSURE) {
  78362. uniforms.push("exposureLinear");
  78363. }
  78364. if (defines.CONTRAST) {
  78365. uniforms.push("contrast");
  78366. }
  78367. if (defines.COLORGRADING) {
  78368. uniforms.push("colorTransformSettings");
  78369. }
  78370. if (defines.VIGNETTE) {
  78371. uniforms.push("vInverseScreenSize");
  78372. uniforms.push("vignetteSettings1");
  78373. uniforms.push("vignetteSettings2");
  78374. }
  78375. if (defines.COLORCURVES) {
  78376. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78377. }
  78378. };
  78379. /**
  78380. * Prepare the list of samplers associated with the Image Processing effects.
  78381. * @param uniformsList The list of uniforms used in the effect
  78382. * @param defines the list of defines currently in use
  78383. */
  78384. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78385. if (defines.COLORGRADING) {
  78386. samplersList.push("txColorTransform");
  78387. }
  78388. };
  78389. /**
  78390. * Prepare the list of defines associated to the shader.
  78391. * @param defines the list of defines to complete
  78392. */
  78393. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78394. if (forPostProcess === void 0) { forPostProcess = false; }
  78395. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78396. defines.VIGNETTE = false;
  78397. defines.TONEMAPPING = false;
  78398. defines.CONTRAST = false;
  78399. defines.EXPOSURE = false;
  78400. defines.COLORCURVES = false;
  78401. defines.COLORGRADING = false;
  78402. defines.COLORGRADING3D = false;
  78403. defines.IMAGEPROCESSING = false;
  78404. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78405. return;
  78406. }
  78407. defines.VIGNETTE = this.vignetteEnabled;
  78408. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78409. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78410. defines.TONEMAPPING = this.toneMappingEnabled;
  78411. defines.CONTRAST = (this.contrast !== 1.0);
  78412. defines.EXPOSURE = (this.exposure !== 1.0);
  78413. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78414. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78415. if (defines.COLORGRADING) {
  78416. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78417. }
  78418. else {
  78419. defines.COLORGRADING3D = false;
  78420. }
  78421. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78422. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78423. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78424. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78425. };
  78426. /**
  78427. * Returns true if all the image processing information are ready.
  78428. */
  78429. ImageProcessingConfiguration.prototype.isReady = function () {
  78430. // Color Grading texure can not be none blocking.
  78431. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78432. };
  78433. /**
  78434. * Binds the image processing to the shader.
  78435. * @param effect The effect to bind to
  78436. */
  78437. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78438. if (aspectRatio === void 0) { aspectRatio = 1; }
  78439. // Color Curves
  78440. if (this._colorCurvesEnabled && this.colorCurves) {
  78441. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78442. }
  78443. // Vignette
  78444. if (this._vignetteEnabled) {
  78445. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78446. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78447. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78448. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78449. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78450. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78451. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78452. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78453. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78454. var vignettePower = -2.0 * this.vignetteWeight;
  78455. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78456. }
  78457. // Exposure
  78458. effect.setFloat("exposureLinear", this.exposure);
  78459. // Contrast
  78460. effect.setFloat("contrast", this.contrast);
  78461. // Color transform settings
  78462. if (this.colorGradingTexture) {
  78463. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78464. var textureSize = this.colorGradingTexture.getSize().height;
  78465. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78466. 0.5 / textureSize, // textureOffset
  78467. textureSize, // textureSize
  78468. this.colorGradingTexture.level // weight
  78469. );
  78470. }
  78471. };
  78472. /**
  78473. * Clones the current image processing instance.
  78474. * @return The cloned image processing
  78475. */
  78476. ImageProcessingConfiguration.prototype.clone = function () {
  78477. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78478. };
  78479. /**
  78480. * Serializes the current image processing instance to a json representation.
  78481. * @return a JSON representation
  78482. */
  78483. ImageProcessingConfiguration.prototype.serialize = function () {
  78484. return BABYLON.SerializationHelper.Serialize(this);
  78485. };
  78486. /**
  78487. * Parses the image processing from a json representation.
  78488. * @param source the JSON source to parse
  78489. * @return The parsed image processing
  78490. */
  78491. ImageProcessingConfiguration.Parse = function (source) {
  78492. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78493. };
  78494. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78495. /**
  78496. * Used to apply the vignette as a mix with the pixel color.
  78497. */
  78498. get: function () {
  78499. return this._VIGNETTEMODE_MULTIPLY;
  78500. },
  78501. enumerable: true,
  78502. configurable: true
  78503. });
  78504. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78505. /**
  78506. * Used to apply the vignette as a replacement of the pixel color.
  78507. */
  78508. get: function () {
  78509. return this._VIGNETTEMODE_OPAQUE;
  78510. },
  78511. enumerable: true,
  78512. configurable: true
  78513. });
  78514. // Static constants associated to the image processing.
  78515. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78516. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78517. __decorate([
  78518. BABYLON.serializeAsColorCurves()
  78519. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78520. __decorate([
  78521. BABYLON.serialize()
  78522. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78523. __decorate([
  78524. BABYLON.serializeAsTexture()
  78525. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78526. __decorate([
  78527. BABYLON.serialize()
  78528. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78529. __decorate([
  78530. BABYLON.serialize()
  78531. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78532. __decorate([
  78533. BABYLON.serialize()
  78534. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78535. __decorate([
  78536. BABYLON.serialize()
  78537. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78538. __decorate([
  78539. BABYLON.serialize()
  78540. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78541. __decorate([
  78542. BABYLON.serialize()
  78543. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78544. __decorate([
  78545. BABYLON.serialize()
  78546. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78547. __decorate([
  78548. BABYLON.serialize()
  78549. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78550. __decorate([
  78551. BABYLON.serialize()
  78552. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78553. __decorate([
  78554. BABYLON.serialize()
  78555. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78556. __decorate([
  78557. BABYLON.serializeAsColor4()
  78558. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78559. __decorate([
  78560. BABYLON.serialize()
  78561. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78562. __decorate([
  78563. BABYLON.serialize()
  78564. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78565. __decorate([
  78566. BABYLON.serialize()
  78567. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78568. __decorate([
  78569. BABYLON.serialize()
  78570. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78571. __decorate([
  78572. BABYLON.serialize()
  78573. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78574. return ImageProcessingConfiguration;
  78575. }());
  78576. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78577. })(BABYLON || (BABYLON = {}));
  78578. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78579. var BABYLON;
  78580. (function (BABYLON) {
  78581. /**
  78582. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78583. * It can help converting any input color in a desired output one. This can then be used to create effects
  78584. * from sepia, black and white to sixties or futuristic rendering...
  78585. *
  78586. * The only supported format is currently 3dl.
  78587. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78588. */
  78589. var ColorGradingTexture = /** @class */ (function (_super) {
  78590. __extends(ColorGradingTexture, _super);
  78591. /**
  78592. * Instantiates a ColorGradingTexture from the following parameters.
  78593. *
  78594. * @param url The location of the color gradind data (currently only supporting 3dl)
  78595. * @param scene The scene the texture will be used in
  78596. */
  78597. function ColorGradingTexture(url, scene) {
  78598. var _this = _super.call(this, scene) || this;
  78599. if (!url) {
  78600. return _this;
  78601. }
  78602. _this._engine = scene.getEngine();
  78603. _this._textureMatrix = BABYLON.Matrix.Identity();
  78604. _this.name = url;
  78605. _this.url = url;
  78606. _this.hasAlpha = false;
  78607. _this.isCube = false;
  78608. _this.is3D = _this._engine.webGLVersion > 1;
  78609. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78610. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78611. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78612. _this.anisotropicFilteringLevel = 1;
  78613. _this._texture = _this._getFromCache(url, true);
  78614. if (!_this._texture) {
  78615. if (!scene.useDelayedTextureLoading) {
  78616. _this.loadTexture();
  78617. }
  78618. else {
  78619. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78620. }
  78621. }
  78622. return _this;
  78623. }
  78624. /**
  78625. * Returns the texture matrix used in most of the material.
  78626. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  78627. */
  78628. ColorGradingTexture.prototype.getTextureMatrix = function () {
  78629. return this._textureMatrix;
  78630. };
  78631. /**
  78632. * Occurs when the file being loaded is a .3dl LUT file.
  78633. */
  78634. ColorGradingTexture.prototype.load3dlTexture = function () {
  78635. var engine = this._engine;
  78636. var texture;
  78637. if (engine.webGLVersion === 1) {
  78638. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78639. }
  78640. else {
  78641. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78642. }
  78643. this._texture = texture;
  78644. var callback = function (text) {
  78645. if (typeof text !== "string") {
  78646. return;
  78647. }
  78648. var data = null;
  78649. var tempData = null;
  78650. var line;
  78651. var lines = text.split('\n');
  78652. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  78653. var maxColor = 0;
  78654. for (var i = 0; i < lines.length; i++) {
  78655. line = lines[i];
  78656. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  78657. continue;
  78658. if (line.indexOf('#') === 0)
  78659. continue;
  78660. var words = line.split(" ");
  78661. if (size === 0) {
  78662. // Number of space + one
  78663. size = words.length;
  78664. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  78665. tempData = new Float32Array(size * size * size * 4);
  78666. continue;
  78667. }
  78668. if (size != 0) {
  78669. var r = Math.max(parseInt(words[0]), 0);
  78670. var g = Math.max(parseInt(words[1]), 0);
  78671. var b = Math.max(parseInt(words[2]), 0);
  78672. maxColor = Math.max(r, maxColor);
  78673. maxColor = Math.max(g, maxColor);
  78674. maxColor = Math.max(b, maxColor);
  78675. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  78676. if (tempData) {
  78677. tempData[pixelStorageIndex + 0] = r;
  78678. tempData[pixelStorageIndex + 1] = g;
  78679. tempData[pixelStorageIndex + 2] = b;
  78680. }
  78681. pixelIndexSlice++;
  78682. if (pixelIndexSlice % size == 0) {
  78683. pixelIndexH++;
  78684. pixelIndexSlice = 0;
  78685. if (pixelIndexH % size == 0) {
  78686. pixelIndexW++;
  78687. pixelIndexH = 0;
  78688. }
  78689. }
  78690. }
  78691. }
  78692. if (tempData && data) {
  78693. for (var i = 0; i < tempData.length; i++) {
  78694. if (i > 0 && (i + 1) % 4 === 0) {
  78695. data[i] = 255;
  78696. }
  78697. else {
  78698. var value = tempData[i];
  78699. data[i] = (value / maxColor * 255);
  78700. }
  78701. }
  78702. }
  78703. if (texture.is3D) {
  78704. texture.updateSize(size, size, size);
  78705. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78706. }
  78707. else {
  78708. texture.updateSize(size * size, size);
  78709. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78710. }
  78711. };
  78712. var scene = this.getScene();
  78713. if (scene) {
  78714. scene._loadFile(this.url, callback);
  78715. }
  78716. else {
  78717. this._engine._loadFile(this.url, callback);
  78718. }
  78719. return this._texture;
  78720. };
  78721. /**
  78722. * Starts the loading process of the texture.
  78723. */
  78724. ColorGradingTexture.prototype.loadTexture = function () {
  78725. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78726. this.load3dlTexture();
  78727. }
  78728. };
  78729. /**
  78730. * Clones the color gradind texture.
  78731. */
  78732. ColorGradingTexture.prototype.clone = function () {
  78733. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78734. // Base texture
  78735. newTexture.level = this.level;
  78736. return newTexture;
  78737. };
  78738. /**
  78739. * Called during delayed load for textures.
  78740. */
  78741. ColorGradingTexture.prototype.delayLoad = function () {
  78742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78743. return;
  78744. }
  78745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78746. this._texture = this._getFromCache(this.url, true);
  78747. if (!this._texture) {
  78748. this.loadTexture();
  78749. }
  78750. };
  78751. /**
  78752. * Parses a color grading texture serialized by Babylon.
  78753. * @param parsedTexture The texture information being parsedTexture
  78754. * @param scene The scene to load the texture in
  78755. * @param rootUrl The root url of the data assets to load
  78756. * @return A color gradind texture
  78757. */
  78758. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78759. var texture = null;
  78760. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78761. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78762. texture.name = parsedTexture.name;
  78763. texture.level = parsedTexture.level;
  78764. }
  78765. return texture;
  78766. };
  78767. /**
  78768. * Serializes the LUT texture to json format.
  78769. */
  78770. ColorGradingTexture.prototype.serialize = function () {
  78771. if (!this.name) {
  78772. return null;
  78773. }
  78774. var serializationObject = {};
  78775. serializationObject.name = this.name;
  78776. serializationObject.level = this.level;
  78777. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78778. return serializationObject;
  78779. };
  78780. /**
  78781. * Empty line regex stored for GC.
  78782. */
  78783. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78784. return ColorGradingTexture;
  78785. }(BABYLON.BaseTexture));
  78786. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78787. })(BABYLON || (BABYLON = {}));
  78788. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78789. var BABYLON;
  78790. (function (BABYLON) {
  78791. /**
  78792. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78793. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78794. * 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;
  78795. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78796. */
  78797. var ColorCurves = /** @class */ (function () {
  78798. function ColorCurves() {
  78799. this._dirty = true;
  78800. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78801. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78802. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78803. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78804. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78805. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78806. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78807. this._globalHue = 30;
  78808. this._globalDensity = 0;
  78809. this._globalSaturation = 0;
  78810. this._globalExposure = 0;
  78811. this._highlightsHue = 30;
  78812. this._highlightsDensity = 0;
  78813. this._highlightsSaturation = 0;
  78814. this._highlightsExposure = 0;
  78815. this._midtonesHue = 30;
  78816. this._midtonesDensity = 0;
  78817. this._midtonesSaturation = 0;
  78818. this._midtonesExposure = 0;
  78819. this._shadowsHue = 30;
  78820. this._shadowsDensity = 0;
  78821. this._shadowsSaturation = 0;
  78822. this._shadowsExposure = 0;
  78823. }
  78824. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78825. /**
  78826. * Gets the global Hue value.
  78827. * 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).
  78828. */
  78829. get: function () {
  78830. return this._globalHue;
  78831. },
  78832. /**
  78833. * Sets the global Hue value.
  78834. * 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).
  78835. */
  78836. set: function (value) {
  78837. this._globalHue = value;
  78838. this._dirty = true;
  78839. },
  78840. enumerable: true,
  78841. configurable: true
  78842. });
  78843. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78844. /**
  78845. * Gets the global Density value.
  78846. * 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.
  78847. * Values less than zero provide a filter of opposite hue.
  78848. */
  78849. get: function () {
  78850. return this._globalDensity;
  78851. },
  78852. /**
  78853. * Sets the global Density value.
  78854. * 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.
  78855. * Values less than zero provide a filter of opposite hue.
  78856. */
  78857. set: function (value) {
  78858. this._globalDensity = value;
  78859. this._dirty = true;
  78860. },
  78861. enumerable: true,
  78862. configurable: true
  78863. });
  78864. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78865. /**
  78866. * Gets the global Saturation value.
  78867. * 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.
  78868. */
  78869. get: function () {
  78870. return this._globalSaturation;
  78871. },
  78872. /**
  78873. * Sets the global Saturation value.
  78874. * 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.
  78875. */
  78876. set: function (value) {
  78877. this._globalSaturation = value;
  78878. this._dirty = true;
  78879. },
  78880. enumerable: true,
  78881. configurable: true
  78882. });
  78883. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78884. /**
  78885. * Gets the global Exposure value.
  78886. * 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.
  78887. */
  78888. get: function () {
  78889. return this._globalExposure;
  78890. },
  78891. /**
  78892. * Sets the global Exposure value.
  78893. * 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.
  78894. */
  78895. set: function (value) {
  78896. this._globalExposure = value;
  78897. this._dirty = true;
  78898. },
  78899. enumerable: true,
  78900. configurable: true
  78901. });
  78902. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78903. /**
  78904. * Gets the highlights Hue value.
  78905. * 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).
  78906. */
  78907. get: function () {
  78908. return this._highlightsHue;
  78909. },
  78910. /**
  78911. * Sets the highlights Hue value.
  78912. * 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).
  78913. */
  78914. set: function (value) {
  78915. this._highlightsHue = value;
  78916. this._dirty = true;
  78917. },
  78918. enumerable: true,
  78919. configurable: true
  78920. });
  78921. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78922. /**
  78923. * Gets the highlights Density value.
  78924. * 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.
  78925. * Values less than zero provide a filter of opposite hue.
  78926. */
  78927. get: function () {
  78928. return this._highlightsDensity;
  78929. },
  78930. /**
  78931. * Sets the highlights Density value.
  78932. * 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.
  78933. * Values less than zero provide a filter of opposite hue.
  78934. */
  78935. set: function (value) {
  78936. this._highlightsDensity = value;
  78937. this._dirty = true;
  78938. },
  78939. enumerable: true,
  78940. configurable: true
  78941. });
  78942. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78943. /**
  78944. * Gets the highlights Saturation value.
  78945. * 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.
  78946. */
  78947. get: function () {
  78948. return this._highlightsSaturation;
  78949. },
  78950. /**
  78951. * Sets the highlights Saturation value.
  78952. * 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.
  78953. */
  78954. set: function (value) {
  78955. this._highlightsSaturation = value;
  78956. this._dirty = true;
  78957. },
  78958. enumerable: true,
  78959. configurable: true
  78960. });
  78961. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78962. /**
  78963. * Gets the highlights Exposure value.
  78964. * 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.
  78965. */
  78966. get: function () {
  78967. return this._highlightsExposure;
  78968. },
  78969. /**
  78970. * Sets the highlights Exposure value.
  78971. * 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.
  78972. */
  78973. set: function (value) {
  78974. this._highlightsExposure = value;
  78975. this._dirty = true;
  78976. },
  78977. enumerable: true,
  78978. configurable: true
  78979. });
  78980. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78981. /**
  78982. * Gets the midtones Hue value.
  78983. * 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).
  78984. */
  78985. get: function () {
  78986. return this._midtonesHue;
  78987. },
  78988. /**
  78989. * Sets the midtones Hue value.
  78990. * 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).
  78991. */
  78992. set: function (value) {
  78993. this._midtonesHue = value;
  78994. this._dirty = true;
  78995. },
  78996. enumerable: true,
  78997. configurable: true
  78998. });
  78999. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79000. /**
  79001. * Gets the midtones Density value.
  79002. * 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.
  79003. * Values less than zero provide a filter of opposite hue.
  79004. */
  79005. get: function () {
  79006. return this._midtonesDensity;
  79007. },
  79008. /**
  79009. * Sets the midtones Density value.
  79010. * 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.
  79011. * Values less than zero provide a filter of opposite hue.
  79012. */
  79013. set: function (value) {
  79014. this._midtonesDensity = value;
  79015. this._dirty = true;
  79016. },
  79017. enumerable: true,
  79018. configurable: true
  79019. });
  79020. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79021. /**
  79022. * Gets the midtones Saturation value.
  79023. * 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.
  79024. */
  79025. get: function () {
  79026. return this._midtonesSaturation;
  79027. },
  79028. /**
  79029. * Sets the midtones Saturation value.
  79030. * 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.
  79031. */
  79032. set: function (value) {
  79033. this._midtonesSaturation = value;
  79034. this._dirty = true;
  79035. },
  79036. enumerable: true,
  79037. configurable: true
  79038. });
  79039. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79040. /**
  79041. * Gets the midtones Exposure value.
  79042. * 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.
  79043. */
  79044. get: function () {
  79045. return this._midtonesExposure;
  79046. },
  79047. /**
  79048. * Sets the midtones Exposure value.
  79049. * 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.
  79050. */
  79051. set: function (value) {
  79052. this._midtonesExposure = value;
  79053. this._dirty = true;
  79054. },
  79055. enumerable: true,
  79056. configurable: true
  79057. });
  79058. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79059. /**
  79060. * Gets the shadows Hue value.
  79061. * 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).
  79062. */
  79063. get: function () {
  79064. return this._shadowsHue;
  79065. },
  79066. /**
  79067. * Sets the shadows Hue value.
  79068. * 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).
  79069. */
  79070. set: function (value) {
  79071. this._shadowsHue = value;
  79072. this._dirty = true;
  79073. },
  79074. enumerable: true,
  79075. configurable: true
  79076. });
  79077. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79078. /**
  79079. * Gets the shadows Density value.
  79080. * 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.
  79081. * Values less than zero provide a filter of opposite hue.
  79082. */
  79083. get: function () {
  79084. return this._shadowsDensity;
  79085. },
  79086. /**
  79087. * Sets the shadows Density value.
  79088. * 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.
  79089. * Values less than zero provide a filter of opposite hue.
  79090. */
  79091. set: function (value) {
  79092. this._shadowsDensity = value;
  79093. this._dirty = true;
  79094. },
  79095. enumerable: true,
  79096. configurable: true
  79097. });
  79098. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79099. /**
  79100. * Gets the shadows Saturation value.
  79101. * 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.
  79102. */
  79103. get: function () {
  79104. return this._shadowsSaturation;
  79105. },
  79106. /**
  79107. * Sets the shadows Saturation value.
  79108. * 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.
  79109. */
  79110. set: function (value) {
  79111. this._shadowsSaturation = value;
  79112. this._dirty = true;
  79113. },
  79114. enumerable: true,
  79115. configurable: true
  79116. });
  79117. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79118. /**
  79119. * Gets the shadows Exposure value.
  79120. * 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.
  79121. */
  79122. get: function () {
  79123. return this._shadowsExposure;
  79124. },
  79125. /**
  79126. * Sets the shadows Exposure value.
  79127. * 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.
  79128. */
  79129. set: function (value) {
  79130. this._shadowsExposure = value;
  79131. this._dirty = true;
  79132. },
  79133. enumerable: true,
  79134. configurable: true
  79135. });
  79136. ColorCurves.prototype.getClassName = function () {
  79137. return "ColorCurves";
  79138. };
  79139. /**
  79140. * Binds the color curves to the shader.
  79141. * @param colorCurves The color curve to bind
  79142. * @param effect The effect to bind to
  79143. */
  79144. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79145. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79146. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79147. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79148. if (colorCurves._dirty) {
  79149. colorCurves._dirty = false;
  79150. // Fill in global info.
  79151. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79152. // Compute highlights info.
  79153. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79154. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79155. // Compute midtones info.
  79156. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79157. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79158. // Compute shadows info.
  79159. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79160. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79161. // Compute deltas (neutral is midtones).
  79162. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79163. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79164. }
  79165. if (effect) {
  79166. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79167. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79168. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79169. }
  79170. };
  79171. /**
  79172. * Prepare the list of uniforms associated with the ColorCurves effects.
  79173. * @param uniformsList The list of uniforms used in the effect
  79174. */
  79175. ColorCurves.PrepareUniforms = function (uniformsList) {
  79176. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79177. };
  79178. /**
  79179. * Returns color grading data based on a hue, density, saturation and exposure value.
  79180. * @param filterHue The hue of the color filter.
  79181. * @param filterDensity The density of the color filter.
  79182. * @param saturation The saturation.
  79183. * @param exposure The exposure.
  79184. * @param result The result data container.
  79185. */
  79186. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79187. if (hue == null) {
  79188. return;
  79189. }
  79190. hue = ColorCurves.clamp(hue, 0, 360);
  79191. density = ColorCurves.clamp(density, -100, 100);
  79192. saturation = ColorCurves.clamp(saturation, -100, 100);
  79193. exposure = ColorCurves.clamp(exposure, -100, 100);
  79194. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79195. // so that the maximum filter density is only 50% control. This provides fine control
  79196. // for small values and reasonable range.
  79197. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79198. density *= 0.5;
  79199. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79200. if (density < 0) {
  79201. density *= -1;
  79202. hue = (hue + 180) % 360;
  79203. }
  79204. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79205. result.scaleToRef(2, result);
  79206. result.a = 1 + 0.01 * saturation;
  79207. };
  79208. /**
  79209. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79210. * @param value The input slider value in range [-100,100].
  79211. * @returns Adjusted value.
  79212. */
  79213. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79214. value /= 100;
  79215. var x = Math.abs(value);
  79216. x = Math.pow(x, 2);
  79217. if (value < 0) {
  79218. x *= -1;
  79219. }
  79220. x *= 100;
  79221. return x;
  79222. };
  79223. /**
  79224. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79225. * @param hue The hue (H) input.
  79226. * @param saturation The saturation (S) input.
  79227. * @param brightness The brightness (B) input.
  79228. * @result An RGBA color represented as Vector4.
  79229. */
  79230. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79231. var h = ColorCurves.clamp(hue, 0, 360);
  79232. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79233. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79234. if (s === 0) {
  79235. result.r = v;
  79236. result.g = v;
  79237. result.b = v;
  79238. }
  79239. else {
  79240. // sector 0 to 5
  79241. h /= 60;
  79242. var i = Math.floor(h);
  79243. // fractional part of h
  79244. var f = h - i;
  79245. var p = v * (1 - s);
  79246. var q = v * (1 - s * f);
  79247. var t = v * (1 - s * (1 - f));
  79248. switch (i) {
  79249. case 0:
  79250. result.r = v;
  79251. result.g = t;
  79252. result.b = p;
  79253. break;
  79254. case 1:
  79255. result.r = q;
  79256. result.g = v;
  79257. result.b = p;
  79258. break;
  79259. case 2:
  79260. result.r = p;
  79261. result.g = v;
  79262. result.b = t;
  79263. break;
  79264. case 3:
  79265. result.r = p;
  79266. result.g = q;
  79267. result.b = v;
  79268. break;
  79269. case 4:
  79270. result.r = t;
  79271. result.g = p;
  79272. result.b = v;
  79273. break;
  79274. default: // case 5:
  79275. result.r = v;
  79276. result.g = p;
  79277. result.b = q;
  79278. break;
  79279. }
  79280. }
  79281. result.a = 1;
  79282. };
  79283. /**
  79284. * Returns a value clamped between min and max
  79285. * @param value The value to clamp
  79286. * @param min The minimum of value
  79287. * @param max The maximum of value
  79288. * @returns The clamped value.
  79289. */
  79290. ColorCurves.clamp = function (value, min, max) {
  79291. return Math.min(Math.max(value, min), max);
  79292. };
  79293. /**
  79294. * Clones the current color curve instance.
  79295. * @return The cloned curves
  79296. */
  79297. ColorCurves.prototype.clone = function () {
  79298. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79299. };
  79300. /**
  79301. * Serializes the current color curve instance to a json representation.
  79302. * @return a JSON representation
  79303. */
  79304. ColorCurves.prototype.serialize = function () {
  79305. return BABYLON.SerializationHelper.Serialize(this);
  79306. };
  79307. /**
  79308. * Parses the color curve from a json representation.
  79309. * @param source the JSON source to parse
  79310. * @return The parsed curves
  79311. */
  79312. ColorCurves.Parse = function (source) {
  79313. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79314. };
  79315. __decorate([
  79316. BABYLON.serialize()
  79317. ], ColorCurves.prototype, "_globalHue", void 0);
  79318. __decorate([
  79319. BABYLON.serialize()
  79320. ], ColorCurves.prototype, "_globalDensity", void 0);
  79321. __decorate([
  79322. BABYLON.serialize()
  79323. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79324. __decorate([
  79325. BABYLON.serialize()
  79326. ], ColorCurves.prototype, "_globalExposure", void 0);
  79327. __decorate([
  79328. BABYLON.serialize()
  79329. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79330. __decorate([
  79331. BABYLON.serialize()
  79332. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79333. __decorate([
  79334. BABYLON.serialize()
  79335. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79336. __decorate([
  79337. BABYLON.serialize()
  79338. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79339. __decorate([
  79340. BABYLON.serialize()
  79341. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79342. __decorate([
  79343. BABYLON.serialize()
  79344. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79345. __decorate([
  79346. BABYLON.serialize()
  79347. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79348. __decorate([
  79349. BABYLON.serialize()
  79350. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79351. return ColorCurves;
  79352. }());
  79353. BABYLON.ColorCurves = ColorCurves;
  79354. })(BABYLON || (BABYLON = {}));
  79355. //# sourceMappingURL=babylon.colorCurves.js.map
  79356. var BABYLON;
  79357. (function (BABYLON) {
  79358. var RefractionPostProcess = /** @class */ (function (_super) {
  79359. __extends(RefractionPostProcess, _super);
  79360. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79361. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79362. _this.color = color;
  79363. _this.depth = depth;
  79364. _this.colorLevel = colorLevel;
  79365. _this._ownRefractionTexture = true;
  79366. _this.onActivateObservable.add(function (cam) {
  79367. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79368. });
  79369. _this.onApplyObservable.add(function (effect) {
  79370. effect.setColor3("baseColor", _this.color);
  79371. effect.setFloat("depth", _this.depth);
  79372. effect.setFloat("colorLevel", _this.colorLevel);
  79373. effect.setTexture("refractionSampler", _this._refTexture);
  79374. });
  79375. return _this;
  79376. }
  79377. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79378. /**
  79379. * Gets or sets the refraction texture
  79380. * Please note that you are responsible for disposing the texture if you set it manually
  79381. */
  79382. get: function () {
  79383. return this._refTexture;
  79384. },
  79385. set: function (value) {
  79386. if (this._refTexture && this._ownRefractionTexture) {
  79387. this._refTexture.dispose();
  79388. }
  79389. this._refTexture = value;
  79390. this._ownRefractionTexture = false;
  79391. },
  79392. enumerable: true,
  79393. configurable: true
  79394. });
  79395. // Methods
  79396. RefractionPostProcess.prototype.dispose = function (camera) {
  79397. if (this._refTexture && this._ownRefractionTexture) {
  79398. this._refTexture.dispose();
  79399. this._refTexture = null;
  79400. }
  79401. _super.prototype.dispose.call(this, camera);
  79402. };
  79403. return RefractionPostProcess;
  79404. }(BABYLON.PostProcess));
  79405. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79406. })(BABYLON || (BABYLON = {}));
  79407. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79408. var BABYLON;
  79409. (function (BABYLON) {
  79410. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79411. __extends(BlackAndWhitePostProcess, _super);
  79412. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79413. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79414. _this.degree = 1;
  79415. _this.onApplyObservable.add(function (effect) {
  79416. effect.setFloat("degree", _this.degree);
  79417. });
  79418. return _this;
  79419. }
  79420. return BlackAndWhitePostProcess;
  79421. }(BABYLON.PostProcess));
  79422. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79423. })(BABYLON || (BABYLON = {}));
  79424. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79425. var BABYLON;
  79426. (function (BABYLON) {
  79427. /**
  79428. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79429. * input texture to perform effects such as edge detection or sharpening
  79430. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79431. */
  79432. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79433. __extends(ConvolutionPostProcess, _super);
  79434. /**
  79435. * Creates a new instance ConvolutionPostProcess
  79436. * @param name The name of the effect.
  79437. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79438. * @param options The required width/height ratio to downsize to before computing the render pass.
  79439. * @param camera The camera to apply the render pass to.
  79440. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79441. * @param engine The engine which the post process will be applied. (default: current engine)
  79442. * @param reusable If the post process can be reused on the same frame. (default: false)
  79443. * @param textureType Type of textures used when performing the post process. (default: 0)
  79444. */
  79445. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79446. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79447. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79448. _this.kernel = kernel;
  79449. _this.onApply = function (effect) {
  79450. effect.setFloat2("screenSize", _this.width, _this.height);
  79451. effect.setArray("kernel", _this.kernel);
  79452. };
  79453. return _this;
  79454. }
  79455. // Statics
  79456. /**
  79457. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79458. */
  79459. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79460. /**
  79461. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79462. */
  79463. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79464. /**
  79465. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79466. */
  79467. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79468. /**
  79469. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79470. */
  79471. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79472. /**
  79473. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79474. */
  79475. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79476. /**
  79477. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79478. */
  79479. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79480. return ConvolutionPostProcess;
  79481. }(BABYLON.PostProcess));
  79482. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79483. })(BABYLON || (BABYLON = {}));
  79484. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79485. var BABYLON;
  79486. (function (BABYLON) {
  79487. var FilterPostProcess = /** @class */ (function (_super) {
  79488. __extends(FilterPostProcess, _super);
  79489. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79490. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79491. _this.kernelMatrix = kernelMatrix;
  79492. _this.onApply = function (effect) {
  79493. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79494. };
  79495. return _this;
  79496. }
  79497. return FilterPostProcess;
  79498. }(BABYLON.PostProcess));
  79499. BABYLON.FilterPostProcess = FilterPostProcess;
  79500. })(BABYLON || (BABYLON = {}));
  79501. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79502. var BABYLON;
  79503. (function (BABYLON) {
  79504. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79505. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79506. __extends(VolumetricLightScatteringPostProcess, _super);
  79507. /**
  79508. * @constructor
  79509. * @param {string} name - The post-process name
  79510. * @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)
  79511. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79512. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79513. * @param {number} samples - The post-process quality, default 100
  79514. * @param {number} samplingMode - The post-process filtering mode
  79515. * @param {BABYLON.Engine} engine - The babylon engine
  79516. * @param {boolean} reusable - If the post-process is reusable
  79517. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79518. */
  79519. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79520. if (samples === void 0) { samples = 100; }
  79521. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79522. 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;
  79523. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79524. /**
  79525. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79526. */
  79527. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79528. /**
  79529. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79530. */
  79531. _this.useCustomMeshPosition = false;
  79532. /**
  79533. * If the post-process should inverse the light scattering direction
  79534. */
  79535. _this.invert = true;
  79536. /**
  79537. * Array containing the excluded meshes not rendered in the internal pass
  79538. */
  79539. _this.excludedMeshes = new Array();
  79540. /**
  79541. * Controls the overall intensity of the post-process
  79542. */
  79543. _this.exposure = 0.3;
  79544. /**
  79545. * Dissipates each sample's contribution in range [0, 1]
  79546. */
  79547. _this.decay = 0.96815;
  79548. /**
  79549. * Controls the overall intensity of each sample
  79550. */
  79551. _this.weight = 0.58767;
  79552. /**
  79553. * Controls the density of each sample
  79554. */
  79555. _this.density = 0.926;
  79556. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79557. engine = scene.getEngine();
  79558. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79559. // Configure mesh
  79560. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79561. // Configure
  79562. _this._createPass(scene, ratio.passRatio || ratio);
  79563. _this.onActivate = function (camera) {
  79564. if (!_this.isSupported) {
  79565. _this.dispose(camera);
  79566. }
  79567. _this.onActivate = null;
  79568. };
  79569. _this.onApplyObservable.add(function (effect) {
  79570. _this._updateMeshScreenCoordinates(scene);
  79571. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79572. effect.setFloat("exposure", _this.exposure);
  79573. effect.setFloat("decay", _this.decay);
  79574. effect.setFloat("weight", _this.weight);
  79575. effect.setFloat("density", _this.density);
  79576. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79577. });
  79578. return _this;
  79579. }
  79580. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79581. get: function () {
  79582. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79583. return false;
  79584. },
  79585. set: function (useDiffuseColor) {
  79586. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79587. },
  79588. enumerable: true,
  79589. configurable: true
  79590. });
  79591. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79592. return "VolumetricLightScatteringPostProcess";
  79593. };
  79594. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79595. var mesh = subMesh.getMesh();
  79596. // Render this.mesh as default
  79597. if (mesh === this.mesh && mesh.material) {
  79598. return mesh.material.isReady(mesh);
  79599. }
  79600. var defines = [];
  79601. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79602. var material = subMesh.getMaterial();
  79603. // Alpha test
  79604. if (material) {
  79605. if (material.needAlphaTesting()) {
  79606. defines.push("#define ALPHATEST");
  79607. }
  79608. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79609. attribs.push(BABYLON.VertexBuffer.UVKind);
  79610. defines.push("#define UV1");
  79611. }
  79612. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79614. defines.push("#define UV2");
  79615. }
  79616. }
  79617. // Bones
  79618. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79619. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79620. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79621. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79622. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79623. }
  79624. else {
  79625. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79626. }
  79627. // Instances
  79628. if (useInstances) {
  79629. defines.push("#define INSTANCES");
  79630. attribs.push("world0");
  79631. attribs.push("world1");
  79632. attribs.push("world2");
  79633. attribs.push("world3");
  79634. }
  79635. // Get correct effect
  79636. var join = defines.join("\n");
  79637. if (this._cachedDefines !== join) {
  79638. this._cachedDefines = join;
  79639. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  79640. }
  79641. return this._volumetricLightScatteringPass.isReady();
  79642. };
  79643. /**
  79644. * Sets the new light position for light scattering effect
  79645. * @param {BABYLON.Vector3} The new custom light position
  79646. */
  79647. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  79648. this.customMeshPosition = position;
  79649. };
  79650. /**
  79651. * Returns the light position for light scattering effect
  79652. * @return {BABYLON.Vector3} The custom light position
  79653. */
  79654. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  79655. return this.customMeshPosition;
  79656. };
  79657. /**
  79658. * Disposes the internal assets and detaches the post-process from the camera
  79659. */
  79660. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  79661. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  79662. if (rttIndex !== -1) {
  79663. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  79664. }
  79665. this._volumetricLightScatteringRTT.dispose();
  79666. _super.prototype.dispose.call(this, camera);
  79667. };
  79668. /**
  79669. * Returns the render target texture used by the post-process
  79670. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  79671. */
  79672. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  79673. return this._volumetricLightScatteringRTT;
  79674. };
  79675. // Private methods
  79676. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  79677. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  79678. return true;
  79679. }
  79680. return false;
  79681. };
  79682. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  79683. var _this = this;
  79684. var engine = scene.getEngine();
  79685. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79686. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79687. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79688. this._volumetricLightScatteringRTT.renderList = null;
  79689. this._volumetricLightScatteringRTT.renderParticles = false;
  79690. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  79691. var camera = this.getCamera();
  79692. if (camera) {
  79693. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79694. }
  79695. else {
  79696. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79697. }
  79698. // Custom render function for submeshes
  79699. var renderSubMesh = function (subMesh) {
  79700. var mesh = subMesh.getRenderingMesh();
  79701. if (_this._meshExcluded(mesh)) {
  79702. return;
  79703. }
  79704. var material = subMesh.getMaterial();
  79705. if (!material) {
  79706. return;
  79707. }
  79708. var scene = mesh.getScene();
  79709. var engine = scene.getEngine();
  79710. // Culling
  79711. engine.setState(material.backFaceCulling);
  79712. // Managing instances
  79713. var batch = mesh._getInstancesRenderList(subMesh._id);
  79714. if (batch.mustReturn) {
  79715. return;
  79716. }
  79717. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79718. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79719. var effect = _this._volumetricLightScatteringPass;
  79720. if (mesh === _this.mesh) {
  79721. if (subMesh.effect) {
  79722. effect = subMesh.effect;
  79723. }
  79724. else {
  79725. effect = material.getEffect();
  79726. }
  79727. }
  79728. engine.enableEffect(effect);
  79729. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79730. if (mesh === _this.mesh) {
  79731. material.bind(mesh.getWorldMatrix(), mesh);
  79732. }
  79733. else {
  79734. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79735. // Alpha test
  79736. if (material && material.needAlphaTesting()) {
  79737. var alphaTexture = material.getAlphaTestTexture();
  79738. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79739. if (alphaTexture) {
  79740. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79741. }
  79742. }
  79743. // Bones
  79744. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79745. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79746. }
  79747. }
  79748. // Draw
  79749. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79750. }
  79751. };
  79752. // Render target texture callbacks
  79753. var savedSceneClearColor;
  79754. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79755. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79756. savedSceneClearColor = scene.clearColor;
  79757. scene.clearColor = sceneClearColor;
  79758. });
  79759. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79760. scene.clearColor = savedSceneClearColor;
  79761. });
  79762. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79763. var engine = scene.getEngine();
  79764. var index;
  79765. if (depthOnlySubMeshes.length) {
  79766. engine.setColorWrite(false);
  79767. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79768. renderSubMesh(depthOnlySubMeshes.data[index]);
  79769. }
  79770. engine.setColorWrite(true);
  79771. }
  79772. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79773. renderSubMesh(opaqueSubMeshes.data[index]);
  79774. }
  79775. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79776. renderSubMesh(alphaTestSubMeshes.data[index]);
  79777. }
  79778. if (transparentSubMeshes.length) {
  79779. // Sort sub meshes
  79780. for (index = 0; index < transparentSubMeshes.length; index++) {
  79781. var submesh = transparentSubMeshes.data[index];
  79782. var boundingInfo = submesh.getBoundingInfo();
  79783. if (boundingInfo && scene.activeCamera) {
  79784. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79785. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79786. }
  79787. }
  79788. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79789. sortedArray.sort(function (a, b) {
  79790. // Alpha index first
  79791. if (a._alphaIndex > b._alphaIndex) {
  79792. return 1;
  79793. }
  79794. if (a._alphaIndex < b._alphaIndex) {
  79795. return -1;
  79796. }
  79797. // Then distance to camera
  79798. if (a._distanceToCamera < b._distanceToCamera) {
  79799. return 1;
  79800. }
  79801. if (a._distanceToCamera > b._distanceToCamera) {
  79802. return -1;
  79803. }
  79804. return 0;
  79805. });
  79806. // Render sub meshes
  79807. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79808. for (index = 0; index < sortedArray.length; index++) {
  79809. renderSubMesh(sortedArray[index]);
  79810. }
  79811. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79812. }
  79813. };
  79814. };
  79815. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79816. var transform = scene.getTransformMatrix();
  79817. var meshPosition;
  79818. if (this.useCustomMeshPosition) {
  79819. meshPosition = this.customMeshPosition;
  79820. }
  79821. else if (this.attachedNode) {
  79822. meshPosition = this.attachedNode.position;
  79823. }
  79824. else {
  79825. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79826. }
  79827. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79828. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79829. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79830. if (this.invert)
  79831. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79832. };
  79833. // Static methods
  79834. /**
  79835. * Creates a default mesh for the Volumeric Light Scattering post-process
  79836. * @param {string} The mesh name
  79837. * @param {BABYLON.Scene} The scene where to create the mesh
  79838. * @return {BABYLON.Mesh} the default mesh
  79839. */
  79840. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79841. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79842. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79843. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79844. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79845. mesh.material = material;
  79846. return mesh;
  79847. };
  79848. __decorate([
  79849. BABYLON.serializeAsVector3()
  79850. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79851. __decorate([
  79852. BABYLON.serialize()
  79853. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79854. __decorate([
  79855. BABYLON.serialize()
  79856. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79857. __decorate([
  79858. BABYLON.serializeAsMeshReference()
  79859. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79860. __decorate([
  79861. BABYLON.serialize()
  79862. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79863. __decorate([
  79864. BABYLON.serialize()
  79865. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79866. __decorate([
  79867. BABYLON.serialize()
  79868. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79869. __decorate([
  79870. BABYLON.serialize()
  79871. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79872. __decorate([
  79873. BABYLON.serialize()
  79874. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79875. return VolumetricLightScatteringPostProcess;
  79876. }(BABYLON.PostProcess));
  79877. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79878. })(BABYLON || (BABYLON = {}));
  79879. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79880. //
  79881. // This post-process allows the modification of rendered colors by using
  79882. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79883. //
  79884. // The object needs to be provided an url to a texture containing the color
  79885. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79886. // Use an image editing software to tweak the LUT to match your needs.
  79887. //
  79888. // For an example of a color LUT, see here:
  79889. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79890. // For explanations on color grading, see here:
  79891. // http://udn.epicgames.com/Three/ColorGrading.html
  79892. //
  79893. var BABYLON;
  79894. (function (BABYLON) {
  79895. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79896. __extends(ColorCorrectionPostProcess, _super);
  79897. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79898. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79899. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79900. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79901. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79902. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79903. _this.onApply = function (effect) {
  79904. effect.setTexture("colorTable", _this._colorTableTexture);
  79905. };
  79906. return _this;
  79907. }
  79908. return ColorCorrectionPostProcess;
  79909. }(BABYLON.PostProcess));
  79910. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79911. })(BABYLON || (BABYLON = {}));
  79912. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79913. var BABYLON;
  79914. (function (BABYLON) {
  79915. /** Defines operator used for tonemapping */
  79916. var TonemappingOperator;
  79917. (function (TonemappingOperator) {
  79918. /** Hable */
  79919. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79920. /** Reinhard */
  79921. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79922. /** HejiDawson */
  79923. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79924. /** Photographic */
  79925. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79926. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79927. ;
  79928. /**
  79929. * Defines a post process to apply tone mapping
  79930. */
  79931. var TonemapPostProcess = /** @class */ (function (_super) {
  79932. __extends(TonemapPostProcess, _super);
  79933. /**
  79934. * Creates a new TonemapPostProcess
  79935. * @param name defines the name of the postprocess
  79936. * @param _operator defines the operator to use
  79937. * @param exposureAdjustment defines the required exposure adjustement
  79938. * @param camera defines the camera to use (can be null)
  79939. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79940. * @param engine defines the hosting engine (can be ignore if camera is set)
  79941. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79942. */
  79943. function TonemapPostProcess(name, _operator,
  79944. /** Defines the required exposure adjustement */
  79945. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79947. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79948. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79949. _this._operator = _operator;
  79950. _this.exposureAdjustment = exposureAdjustment;
  79951. var defines = "#define ";
  79952. if (_this._operator === TonemappingOperator.Hable)
  79953. defines += "HABLE_TONEMAPPING";
  79954. else if (_this._operator === TonemappingOperator.Reinhard)
  79955. defines += "REINHARD_TONEMAPPING";
  79956. else if (_this._operator === TonemappingOperator.HejiDawson)
  79957. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79958. else if (_this._operator === TonemappingOperator.Photographic)
  79959. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79960. //sadly a second call to create the effect.
  79961. _this.updateEffect(defines);
  79962. _this.onApply = function (effect) {
  79963. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79964. };
  79965. return _this;
  79966. }
  79967. return TonemapPostProcess;
  79968. }(BABYLON.PostProcess));
  79969. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79970. })(BABYLON || (BABYLON = {}));
  79971. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79972. var BABYLON;
  79973. (function (BABYLON) {
  79974. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79975. __extends(DisplayPassPostProcess, _super);
  79976. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79977. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79978. }
  79979. return DisplayPassPostProcess;
  79980. }(BABYLON.PostProcess));
  79981. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79982. })(BABYLON || (BABYLON = {}));
  79983. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79984. var BABYLON;
  79985. (function (BABYLON) {
  79986. var HighlightsPostProcess = /** @class */ (function (_super) {
  79987. __extends(HighlightsPostProcess, _super);
  79988. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79989. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79990. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79991. }
  79992. return HighlightsPostProcess;
  79993. }(BABYLON.PostProcess));
  79994. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79995. })(BABYLON || (BABYLON = {}));
  79996. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79997. var BABYLON;
  79998. (function (BABYLON) {
  79999. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80000. __extends(ImageProcessingPostProcess, _super);
  80001. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80002. if (camera === void 0) { camera = null; }
  80003. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80004. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80005. _this._fromLinearSpace = true;
  80006. /**
  80007. * Defines cache preventing GC.
  80008. */
  80009. _this._defines = {
  80010. IMAGEPROCESSING: false,
  80011. VIGNETTE: false,
  80012. VIGNETTEBLENDMODEMULTIPLY: false,
  80013. VIGNETTEBLENDMODEOPAQUE: false,
  80014. TONEMAPPING: false,
  80015. CONTRAST: false,
  80016. COLORCURVES: false,
  80017. COLORGRADING: false,
  80018. COLORGRADING3D: false,
  80019. FROMLINEARSPACE: false,
  80020. SAMPLER3DGREENDEPTH: false,
  80021. SAMPLER3DBGRMAP: false,
  80022. IMAGEPROCESSINGPOSTPROCESS: false,
  80023. EXPOSURE: false,
  80024. };
  80025. // Setup the configuration as forced by the constructor. This would then not force the
  80026. // scene materials output in linear space and let untouched the default forward pass.
  80027. if (imageProcessingConfiguration) {
  80028. imageProcessingConfiguration.applyByPostProcess = true;
  80029. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80030. // This will cause the shader to be compiled
  80031. _this.fromLinearSpace = false;
  80032. }
  80033. // Setup the default processing configuration to the scene.
  80034. else {
  80035. _this._attachImageProcessingConfiguration(null, true);
  80036. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80037. }
  80038. _this.onApply = function (effect) {
  80039. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80040. };
  80041. return _this;
  80042. }
  80043. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80044. /**
  80045. * Gets the image processing configuration used either in this material.
  80046. */
  80047. get: function () {
  80048. return this._imageProcessingConfiguration;
  80049. },
  80050. /**
  80051. * Sets the Default image processing configuration used either in the this material.
  80052. *
  80053. * If sets to null, the scene one is in use.
  80054. */
  80055. set: function (value) {
  80056. this._attachImageProcessingConfiguration(value);
  80057. },
  80058. enumerable: true,
  80059. configurable: true
  80060. });
  80061. /**
  80062. * Attaches a new image processing configuration to the PBR Material.
  80063. * @param configuration
  80064. */
  80065. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80066. var _this = this;
  80067. if (doNotBuild === void 0) { doNotBuild = false; }
  80068. if (configuration === this._imageProcessingConfiguration) {
  80069. return;
  80070. }
  80071. // Detaches observer.
  80072. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80073. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80074. }
  80075. // Pick the scene configuration if needed.
  80076. if (!configuration) {
  80077. var scene = null;
  80078. var engine = this.getEngine();
  80079. var camera = this.getCamera();
  80080. if (camera) {
  80081. scene = camera.getScene();
  80082. }
  80083. else if (engine && engine.scenes) {
  80084. var scenes = engine.scenes;
  80085. scene = scenes[scenes.length - 1];
  80086. }
  80087. else {
  80088. scene = BABYLON.Engine.LastCreatedScene;
  80089. }
  80090. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80091. }
  80092. else {
  80093. this._imageProcessingConfiguration = configuration;
  80094. }
  80095. // Attaches observer.
  80096. if (this._imageProcessingConfiguration) {
  80097. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80098. _this._updateParameters();
  80099. });
  80100. }
  80101. // Ensure the effect will be rebuilt.
  80102. if (!doNotBuild) {
  80103. this._updateParameters();
  80104. }
  80105. };
  80106. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80107. /**
  80108. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80109. */
  80110. get: function () {
  80111. return this.imageProcessingConfiguration.colorCurves;
  80112. },
  80113. /**
  80114. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80115. */
  80116. set: function (value) {
  80117. this.imageProcessingConfiguration.colorCurves = value;
  80118. },
  80119. enumerable: true,
  80120. configurable: true
  80121. });
  80122. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80123. /**
  80124. * Gets wether the color curves effect is enabled.
  80125. */
  80126. get: function () {
  80127. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80128. },
  80129. /**
  80130. * Sets wether the color curves effect is enabled.
  80131. */
  80132. set: function (value) {
  80133. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80134. },
  80135. enumerable: true,
  80136. configurable: true
  80137. });
  80138. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80139. /**
  80140. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80141. */
  80142. get: function () {
  80143. return this.imageProcessingConfiguration.colorGradingTexture;
  80144. },
  80145. /**
  80146. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80147. */
  80148. set: function (value) {
  80149. this.imageProcessingConfiguration.colorGradingTexture = value;
  80150. },
  80151. enumerable: true,
  80152. configurable: true
  80153. });
  80154. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80155. /**
  80156. * Gets wether the color grading effect is enabled.
  80157. */
  80158. get: function () {
  80159. return this.imageProcessingConfiguration.colorGradingEnabled;
  80160. },
  80161. /**
  80162. * Gets wether the color grading effect is enabled.
  80163. */
  80164. set: function (value) {
  80165. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80166. },
  80167. enumerable: true,
  80168. configurable: true
  80169. });
  80170. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80171. /**
  80172. * Gets exposure used in the effect.
  80173. */
  80174. get: function () {
  80175. return this.imageProcessingConfiguration.exposure;
  80176. },
  80177. /**
  80178. * Sets exposure used in the effect.
  80179. */
  80180. set: function (value) {
  80181. this.imageProcessingConfiguration.exposure = value;
  80182. },
  80183. enumerable: true,
  80184. configurable: true
  80185. });
  80186. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80187. /**
  80188. * Gets wether tonemapping is enabled or not.
  80189. */
  80190. get: function () {
  80191. return this._imageProcessingConfiguration.toneMappingEnabled;
  80192. },
  80193. /**
  80194. * Sets wether tonemapping is enabled or not
  80195. */
  80196. set: function (value) {
  80197. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80198. },
  80199. enumerable: true,
  80200. configurable: true
  80201. });
  80202. ;
  80203. ;
  80204. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80205. /**
  80206. * Gets contrast used in the effect.
  80207. */
  80208. get: function () {
  80209. return this.imageProcessingConfiguration.contrast;
  80210. },
  80211. /**
  80212. * Sets contrast used in the effect.
  80213. */
  80214. set: function (value) {
  80215. this.imageProcessingConfiguration.contrast = value;
  80216. },
  80217. enumerable: true,
  80218. configurable: true
  80219. });
  80220. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80221. /**
  80222. * Gets Vignette stretch size.
  80223. */
  80224. get: function () {
  80225. return this.imageProcessingConfiguration.vignetteStretch;
  80226. },
  80227. /**
  80228. * Sets Vignette stretch size.
  80229. */
  80230. set: function (value) {
  80231. this.imageProcessingConfiguration.vignetteStretch = value;
  80232. },
  80233. enumerable: true,
  80234. configurable: true
  80235. });
  80236. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80237. /**
  80238. * Gets Vignette centre X Offset.
  80239. */
  80240. get: function () {
  80241. return this.imageProcessingConfiguration.vignetteCentreX;
  80242. },
  80243. /**
  80244. * Sets Vignette centre X Offset.
  80245. */
  80246. set: function (value) {
  80247. this.imageProcessingConfiguration.vignetteCentreX = value;
  80248. },
  80249. enumerable: true,
  80250. configurable: true
  80251. });
  80252. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80253. /**
  80254. * Gets Vignette centre Y Offset.
  80255. */
  80256. get: function () {
  80257. return this.imageProcessingConfiguration.vignetteCentreY;
  80258. },
  80259. /**
  80260. * Sets Vignette centre Y Offset.
  80261. */
  80262. set: function (value) {
  80263. this.imageProcessingConfiguration.vignetteCentreY = value;
  80264. },
  80265. enumerable: true,
  80266. configurable: true
  80267. });
  80268. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80269. /**
  80270. * Gets Vignette weight or intensity of the vignette effect.
  80271. */
  80272. get: function () {
  80273. return this.imageProcessingConfiguration.vignetteWeight;
  80274. },
  80275. /**
  80276. * Sets Vignette weight or intensity of the vignette effect.
  80277. */
  80278. set: function (value) {
  80279. this.imageProcessingConfiguration.vignetteWeight = value;
  80280. },
  80281. enumerable: true,
  80282. configurable: true
  80283. });
  80284. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80285. /**
  80286. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80287. * if vignetteEnabled is set to true.
  80288. */
  80289. get: function () {
  80290. return this.imageProcessingConfiguration.vignetteColor;
  80291. },
  80292. /**
  80293. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80294. * if vignetteEnabled is set to true.
  80295. */
  80296. set: function (value) {
  80297. this.imageProcessingConfiguration.vignetteColor = value;
  80298. },
  80299. enumerable: true,
  80300. configurable: true
  80301. });
  80302. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80303. /**
  80304. * Gets Camera field of view used by the Vignette effect.
  80305. */
  80306. get: function () {
  80307. return this.imageProcessingConfiguration.vignetteCameraFov;
  80308. },
  80309. /**
  80310. * Sets Camera field of view used by the Vignette effect.
  80311. */
  80312. set: function (value) {
  80313. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80314. },
  80315. enumerable: true,
  80316. configurable: true
  80317. });
  80318. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80319. /**
  80320. * Gets the vignette blend mode allowing different kind of effect.
  80321. */
  80322. get: function () {
  80323. return this.imageProcessingConfiguration.vignetteBlendMode;
  80324. },
  80325. /**
  80326. * Sets the vignette blend mode allowing different kind of effect.
  80327. */
  80328. set: function (value) {
  80329. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80330. },
  80331. enumerable: true,
  80332. configurable: true
  80333. });
  80334. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80335. /**
  80336. * Gets wether the vignette effect is enabled.
  80337. */
  80338. get: function () {
  80339. return this.imageProcessingConfiguration.vignetteEnabled;
  80340. },
  80341. /**
  80342. * Sets wether the vignette effect is enabled.
  80343. */
  80344. set: function (value) {
  80345. this.imageProcessingConfiguration.vignetteEnabled = value;
  80346. },
  80347. enumerable: true,
  80348. configurable: true
  80349. });
  80350. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80351. /**
  80352. * Gets wether the input of the processing is in Gamma or Linear Space.
  80353. */
  80354. get: function () {
  80355. return this._fromLinearSpace;
  80356. },
  80357. /**
  80358. * Sets wether the input of the processing is in Gamma or Linear Space.
  80359. */
  80360. set: function (value) {
  80361. if (this._fromLinearSpace === value) {
  80362. return;
  80363. }
  80364. this._fromLinearSpace = value;
  80365. this._updateParameters();
  80366. },
  80367. enumerable: true,
  80368. configurable: true
  80369. });
  80370. ImageProcessingPostProcess.prototype.getClassName = function () {
  80371. return "ImageProcessingPostProcess";
  80372. };
  80373. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80374. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80375. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80376. var defines = "";
  80377. for (var define in this._defines) {
  80378. if (this._defines[define]) {
  80379. defines += "#define " + define + ";\r\n";
  80380. }
  80381. }
  80382. var samplers = ["textureSampler"];
  80383. var uniforms = ["scale"];
  80384. if (BABYLON.ImageProcessingConfiguration) {
  80385. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80386. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80387. }
  80388. this.updateEffect(defines, uniforms, samplers);
  80389. };
  80390. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80391. _super.prototype.dispose.call(this, camera);
  80392. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80393. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80394. }
  80395. if (this._imageProcessingConfiguration) {
  80396. this.imageProcessingConfiguration.applyByPostProcess = false;
  80397. }
  80398. };
  80399. __decorate([
  80400. BABYLON.serialize()
  80401. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80402. return ImageProcessingPostProcess;
  80403. }(BABYLON.PostProcess));
  80404. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80405. })(BABYLON || (BABYLON = {}));
  80406. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80407. var BABYLON;
  80408. (function (BABYLON) {
  80409. /**
  80410. * Class used to store bone information
  80411. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80412. */
  80413. var Bone = /** @class */ (function (_super) {
  80414. __extends(Bone, _super);
  80415. /**
  80416. * Create a new bone
  80417. * @param name defines the bone name
  80418. * @param skeleton defines the parent skeleton
  80419. * @param parentBone defines the parent (can be null if the bone is the root)
  80420. * @param localMatrix defines the local matrix
  80421. * @param restPose defines the rest pose matrix
  80422. * @param baseMatrix defines the base matrix
  80423. * @param index defines index of the bone in the hiearchy
  80424. */
  80425. function Bone(
  80426. /**
  80427. * defines the bone name
  80428. */
  80429. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80430. if (parentBone === void 0) { parentBone = null; }
  80431. if (localMatrix === void 0) { localMatrix = null; }
  80432. if (restPose === void 0) { restPose = null; }
  80433. if (baseMatrix === void 0) { baseMatrix = null; }
  80434. if (index === void 0) { index = null; }
  80435. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80436. _this.name = name;
  80437. /**
  80438. * Gets the list of child bones
  80439. */
  80440. _this.children = new Array();
  80441. /** Gets the animations associated with this bone */
  80442. _this.animations = new Array();
  80443. /**
  80444. * @hidden Internal only
  80445. * Set this value to map this bone to a different index in the transform matrices
  80446. * Set this value to -1 to exclude the bone from the transform matrices
  80447. */
  80448. _this._index = null;
  80449. _this._absoluteTransform = new BABYLON.Matrix();
  80450. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80451. _this._scalingDeterminant = 1;
  80452. _this._worldTransform = new BABYLON.Matrix();
  80453. _this._needToDecompose = true;
  80454. _this._needToCompose = false;
  80455. _this._skeleton = skeleton;
  80456. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80457. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80458. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80459. _this._index = index;
  80460. skeleton.bones.push(_this);
  80461. _this.setParent(parentBone, false);
  80462. if (baseMatrix || localMatrix) {
  80463. _this._updateDifferenceMatrix();
  80464. }
  80465. return _this;
  80466. }
  80467. Object.defineProperty(Bone.prototype, "_matrix", {
  80468. /** @hidden */
  80469. get: function () {
  80470. this._compose();
  80471. return this._localMatrix;
  80472. },
  80473. /** @hidden */
  80474. set: function (value) {
  80475. this._localMatrix.copyFrom(value);
  80476. this._needToDecompose = true;
  80477. },
  80478. enumerable: true,
  80479. configurable: true
  80480. });
  80481. // Members
  80482. /**
  80483. * Gets the parent skeleton
  80484. * @returns a skeleton
  80485. */
  80486. Bone.prototype.getSkeleton = function () {
  80487. return this._skeleton;
  80488. };
  80489. /**
  80490. * Gets parent bone
  80491. * @returns a bone or null if the bone is the root of the bone hierarchy
  80492. */
  80493. Bone.prototype.getParent = function () {
  80494. return this._parent;
  80495. };
  80496. /**
  80497. * Sets the parent bone
  80498. * @param parent defines the parent (can be null if the bone is the root)
  80499. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80500. */
  80501. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80502. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80503. if (this._parent === parent) {
  80504. return;
  80505. }
  80506. if (this._parent) {
  80507. var index = this._parent.children.indexOf(this);
  80508. if (index !== -1) {
  80509. this._parent.children.splice(index, 1);
  80510. }
  80511. }
  80512. this._parent = parent;
  80513. if (this._parent) {
  80514. this._parent.children.push(this);
  80515. }
  80516. if (updateDifferenceMatrix) {
  80517. this._updateDifferenceMatrix();
  80518. }
  80519. this.markAsDirty();
  80520. };
  80521. /**
  80522. * Gets the local matrix
  80523. * @returns a matrix
  80524. */
  80525. Bone.prototype.getLocalMatrix = function () {
  80526. this._compose();
  80527. return this._localMatrix;
  80528. };
  80529. /**
  80530. * Gets the base matrix (initial matrix which remains unchanged)
  80531. * @returns a matrix
  80532. */
  80533. Bone.prototype.getBaseMatrix = function () {
  80534. return this._baseMatrix;
  80535. };
  80536. /**
  80537. * Gets the rest pose matrix
  80538. * @returns a matrix
  80539. */
  80540. Bone.prototype.getRestPose = function () {
  80541. return this._restPose;
  80542. };
  80543. /**
  80544. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80545. */
  80546. Bone.prototype.getWorldMatrix = function () {
  80547. return this._worldTransform;
  80548. };
  80549. /**
  80550. * Sets the local matrix to rest pose matrix
  80551. */
  80552. Bone.prototype.returnToRest = function () {
  80553. this.updateMatrix(this._restPose.clone());
  80554. };
  80555. /**
  80556. * Gets the inverse of the absolute transform matrix.
  80557. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80558. * @returns a matrix
  80559. */
  80560. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80561. return this._invertedAbsoluteTransform;
  80562. };
  80563. /**
  80564. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80565. * @returns a matrix
  80566. */
  80567. Bone.prototype.getAbsoluteTransform = function () {
  80568. return this._absoluteTransform;
  80569. };
  80570. Object.defineProperty(Bone.prototype, "position", {
  80571. // Properties (matches AbstractMesh properties)
  80572. /** Gets or sets current position (in local space) */
  80573. get: function () {
  80574. this._decompose();
  80575. return this._localPosition;
  80576. },
  80577. set: function (newPosition) {
  80578. this._decompose();
  80579. this._localPosition.copyFrom(newPosition);
  80580. this._markAsDirtyAndCompose();
  80581. },
  80582. enumerable: true,
  80583. configurable: true
  80584. });
  80585. Object.defineProperty(Bone.prototype, "rotation", {
  80586. /** Gets or sets current rotation (in local space) */
  80587. get: function () {
  80588. return this.getRotation();
  80589. },
  80590. set: function (newRotation) {
  80591. this.setRotation(newRotation);
  80592. },
  80593. enumerable: true,
  80594. configurable: true
  80595. });
  80596. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80597. /** Gets or sets current rotation quaternion (in local space) */
  80598. get: function () {
  80599. this._decompose();
  80600. return this._localRotation;
  80601. },
  80602. set: function (newRotation) {
  80603. this.setRotationQuaternion(newRotation);
  80604. },
  80605. enumerable: true,
  80606. configurable: true
  80607. });
  80608. Object.defineProperty(Bone.prototype, "scaling", {
  80609. /** Gets or sets current scaling (in local space) */
  80610. get: function () {
  80611. return this.getScale();
  80612. },
  80613. set: function (newScaling) {
  80614. this.setScale(newScaling);
  80615. },
  80616. enumerable: true,
  80617. configurable: true
  80618. });
  80619. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  80620. /**
  80621. * Gets the animation properties override
  80622. */
  80623. get: function () {
  80624. return this._skeleton.animationPropertiesOverride;
  80625. },
  80626. enumerable: true,
  80627. configurable: true
  80628. });
  80629. // Methods
  80630. Bone.prototype._decompose = function () {
  80631. if (!this._needToDecompose) {
  80632. return;
  80633. }
  80634. this._needToDecompose = false;
  80635. if (!this._localScaling) {
  80636. this._localScaling = BABYLON.Vector3.Zero();
  80637. this._localRotation = BABYLON.Quaternion.Zero();
  80638. this._localPosition = BABYLON.Vector3.Zero();
  80639. }
  80640. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  80641. };
  80642. Bone.prototype._compose = function () {
  80643. if (!this._needToCompose) {
  80644. return;
  80645. }
  80646. this._needToCompose = false;
  80647. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  80648. };
  80649. /**
  80650. * Update the base and local matrices
  80651. * @param matrix defines the new base or local matrix
  80652. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80653. * @param updateLocalMatrix defines if the local matrix should be updated
  80654. */
  80655. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  80656. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80657. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  80658. this._baseMatrix.copyFrom(matrix);
  80659. if (updateDifferenceMatrix) {
  80660. this._updateDifferenceMatrix();
  80661. }
  80662. if (updateLocalMatrix) {
  80663. this._localMatrix.copyFrom(matrix);
  80664. this._markAsDirtyAndDecompose();
  80665. }
  80666. else {
  80667. this.markAsDirty();
  80668. }
  80669. };
  80670. /** @hidden */
  80671. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  80672. if (updateChildren === void 0) { updateChildren = true; }
  80673. if (!rootMatrix) {
  80674. rootMatrix = this._baseMatrix;
  80675. }
  80676. if (this._parent) {
  80677. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80678. }
  80679. else {
  80680. this._absoluteTransform.copyFrom(rootMatrix);
  80681. }
  80682. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  80683. if (updateChildren) {
  80684. for (var index = 0; index < this.children.length; index++) {
  80685. this.children[index]._updateDifferenceMatrix();
  80686. }
  80687. }
  80688. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  80689. };
  80690. /**
  80691. * Flag the bone as dirty (Forcing it to update everything)
  80692. */
  80693. Bone.prototype.markAsDirty = function () {
  80694. this._currentRenderId++;
  80695. this._childRenderId++;
  80696. this._skeleton._markAsDirty();
  80697. };
  80698. Bone.prototype._markAsDirtyAndCompose = function () {
  80699. this.markAsDirty();
  80700. this._needToCompose = true;
  80701. };
  80702. Bone.prototype._markAsDirtyAndDecompose = function () {
  80703. this.markAsDirty();
  80704. this._needToDecompose = true;
  80705. };
  80706. /**
  80707. * Copy an animation range from another bone
  80708. * @param source defines the source bone
  80709. * @param rangeName defines the range name to copy
  80710. * @param frameOffset defines the frame offset
  80711. * @param rescaleAsRequired defines if rescaling must be applied if required
  80712. * @param skelDimensionsRatio defines the scaling ratio
  80713. * @returns true if operation was successful
  80714. */
  80715. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80716. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80717. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80718. // all animation may be coming from a library skeleton, so may need to create animation
  80719. if (this.animations.length === 0) {
  80720. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80721. this.animations[0].setKeys([]);
  80722. }
  80723. // get animation info / verify there is such a range from the source bone
  80724. var sourceRange = source.animations[0].getRange(rangeName);
  80725. if (!sourceRange) {
  80726. return false;
  80727. }
  80728. var from = sourceRange.from;
  80729. var to = sourceRange.to;
  80730. var sourceKeys = source.animations[0].getKeys();
  80731. // rescaling prep
  80732. var sourceBoneLength = source.length;
  80733. var sourceParent = source.getParent();
  80734. var parent = this.getParent();
  80735. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80736. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80737. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80738. var destKeys = this.animations[0].getKeys();
  80739. // loop vars declaration
  80740. var orig;
  80741. var origTranslation;
  80742. var mat;
  80743. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80744. orig = sourceKeys[key];
  80745. if (orig.frame >= from && orig.frame <= to) {
  80746. if (rescaleAsRequired) {
  80747. mat = orig.value.clone();
  80748. // scale based on parent ratio, when bone has parent
  80749. if (parentScalingReqd) {
  80750. origTranslation = mat.getTranslation();
  80751. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80752. // scale based on skeleton dimension ratio when root bone, and value is passed
  80753. }
  80754. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80755. origTranslation = mat.getTranslation();
  80756. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80757. // use original when root bone, and no data for skelDimensionsRatio
  80758. }
  80759. else {
  80760. mat = orig.value;
  80761. }
  80762. }
  80763. else {
  80764. mat = orig.value;
  80765. }
  80766. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80767. }
  80768. }
  80769. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80770. return true;
  80771. };
  80772. /**
  80773. * Translate the bone in local or world space
  80774. * @param vec The amount to translate the bone
  80775. * @param space The space that the translation is in
  80776. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80777. */
  80778. Bone.prototype.translate = function (vec, space, mesh) {
  80779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80780. var lm = this.getLocalMatrix();
  80781. if (space == BABYLON.Space.LOCAL) {
  80782. lm.m[12] += vec.x;
  80783. lm.m[13] += vec.y;
  80784. lm.m[14] += vec.z;
  80785. }
  80786. else {
  80787. var wm = null;
  80788. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80789. if (mesh) {
  80790. wm = mesh.getWorldMatrix();
  80791. }
  80792. this._skeleton.computeAbsoluteTransforms();
  80793. var tmat = Bone._tmpMats[0];
  80794. var tvec = Bone._tmpVecs[0];
  80795. if (this._parent) {
  80796. if (mesh && wm) {
  80797. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80798. tmat.multiplyToRef(wm, tmat);
  80799. }
  80800. else {
  80801. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80802. }
  80803. }
  80804. tmat.m[12] = 0;
  80805. tmat.m[13] = 0;
  80806. tmat.m[14] = 0;
  80807. tmat.invert();
  80808. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80809. lm.m[12] += tvec.x;
  80810. lm.m[13] += tvec.y;
  80811. lm.m[14] += tvec.z;
  80812. }
  80813. this._markAsDirtyAndDecompose();
  80814. };
  80815. /**
  80816. * Set the postion of the bone in local or world space
  80817. * @param position The position to set the bone
  80818. * @param space The space that the position is in
  80819. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80820. */
  80821. Bone.prototype.setPosition = function (position, space, mesh) {
  80822. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80823. var lm = this.getLocalMatrix();
  80824. if (space == BABYLON.Space.LOCAL) {
  80825. lm.m[12] = position.x;
  80826. lm.m[13] = position.y;
  80827. lm.m[14] = position.z;
  80828. }
  80829. else {
  80830. var wm = null;
  80831. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80832. if (mesh) {
  80833. wm = mesh.getWorldMatrix();
  80834. }
  80835. this._skeleton.computeAbsoluteTransforms();
  80836. var tmat = Bone._tmpMats[0];
  80837. var vec = Bone._tmpVecs[0];
  80838. if (this._parent) {
  80839. if (mesh && wm) {
  80840. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80841. tmat.multiplyToRef(wm, tmat);
  80842. }
  80843. else {
  80844. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80845. }
  80846. }
  80847. tmat.invert();
  80848. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80849. lm.m[12] = vec.x;
  80850. lm.m[13] = vec.y;
  80851. lm.m[14] = vec.z;
  80852. }
  80853. this._markAsDirtyAndDecompose();
  80854. };
  80855. /**
  80856. * Set the absolute position of the bone (world space)
  80857. * @param position The position to set the bone
  80858. * @param mesh The mesh that this bone is attached to
  80859. */
  80860. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80861. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80862. };
  80863. /**
  80864. * Scale the bone on the x, y and z axes (in local space)
  80865. * @param x The amount to scale the bone on the x axis
  80866. * @param y The amount to scale the bone on the y axis
  80867. * @param z The amount to scale the bone on the z axis
  80868. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80869. */
  80870. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80871. if (scaleChildren === void 0) { scaleChildren = false; }
  80872. var locMat = this.getLocalMatrix();
  80873. // Apply new scaling on top of current local matrix
  80874. var scaleMat = Bone._tmpMats[0];
  80875. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80876. scaleMat.multiplyToRef(locMat, locMat);
  80877. // Invert scaling matrix and apply the inverse to all children
  80878. scaleMat.invert();
  80879. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80880. var child = _a[_i];
  80881. var cm = child.getLocalMatrix();
  80882. cm.multiplyToRef(scaleMat, cm);
  80883. cm.m[12] *= x;
  80884. cm.m[13] *= y;
  80885. cm.m[14] *= z;
  80886. child._markAsDirtyAndDecompose();
  80887. }
  80888. this._markAsDirtyAndDecompose();
  80889. if (scaleChildren) {
  80890. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80891. var child = _c[_b];
  80892. child.scale(x, y, z, scaleChildren);
  80893. }
  80894. }
  80895. };
  80896. /**
  80897. * Set the bone scaling in local space
  80898. * @param scale defines the scaling vector
  80899. */
  80900. Bone.prototype.setScale = function (scale) {
  80901. this._decompose();
  80902. this._localScaling.copyFrom(scale);
  80903. this._markAsDirtyAndCompose();
  80904. };
  80905. /**
  80906. * Gets the current scaling in local space
  80907. * @returns the current scaling vector
  80908. */
  80909. Bone.prototype.getScale = function () {
  80910. this._decompose();
  80911. return this._localScaling;
  80912. };
  80913. /**
  80914. * Gets the current scaling in local space and stores it in a target vector
  80915. * @param result defines the target vector
  80916. */
  80917. Bone.prototype.getScaleToRef = function (result) {
  80918. this._decompose();
  80919. result.copyFrom(this._localScaling);
  80920. };
  80921. /**
  80922. * Set the yaw, pitch, and roll of the bone in local or world space
  80923. * @param yaw The rotation of the bone on the y axis
  80924. * @param pitch The rotation of the bone on the x axis
  80925. * @param roll The rotation of the bone on the z axis
  80926. * @param space The space that the axes of rotation are in
  80927. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80928. */
  80929. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80931. if (space === BABYLON.Space.LOCAL) {
  80932. var quat = Bone._tmpQuat;
  80933. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80934. this.setRotationQuaternion(quat, space, mesh);
  80935. return;
  80936. }
  80937. var rotMatInv = Bone._tmpMats[0];
  80938. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80939. return;
  80940. }
  80941. var rotMat = Bone._tmpMats[1];
  80942. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80943. rotMatInv.multiplyToRef(rotMat, rotMat);
  80944. this._rotateWithMatrix(rotMat, space, mesh);
  80945. };
  80946. /**
  80947. * Add a rotation to the bone on an axis in local or world space
  80948. * @param axis The axis to rotate the bone on
  80949. * @param amount The amount to rotate the bone
  80950. * @param space The space that the axis is in
  80951. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80952. */
  80953. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80954. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80955. var rmat = Bone._tmpMats[0];
  80956. rmat.m[12] = 0;
  80957. rmat.m[13] = 0;
  80958. rmat.m[14] = 0;
  80959. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80960. this._rotateWithMatrix(rmat, space, mesh);
  80961. };
  80962. /**
  80963. * Set the rotation of the bone to a particular axis angle in local or world space
  80964. * @param axis The axis to rotate the bone on
  80965. * @param angle The angle that the bone should be rotated to
  80966. * @param space The space that the axis is in
  80967. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80968. */
  80969. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80971. if (space === BABYLON.Space.LOCAL) {
  80972. var quat = Bone._tmpQuat;
  80973. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80974. this.setRotationQuaternion(quat, space, mesh);
  80975. return;
  80976. }
  80977. var rotMatInv = Bone._tmpMats[0];
  80978. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80979. return;
  80980. }
  80981. var rotMat = Bone._tmpMats[1];
  80982. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80983. rotMatInv.multiplyToRef(rotMat, rotMat);
  80984. this._rotateWithMatrix(rotMat, space, mesh);
  80985. };
  80986. /**
  80987. * Set the euler rotation of the bone in local of world space
  80988. * @param rotation The euler rotation that the bone should be set to
  80989. * @param space The space that the rotation is in
  80990. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80991. */
  80992. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80994. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80995. };
  80996. /**
  80997. * Set the quaternion rotation of the bone in local of world space
  80998. * @param quat The quaternion rotation that the bone should be set to
  80999. * @param space The space that the rotation is in
  81000. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81001. */
  81002. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81004. if (space === BABYLON.Space.LOCAL) {
  81005. this._decompose();
  81006. this._localRotation.copyFrom(quat);
  81007. this._markAsDirtyAndCompose();
  81008. return;
  81009. }
  81010. var rotMatInv = Bone._tmpMats[0];
  81011. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81012. return;
  81013. }
  81014. var rotMat = Bone._tmpMats[1];
  81015. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81016. rotMatInv.multiplyToRef(rotMat, rotMat);
  81017. this._rotateWithMatrix(rotMat, space, mesh);
  81018. };
  81019. /**
  81020. * Set the rotation matrix of the bone in local of world space
  81021. * @param rotMat The rotation matrix that the bone should be set to
  81022. * @param space The space that the rotation is in
  81023. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81024. */
  81025. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81027. if (space === BABYLON.Space.LOCAL) {
  81028. var quat = Bone._tmpQuat;
  81029. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81030. this.setRotationQuaternion(quat, space, mesh);
  81031. return;
  81032. }
  81033. var rotMatInv = Bone._tmpMats[0];
  81034. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81035. return;
  81036. }
  81037. var rotMat2 = Bone._tmpMats[1];
  81038. rotMat2.copyFrom(rotMat);
  81039. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81040. this._rotateWithMatrix(rotMat2, space, mesh);
  81041. };
  81042. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81043. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81044. var lmat = this.getLocalMatrix();
  81045. var lx = lmat.m[12];
  81046. var ly = lmat.m[13];
  81047. var lz = lmat.m[14];
  81048. var parent = this.getParent();
  81049. var parentScale = Bone._tmpMats[3];
  81050. var parentScaleInv = Bone._tmpMats[4];
  81051. if (parent && space == BABYLON.Space.WORLD) {
  81052. if (mesh) {
  81053. parentScale.copyFrom(mesh.getWorldMatrix());
  81054. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81055. }
  81056. else {
  81057. parentScale.copyFrom(parent.getAbsoluteTransform());
  81058. }
  81059. parentScaleInv.copyFrom(parentScale);
  81060. parentScaleInv.invert();
  81061. lmat.multiplyToRef(parentScale, lmat);
  81062. lmat.multiplyToRef(rmat, lmat);
  81063. lmat.multiplyToRef(parentScaleInv, lmat);
  81064. }
  81065. else {
  81066. if (space == BABYLON.Space.WORLD && mesh) {
  81067. parentScale.copyFrom(mesh.getWorldMatrix());
  81068. parentScaleInv.copyFrom(parentScale);
  81069. parentScaleInv.invert();
  81070. lmat.multiplyToRef(parentScale, lmat);
  81071. lmat.multiplyToRef(rmat, lmat);
  81072. lmat.multiplyToRef(parentScaleInv, lmat);
  81073. }
  81074. else {
  81075. lmat.multiplyToRef(rmat, lmat);
  81076. }
  81077. }
  81078. lmat.m[12] = lx;
  81079. lmat.m[13] = ly;
  81080. lmat.m[14] = lz;
  81081. this.computeAbsoluteTransforms();
  81082. this._markAsDirtyAndDecompose();
  81083. };
  81084. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81085. var scaleMatrix = Bone._tmpMats[2];
  81086. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81087. if (mesh) {
  81088. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81089. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81090. }
  81091. rotMatInv.invert();
  81092. if (isNaN(rotMatInv.m[0])) {
  81093. // Matrix failed to invert.
  81094. // This can happen if scale is zero for example.
  81095. return false;
  81096. }
  81097. scaleMatrix.m[0] *= this._scalingDeterminant;
  81098. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81099. return true;
  81100. };
  81101. /**
  81102. * Get the position of the bone in local or world space
  81103. * @param space The space that the returned position is in
  81104. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81105. * @returns The position of the bone
  81106. */
  81107. Bone.prototype.getPosition = function (space, mesh) {
  81108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81109. if (mesh === void 0) { mesh = null; }
  81110. var pos = BABYLON.Vector3.Zero();
  81111. this.getPositionToRef(space, mesh, pos);
  81112. return pos;
  81113. };
  81114. /**
  81115. * Copy the position of the bone to a vector3 in local or world space
  81116. * @param space The space that the returned position is in
  81117. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81118. * @param result The vector3 to copy the position to
  81119. */
  81120. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81122. if (space == BABYLON.Space.LOCAL) {
  81123. var lm = this.getLocalMatrix();
  81124. result.x = lm.m[12];
  81125. result.y = lm.m[13];
  81126. result.z = lm.m[14];
  81127. }
  81128. else {
  81129. var wm = null;
  81130. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81131. if (mesh) {
  81132. wm = mesh.getWorldMatrix();
  81133. }
  81134. this._skeleton.computeAbsoluteTransforms();
  81135. var tmat = Bone._tmpMats[0];
  81136. if (mesh && wm) {
  81137. tmat.copyFrom(this.getAbsoluteTransform());
  81138. tmat.multiplyToRef(wm, tmat);
  81139. }
  81140. else {
  81141. tmat = this.getAbsoluteTransform();
  81142. }
  81143. result.x = tmat.m[12];
  81144. result.y = tmat.m[13];
  81145. result.z = tmat.m[14];
  81146. }
  81147. };
  81148. /**
  81149. * Get the absolute position of the bone (world space)
  81150. * @param mesh The mesh that this bone is attached to
  81151. * @returns The absolute position of the bone
  81152. */
  81153. Bone.prototype.getAbsolutePosition = function (mesh) {
  81154. if (mesh === void 0) { mesh = null; }
  81155. var pos = BABYLON.Vector3.Zero();
  81156. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81157. return pos;
  81158. };
  81159. /**
  81160. * Copy the absolute position of the bone (world space) to the result param
  81161. * @param mesh The mesh that this bone is attached to
  81162. * @param result The vector3 to copy the absolute position to
  81163. */
  81164. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81165. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81166. };
  81167. /**
  81168. * Compute the absolute transforms of this bone and its children
  81169. */
  81170. Bone.prototype.computeAbsoluteTransforms = function () {
  81171. this._compose();
  81172. if (this._parent) {
  81173. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81174. }
  81175. else {
  81176. this._absoluteTransform.copyFrom(this._localMatrix);
  81177. var poseMatrix = this._skeleton.getPoseMatrix();
  81178. if (poseMatrix) {
  81179. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81180. }
  81181. }
  81182. var children = this.children;
  81183. var len = children.length;
  81184. for (var i = 0; i < len; i++) {
  81185. children[i].computeAbsoluteTransforms();
  81186. }
  81187. };
  81188. /**
  81189. * Get the world direction from an axis that is in the local space of the bone
  81190. * @param localAxis The local direction that is used to compute the world direction
  81191. * @param mesh The mesh that this bone is attached to
  81192. * @returns The world direction
  81193. */
  81194. Bone.prototype.getDirection = function (localAxis, mesh) {
  81195. if (mesh === void 0) { mesh = null; }
  81196. var result = BABYLON.Vector3.Zero();
  81197. this.getDirectionToRef(localAxis, mesh, result);
  81198. return result;
  81199. };
  81200. /**
  81201. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81202. * @param localAxis The local direction that is used to compute the world direction
  81203. * @param mesh The mesh that this bone is attached to
  81204. * @param result The vector3 that the world direction will be copied to
  81205. */
  81206. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81207. if (mesh === void 0) { mesh = null; }
  81208. var wm = null;
  81209. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81210. if (mesh) {
  81211. wm = mesh.getWorldMatrix();
  81212. }
  81213. this._skeleton.computeAbsoluteTransforms();
  81214. var mat = Bone._tmpMats[0];
  81215. mat.copyFrom(this.getAbsoluteTransform());
  81216. if (mesh && wm) {
  81217. mat.multiplyToRef(wm, mat);
  81218. }
  81219. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81220. result.normalize();
  81221. };
  81222. /**
  81223. * Get the euler rotation of the bone in local or world space
  81224. * @param space The space that the rotation should be in
  81225. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81226. * @returns The euler rotation
  81227. */
  81228. Bone.prototype.getRotation = function (space, mesh) {
  81229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81230. if (mesh === void 0) { mesh = null; }
  81231. var result = BABYLON.Vector3.Zero();
  81232. this.getRotationToRef(space, mesh, result);
  81233. return result;
  81234. };
  81235. /**
  81236. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81237. * @param space The space that the rotation should be in
  81238. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81239. * @param result The vector3 that the rotation should be copied to
  81240. */
  81241. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81243. if (mesh === void 0) { mesh = null; }
  81244. var quat = Bone._tmpQuat;
  81245. this.getRotationQuaternionToRef(space, mesh, quat);
  81246. quat.toEulerAnglesToRef(result);
  81247. };
  81248. /**
  81249. * Get the quaternion rotation of the bone in either local or world space
  81250. * @param space The space that the rotation should be in
  81251. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81252. * @returns The quaternion rotation
  81253. */
  81254. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81256. if (mesh === void 0) { mesh = null; }
  81257. var result = BABYLON.Quaternion.Identity();
  81258. this.getRotationQuaternionToRef(space, mesh, result);
  81259. return result;
  81260. };
  81261. /**
  81262. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81263. * @param space The space that the rotation should be in
  81264. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81265. * @param result The quaternion that the rotation should be copied to
  81266. */
  81267. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81269. if (mesh === void 0) { mesh = null; }
  81270. if (space == BABYLON.Space.LOCAL) {
  81271. this._decompose();
  81272. result.copyFrom(this._localRotation);
  81273. }
  81274. else {
  81275. var mat = Bone._tmpMats[0];
  81276. var amat = this.getAbsoluteTransform();
  81277. if (mesh) {
  81278. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81279. }
  81280. else {
  81281. mat.copyFrom(amat);
  81282. }
  81283. mat.m[0] *= this._scalingDeterminant;
  81284. mat.m[1] *= this._scalingDeterminant;
  81285. mat.m[2] *= this._scalingDeterminant;
  81286. mat.decompose(undefined, result, undefined);
  81287. }
  81288. };
  81289. /**
  81290. * Get the rotation matrix of the bone in local or world space
  81291. * @param space The space that the rotation should be in
  81292. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81293. * @returns The rotation matrix
  81294. */
  81295. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81297. var result = BABYLON.Matrix.Identity();
  81298. this.getRotationMatrixToRef(space, mesh, result);
  81299. return result;
  81300. };
  81301. /**
  81302. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81303. * @param space The space that the rotation should be in
  81304. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81305. * @param result The quaternion that the rotation should be copied to
  81306. */
  81307. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81309. if (space == BABYLON.Space.LOCAL) {
  81310. this.getLocalMatrix().getRotationMatrixToRef(result);
  81311. }
  81312. else {
  81313. var mat = Bone._tmpMats[0];
  81314. var amat = this.getAbsoluteTransform();
  81315. if (mesh) {
  81316. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81317. }
  81318. else {
  81319. mat.copyFrom(amat);
  81320. }
  81321. mat.m[0] *= this._scalingDeterminant;
  81322. mat.m[1] *= this._scalingDeterminant;
  81323. mat.m[2] *= this._scalingDeterminant;
  81324. mat.getRotationMatrixToRef(result);
  81325. }
  81326. };
  81327. /**
  81328. * Get the world position of a point that is in the local space of the bone
  81329. * @param position The local position
  81330. * @param mesh The mesh that this bone is attached to
  81331. * @returns The world position
  81332. */
  81333. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81334. if (mesh === void 0) { mesh = null; }
  81335. var result = BABYLON.Vector3.Zero();
  81336. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81337. return result;
  81338. };
  81339. /**
  81340. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81341. * @param position The local position
  81342. * @param mesh The mesh that this bone is attached to
  81343. * @param result The vector3 that the world position should be copied to
  81344. */
  81345. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81346. if (mesh === void 0) { mesh = null; }
  81347. var wm = null;
  81348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81349. if (mesh) {
  81350. wm = mesh.getWorldMatrix();
  81351. }
  81352. this._skeleton.computeAbsoluteTransforms();
  81353. var tmat = Bone._tmpMats[0];
  81354. if (mesh && wm) {
  81355. tmat.copyFrom(this.getAbsoluteTransform());
  81356. tmat.multiplyToRef(wm, tmat);
  81357. }
  81358. else {
  81359. tmat = this.getAbsoluteTransform();
  81360. }
  81361. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81362. };
  81363. /**
  81364. * Get the local position of a point that is in world space
  81365. * @param position The world position
  81366. * @param mesh The mesh that this bone is attached to
  81367. * @returns The local position
  81368. */
  81369. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81370. if (mesh === void 0) { mesh = null; }
  81371. var result = BABYLON.Vector3.Zero();
  81372. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81373. return result;
  81374. };
  81375. /**
  81376. * Get the local position of a point that is in world space and copy it to the result param
  81377. * @param position The world position
  81378. * @param mesh The mesh that this bone is attached to
  81379. * @param result The vector3 that the local position should be copied to
  81380. */
  81381. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81382. if (mesh === void 0) { mesh = null; }
  81383. var wm = null;
  81384. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81385. if (mesh) {
  81386. wm = mesh.getWorldMatrix();
  81387. }
  81388. this._skeleton.computeAbsoluteTransforms();
  81389. var tmat = Bone._tmpMats[0];
  81390. tmat.copyFrom(this.getAbsoluteTransform());
  81391. if (mesh && wm) {
  81392. tmat.multiplyToRef(wm, tmat);
  81393. }
  81394. tmat.invert();
  81395. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81396. };
  81397. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81398. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81399. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81400. return Bone;
  81401. }(BABYLON.Node));
  81402. BABYLON.Bone = Bone;
  81403. })(BABYLON || (BABYLON = {}));
  81404. //# sourceMappingURL=babylon.bone.js.map
  81405. var BABYLON;
  81406. (function (BABYLON) {
  81407. /**
  81408. * Class used to apply inverse kinematics to bones
  81409. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81410. */
  81411. var BoneIKController = /** @class */ (function () {
  81412. /**
  81413. * Creates a new BoneIKController
  81414. * @param mesh defines the mesh to control
  81415. * @param bone defines the bone to control
  81416. * @param options defines options to set up the controller
  81417. */
  81418. function BoneIKController(mesh, bone, options) {
  81419. /**
  81420. * Gets or sets the target position
  81421. */
  81422. this.targetPosition = BABYLON.Vector3.Zero();
  81423. /**
  81424. * Gets or sets the pole target position
  81425. */
  81426. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81427. /**
  81428. * Gets or sets the pole target local offset
  81429. */
  81430. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81431. /**
  81432. * Gets or sets the pole angle
  81433. */
  81434. this.poleAngle = 0;
  81435. /**
  81436. * 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)
  81437. */
  81438. this.slerpAmount = 1;
  81439. this._bone1Quat = BABYLON.Quaternion.Identity();
  81440. this._bone1Mat = BABYLON.Matrix.Identity();
  81441. this._bone2Ang = Math.PI;
  81442. this._maxAngle = Math.PI;
  81443. this._rightHandedSystem = false;
  81444. this._bendAxis = BABYLON.Vector3.Right();
  81445. this._slerping = false;
  81446. this._adjustRoll = 0;
  81447. this._bone2 = bone;
  81448. this._bone1 = bone.getParent();
  81449. if (!this._bone1) {
  81450. return;
  81451. }
  81452. this.mesh = mesh;
  81453. var bonePos = bone.getPosition();
  81454. if (bone.getAbsoluteTransform().determinant() > 0) {
  81455. this._rightHandedSystem = true;
  81456. this._bendAxis.x = 0;
  81457. this._bendAxis.y = 0;
  81458. this._bendAxis.z = -1;
  81459. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81460. this._adjustRoll = Math.PI * .5;
  81461. this._bendAxis.z = 1;
  81462. }
  81463. }
  81464. if (this._bone1.length) {
  81465. var boneScale1 = this._bone1.getScale();
  81466. var boneScale2 = this._bone2.getScale();
  81467. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81468. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81469. }
  81470. else if (this._bone1.children[0]) {
  81471. mesh.computeWorldMatrix(true);
  81472. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81473. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81474. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81475. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81476. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81477. }
  81478. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81479. this.maxAngle = Math.PI;
  81480. if (options) {
  81481. if (options.targetMesh) {
  81482. this.targetMesh = options.targetMesh;
  81483. this.targetMesh.computeWorldMatrix(true);
  81484. }
  81485. if (options.poleTargetMesh) {
  81486. this.poleTargetMesh = options.poleTargetMesh;
  81487. this.poleTargetMesh.computeWorldMatrix(true);
  81488. }
  81489. else if (options.poleTargetBone) {
  81490. this.poleTargetBone = options.poleTargetBone;
  81491. }
  81492. else if (this._bone1.getParent()) {
  81493. this.poleTargetBone = this._bone1.getParent();
  81494. }
  81495. if (options.poleTargetLocalOffset) {
  81496. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81497. }
  81498. if (options.poleAngle) {
  81499. this.poleAngle = options.poleAngle;
  81500. }
  81501. if (options.bendAxis) {
  81502. this._bendAxis.copyFrom(options.bendAxis);
  81503. }
  81504. if (options.maxAngle) {
  81505. this.maxAngle = options.maxAngle;
  81506. }
  81507. if (options.slerpAmount) {
  81508. this.slerpAmount = options.slerpAmount;
  81509. }
  81510. }
  81511. }
  81512. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81513. /**
  81514. * Gets or sets maximum allowed angle
  81515. */
  81516. get: function () {
  81517. return this._maxAngle;
  81518. },
  81519. set: function (value) {
  81520. this._setMaxAngle(value);
  81521. },
  81522. enumerable: true,
  81523. configurable: true
  81524. });
  81525. BoneIKController.prototype._setMaxAngle = function (ang) {
  81526. if (ang < 0) {
  81527. ang = 0;
  81528. }
  81529. if (ang > Math.PI || ang == undefined) {
  81530. ang = Math.PI;
  81531. }
  81532. this._maxAngle = ang;
  81533. var a = this._bone1Length;
  81534. var b = this._bone2Length;
  81535. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81536. };
  81537. /**
  81538. * Force the controller to update the bones
  81539. */
  81540. BoneIKController.prototype.update = function () {
  81541. var bone1 = this._bone1;
  81542. if (!bone1) {
  81543. return;
  81544. }
  81545. var target = this.targetPosition;
  81546. var poleTarget = this.poleTargetPosition;
  81547. var mat1 = BoneIKController._tmpMats[0];
  81548. var mat2 = BoneIKController._tmpMats[1];
  81549. if (this.targetMesh) {
  81550. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81551. }
  81552. if (this.poleTargetBone) {
  81553. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81554. }
  81555. else if (this.poleTargetMesh) {
  81556. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81557. }
  81558. var bonePos = BoneIKController._tmpVecs[0];
  81559. var zaxis = BoneIKController._tmpVecs[1];
  81560. var xaxis = BoneIKController._tmpVecs[2];
  81561. var yaxis = BoneIKController._tmpVecs[3];
  81562. var upAxis = BoneIKController._tmpVecs[4];
  81563. var _tmpQuat = BoneIKController._tmpQuat;
  81564. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81565. poleTarget.subtractToRef(bonePos, upAxis);
  81566. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81567. upAxis.y = 1;
  81568. }
  81569. else {
  81570. upAxis.normalize();
  81571. }
  81572. target.subtractToRef(bonePos, yaxis);
  81573. yaxis.normalize();
  81574. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81575. zaxis.normalize();
  81576. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81577. xaxis.normalize();
  81578. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81579. var a = this._bone1Length;
  81580. var b = this._bone2Length;
  81581. var c = BABYLON.Vector3.Distance(bonePos, target);
  81582. if (this._maxReach > 0) {
  81583. c = Math.min(this._maxReach, c);
  81584. }
  81585. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81586. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81587. if (acosa > 1) {
  81588. acosa = 1;
  81589. }
  81590. if (acosb > 1) {
  81591. acosb = 1;
  81592. }
  81593. if (acosa < -1) {
  81594. acosa = -1;
  81595. }
  81596. if (acosb < -1) {
  81597. acosb = -1;
  81598. }
  81599. var angA = Math.acos(acosa);
  81600. var angB = Math.acos(acosb);
  81601. var angC = -angA - angB;
  81602. if (this._rightHandedSystem) {
  81603. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81604. mat2.multiplyToRef(mat1, mat1);
  81605. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81606. mat2.multiplyToRef(mat1, mat1);
  81607. }
  81608. else {
  81609. var _tmpVec = BoneIKController._tmpVecs[5];
  81610. _tmpVec.copyFrom(this._bendAxis);
  81611. _tmpVec.x *= -1;
  81612. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  81613. mat2.multiplyToRef(mat1, mat1);
  81614. }
  81615. if (this.poleAngle) {
  81616. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  81617. mat1.multiplyToRef(mat2, mat1);
  81618. }
  81619. if (this._bone1) {
  81620. if (this.slerpAmount < 1) {
  81621. if (!this._slerping) {
  81622. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  81623. }
  81624. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  81625. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  81626. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  81627. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  81628. this._slerping = true;
  81629. }
  81630. else {
  81631. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  81632. this._bone1Mat.copyFrom(mat1);
  81633. this._slerping = false;
  81634. }
  81635. }
  81636. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  81637. this._bone2Ang = angC;
  81638. };
  81639. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81640. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  81641. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81642. return BoneIKController;
  81643. }());
  81644. BABYLON.BoneIKController = BoneIKController;
  81645. })(BABYLON || (BABYLON = {}));
  81646. //# sourceMappingURL=babylon.boneIKController.js.map
  81647. var BABYLON;
  81648. (function (BABYLON) {
  81649. /**
  81650. * Class used to make a bone look toward a point in space
  81651. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  81652. */
  81653. var BoneLookController = /** @class */ (function () {
  81654. /**
  81655. * Create a BoneLookController
  81656. * @param mesh the mesh that the bone belongs to
  81657. * @param bone the bone that will be looking to the target
  81658. * @param target the target Vector3 to look at
  81659. * @param settings optional settings:
  81660. * * maxYaw: the maximum angle the bone will yaw to
  81661. * * minYaw: the minimum angle the bone will yaw to
  81662. * * maxPitch: the maximum angle the bone will pitch to
  81663. * * minPitch: the minimum angle the bone will yaw to
  81664. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  81665. * * upAxis: the up axis of the coordinate system
  81666. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  81667. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  81668. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  81669. * * adjustYaw: used to make an adjustment to the yaw of the bone
  81670. * * adjustPitch: used to make an adjustment to the pitch of the bone
  81671. * * adjustRoll: used to make an adjustment to the roll of the bone
  81672. **/
  81673. function BoneLookController(mesh, bone, target, options) {
  81674. /**
  81675. * The up axis of the coordinate system that is used when the bone is rotated
  81676. */
  81677. this.upAxis = BABYLON.Vector3.Up();
  81678. /**
  81679. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  81680. */
  81681. this.upAxisSpace = BABYLON.Space.LOCAL;
  81682. /**
  81683. * Used to make an adjustment to the yaw of the bone
  81684. */
  81685. this.adjustYaw = 0;
  81686. /**
  81687. * Used to make an adjustment to the pitch of the bone
  81688. */
  81689. this.adjustPitch = 0;
  81690. /**
  81691. * Used to make an adjustment to the roll of the bone
  81692. */
  81693. this.adjustRoll = 0;
  81694. /**
  81695. * 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)
  81696. */
  81697. this.slerpAmount = 1;
  81698. this._boneQuat = BABYLON.Quaternion.Identity();
  81699. this._slerping = false;
  81700. this._firstFrameSkipped = false;
  81701. this._fowardAxis = BABYLON.Vector3.Forward();
  81702. this.mesh = mesh;
  81703. this.bone = bone;
  81704. this.target = target;
  81705. if (options) {
  81706. if (options.adjustYaw) {
  81707. this.adjustYaw = options.adjustYaw;
  81708. }
  81709. if (options.adjustPitch) {
  81710. this.adjustPitch = options.adjustPitch;
  81711. }
  81712. if (options.adjustRoll) {
  81713. this.adjustRoll = options.adjustRoll;
  81714. }
  81715. if (options.maxYaw != null) {
  81716. this.maxYaw = options.maxYaw;
  81717. }
  81718. else {
  81719. this.maxYaw = Math.PI;
  81720. }
  81721. if (options.minYaw != null) {
  81722. this.minYaw = options.minYaw;
  81723. }
  81724. else {
  81725. this.minYaw = -Math.PI;
  81726. }
  81727. if (options.maxPitch != null) {
  81728. this.maxPitch = options.maxPitch;
  81729. }
  81730. else {
  81731. this.maxPitch = Math.PI;
  81732. }
  81733. if (options.minPitch != null) {
  81734. this.minPitch = options.minPitch;
  81735. }
  81736. else {
  81737. this.minPitch = -Math.PI;
  81738. }
  81739. if (options.slerpAmount != null) {
  81740. this.slerpAmount = options.slerpAmount;
  81741. }
  81742. if (options.upAxis != null) {
  81743. this.upAxis = options.upAxis;
  81744. }
  81745. if (options.upAxisSpace != null) {
  81746. this.upAxisSpace = options.upAxisSpace;
  81747. }
  81748. if (options.yawAxis != null || options.pitchAxis != null) {
  81749. var newYawAxis = BABYLON.Axis.Y;
  81750. var newPitchAxis = BABYLON.Axis.X;
  81751. if (options.yawAxis != null) {
  81752. newYawAxis = options.yawAxis.clone();
  81753. newYawAxis.normalize();
  81754. }
  81755. if (options.pitchAxis != null) {
  81756. newPitchAxis = options.pitchAxis.clone();
  81757. newPitchAxis.normalize();
  81758. }
  81759. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81760. this._transformYawPitch = BABYLON.Matrix.Identity();
  81761. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81762. this._transformYawPitchInv = this._transformYawPitch.clone();
  81763. this._transformYawPitch.invert();
  81764. }
  81765. }
  81766. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81767. this.upAxisSpace = BABYLON.Space.LOCAL;
  81768. }
  81769. }
  81770. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81771. /**
  81772. * Gets or sets the minimum yaw angle that the bone can look to
  81773. */
  81774. get: function () {
  81775. return this._minYaw;
  81776. },
  81777. set: function (value) {
  81778. this._minYaw = value;
  81779. this._minYawSin = Math.sin(value);
  81780. this._minYawCos = Math.cos(value);
  81781. if (this._maxYaw != null) {
  81782. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81783. this._yawRange = this._maxYaw - this._minYaw;
  81784. }
  81785. },
  81786. enumerable: true,
  81787. configurable: true
  81788. });
  81789. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81790. /**
  81791. * Gets or sets the maximum yaw angle that the bone can look to
  81792. */
  81793. get: function () {
  81794. return this._maxYaw;
  81795. },
  81796. set: function (value) {
  81797. this._maxYaw = value;
  81798. this._maxYawSin = Math.sin(value);
  81799. this._maxYawCos = Math.cos(value);
  81800. if (this._minYaw != null) {
  81801. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81802. this._yawRange = this._maxYaw - this._minYaw;
  81803. }
  81804. },
  81805. enumerable: true,
  81806. configurable: true
  81807. });
  81808. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81809. /**
  81810. * Gets or sets the minimum pitch angle that the bone can look to
  81811. */
  81812. get: function () {
  81813. return this._minPitch;
  81814. },
  81815. set: function (value) {
  81816. this._minPitch = value;
  81817. this._minPitchTan = Math.tan(value);
  81818. },
  81819. enumerable: true,
  81820. configurable: true
  81821. });
  81822. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81823. /**
  81824. * Gets or sets the maximum pitch angle that the bone can look to
  81825. */
  81826. get: function () {
  81827. return this._maxPitch;
  81828. },
  81829. set: function (value) {
  81830. this._maxPitch = value;
  81831. this._maxPitchTan = Math.tan(value);
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. /**
  81837. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81838. */
  81839. BoneLookController.prototype.update = function () {
  81840. //skip the first frame when slerping so that the mesh rotation is correct
  81841. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81842. this._firstFrameSkipped = true;
  81843. return;
  81844. }
  81845. var bone = this.bone;
  81846. var bonePos = BoneLookController._tmpVecs[0];
  81847. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81848. var target = this.target;
  81849. var _tmpMat1 = BoneLookController._tmpMats[0];
  81850. var _tmpMat2 = BoneLookController._tmpMats[1];
  81851. var mesh = this.mesh;
  81852. var parentBone = bone.getParent();
  81853. var upAxis = BoneLookController._tmpVecs[1];
  81854. upAxis.copyFrom(this.upAxis);
  81855. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81856. if (this._transformYawPitch) {
  81857. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81858. }
  81859. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81860. }
  81861. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81862. mesh.getDirectionToRef(upAxis, upAxis);
  81863. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81864. upAxis.normalize();
  81865. }
  81866. }
  81867. var checkYaw = false;
  81868. var checkPitch = false;
  81869. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81870. checkYaw = true;
  81871. }
  81872. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81873. checkPitch = true;
  81874. }
  81875. if (checkYaw || checkPitch) {
  81876. var spaceMat = BoneLookController._tmpMats[2];
  81877. var spaceMatInv = BoneLookController._tmpMats[3];
  81878. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81879. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81880. }
  81881. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81882. spaceMat.copyFrom(mesh.getWorldMatrix());
  81883. }
  81884. else {
  81885. var forwardAxis = BoneLookController._tmpVecs[2];
  81886. forwardAxis.copyFrom(this._fowardAxis);
  81887. if (this._transformYawPitch) {
  81888. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81889. }
  81890. if (parentBone) {
  81891. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81892. }
  81893. else {
  81894. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81895. }
  81896. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81897. rightAxis.normalize();
  81898. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81899. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81900. }
  81901. spaceMat.invertToRef(spaceMatInv);
  81902. var xzlen = null;
  81903. if (checkPitch) {
  81904. var localTarget = BoneLookController._tmpVecs[3];
  81905. target.subtractToRef(bonePos, localTarget);
  81906. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81907. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81908. var pitch = Math.atan2(localTarget.y, xzlen);
  81909. var newPitch = pitch;
  81910. if (pitch > this._maxPitch) {
  81911. localTarget.y = this._maxPitchTan * xzlen;
  81912. newPitch = this._maxPitch;
  81913. }
  81914. else if (pitch < this._minPitch) {
  81915. localTarget.y = this._minPitchTan * xzlen;
  81916. newPitch = this._minPitch;
  81917. }
  81918. if (pitch != newPitch) {
  81919. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81920. localTarget.addInPlace(bonePos);
  81921. target = localTarget;
  81922. }
  81923. }
  81924. if (checkYaw) {
  81925. var localTarget = BoneLookController._tmpVecs[4];
  81926. target.subtractToRef(bonePos, localTarget);
  81927. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81928. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81929. var newYaw = yaw;
  81930. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81931. if (xzlen == null) {
  81932. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81933. }
  81934. if (this._yawRange > Math.PI) {
  81935. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81936. localTarget.z = this._maxYawCos * xzlen;
  81937. localTarget.x = this._maxYawSin * xzlen;
  81938. newYaw = this._maxYaw;
  81939. }
  81940. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81941. localTarget.z = this._minYawCos * xzlen;
  81942. localTarget.x = this._minYawSin * xzlen;
  81943. newYaw = this._minYaw;
  81944. }
  81945. }
  81946. else {
  81947. if (yaw > this._maxYaw) {
  81948. localTarget.z = this._maxYawCos * xzlen;
  81949. localTarget.x = this._maxYawSin * xzlen;
  81950. newYaw = this._maxYaw;
  81951. }
  81952. else if (yaw < this._minYaw) {
  81953. localTarget.z = this._minYawCos * xzlen;
  81954. localTarget.x = this._minYawSin * xzlen;
  81955. newYaw = this._minYaw;
  81956. }
  81957. }
  81958. }
  81959. if (this._slerping && this._yawRange > Math.PI) {
  81960. //are we going to be crossing into the min/max region?
  81961. var boneFwd = BoneLookController._tmpVecs[8];
  81962. boneFwd.copyFrom(BABYLON.Axis.Z);
  81963. if (this._transformYawPitch) {
  81964. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81965. }
  81966. var boneRotMat = BoneLookController._tmpMats[4];
  81967. this._boneQuat.toRotationMatrix(boneRotMat);
  81968. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81969. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81970. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81971. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81972. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81973. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81974. if (angBtwTar > angBtwMidYaw) {
  81975. if (xzlen == null) {
  81976. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81977. }
  81978. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81979. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81980. if (angBtwMin < angBtwMax) {
  81981. newYaw = boneYaw + Math.PI * .75;
  81982. localTarget.z = Math.cos(newYaw) * xzlen;
  81983. localTarget.x = Math.sin(newYaw) * xzlen;
  81984. }
  81985. else {
  81986. newYaw = boneYaw - Math.PI * .75;
  81987. localTarget.z = Math.cos(newYaw) * xzlen;
  81988. localTarget.x = Math.sin(newYaw) * xzlen;
  81989. }
  81990. }
  81991. }
  81992. if (yaw != newYaw) {
  81993. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81994. localTarget.addInPlace(bonePos);
  81995. target = localTarget;
  81996. }
  81997. }
  81998. }
  81999. var zaxis = BoneLookController._tmpVecs[5];
  82000. var xaxis = BoneLookController._tmpVecs[6];
  82001. var yaxis = BoneLookController._tmpVecs[7];
  82002. var _tmpQuat = BoneLookController._tmpQuat;
  82003. target.subtractToRef(bonePos, zaxis);
  82004. zaxis.normalize();
  82005. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82006. xaxis.normalize();
  82007. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82008. yaxis.normalize();
  82009. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82010. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82011. return;
  82012. }
  82013. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82014. return;
  82015. }
  82016. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82017. return;
  82018. }
  82019. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82020. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82021. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82022. }
  82023. if (this.slerpAmount < 1) {
  82024. if (!this._slerping) {
  82025. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82026. }
  82027. if (this._transformYawPitch) {
  82028. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82029. }
  82030. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82031. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82032. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82033. this._slerping = true;
  82034. }
  82035. else {
  82036. if (this._transformYawPitch) {
  82037. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82038. }
  82039. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82040. this._slerping = false;
  82041. }
  82042. };
  82043. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82044. var angDiff = ang2 - ang1;
  82045. angDiff %= Math.PI * 2;
  82046. if (angDiff > Math.PI) {
  82047. angDiff -= Math.PI * 2;
  82048. }
  82049. else if (angDiff < -Math.PI) {
  82050. angDiff += Math.PI * 2;
  82051. }
  82052. return angDiff;
  82053. };
  82054. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82055. ang1 %= (2 * Math.PI);
  82056. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82057. ang2 %= (2 * Math.PI);
  82058. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82059. var ab = 0;
  82060. if (ang1 < ang2) {
  82061. ab = ang2 - ang1;
  82062. }
  82063. else {
  82064. ab = ang1 - ang2;
  82065. }
  82066. if (ab > Math.PI) {
  82067. ab = Math.PI * 2 - ab;
  82068. }
  82069. return ab;
  82070. };
  82071. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82072. ang %= (2 * Math.PI);
  82073. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82074. ang1 %= (2 * Math.PI);
  82075. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82076. ang2 %= (2 * Math.PI);
  82077. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82078. if (ang1 < ang2) {
  82079. if (ang > ang1 && ang < ang2) {
  82080. return true;
  82081. }
  82082. }
  82083. else {
  82084. if (ang > ang2 && ang < ang1) {
  82085. return true;
  82086. }
  82087. }
  82088. return false;
  82089. };
  82090. 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()];
  82091. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82092. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82093. return BoneLookController;
  82094. }());
  82095. BABYLON.BoneLookController = BoneLookController;
  82096. })(BABYLON || (BABYLON = {}));
  82097. //# sourceMappingURL=babylon.boneLookController.js.map
  82098. var BABYLON;
  82099. (function (BABYLON) {
  82100. /**
  82101. * Class used to handle skinning animations
  82102. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82103. */
  82104. var Skeleton = /** @class */ (function () {
  82105. /**
  82106. * Creates a new skeleton
  82107. * @param name defines the skeleton name
  82108. * @param id defines the skeleton Id
  82109. * @param scene defines the hosting scene
  82110. */
  82111. function Skeleton(
  82112. /** defines the skeleton name */
  82113. name,
  82114. /** defines the skeleton Id */
  82115. id, scene) {
  82116. this.name = name;
  82117. this.id = id;
  82118. /**
  82119. * Gets the list of child bones
  82120. */
  82121. this.bones = new Array();
  82122. /**
  82123. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82124. */
  82125. this.needInitialSkinMatrix = false;
  82126. this._isDirty = true;
  82127. this._meshesWithPoseMatrix = new Array();
  82128. this._identity = BABYLON.Matrix.Identity();
  82129. this._ranges = {};
  82130. this._lastAbsoluteTransformsUpdateId = -1;
  82131. /**
  82132. * Specifies if the skeleton should be serialized
  82133. */
  82134. this.doNotSerialize = false;
  82135. this._animationPropertiesOverride = null;
  82136. // Events
  82137. /**
  82138. * An observable triggered before computing the skeleton's matrices
  82139. */
  82140. this.onBeforeComputeObservable = new BABYLON.Observable();
  82141. this.bones = [];
  82142. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82143. scene.skeletons.push(this);
  82144. //make sure it will recalculate the matrix next time prepare is called.
  82145. this._isDirty = true;
  82146. }
  82147. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82148. /**
  82149. * Gets or sets the animation properties override
  82150. */
  82151. get: function () {
  82152. if (!this._animationPropertiesOverride) {
  82153. return this._scene.animationPropertiesOverride;
  82154. }
  82155. return this._animationPropertiesOverride;
  82156. },
  82157. set: function (value) {
  82158. this._animationPropertiesOverride = value;
  82159. },
  82160. enumerable: true,
  82161. configurable: true
  82162. });
  82163. // Members
  82164. /**
  82165. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82166. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82167. * @returns a Float32Array containing matrices data
  82168. */
  82169. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82170. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82171. return mesh._bonesTransformMatrices;
  82172. }
  82173. if (!this._transformMatrices) {
  82174. this.prepare();
  82175. }
  82176. return this._transformMatrices;
  82177. };
  82178. /**
  82179. * Gets the current hosting scene
  82180. * @returns a scene object
  82181. */
  82182. Skeleton.prototype.getScene = function () {
  82183. return this._scene;
  82184. };
  82185. // Methods
  82186. /**
  82187. * Gets a string representing the current skeleton data
  82188. * @param fullDetails defines a boolean indicating if we want a verbose version
  82189. * @returns a string representing the current skeleton data
  82190. */
  82191. Skeleton.prototype.toString = function (fullDetails) {
  82192. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82193. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82194. if (fullDetails) {
  82195. ret += ", Ranges: {";
  82196. var first = true;
  82197. for (var name_1 in this._ranges) {
  82198. if (first) {
  82199. ret += ", ";
  82200. first = false;
  82201. }
  82202. ret += name_1;
  82203. }
  82204. ret += "}";
  82205. }
  82206. return ret;
  82207. };
  82208. /**
  82209. * Get bone's index searching by name
  82210. * @param name defines bone's name to search for
  82211. * @return the indice of the bone. Returns -1 if not found
  82212. */
  82213. Skeleton.prototype.getBoneIndexByName = function (name) {
  82214. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82215. if (this.bones[boneIndex].name === name) {
  82216. return boneIndex;
  82217. }
  82218. }
  82219. return -1;
  82220. };
  82221. /**
  82222. * Creater a new animation range
  82223. * @param name defines the name of the range
  82224. * @param from defines the start key
  82225. * @param to defines the end key
  82226. */
  82227. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82228. // check name not already in use
  82229. if (!this._ranges[name]) {
  82230. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82231. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82232. if (this.bones[i].animations[0]) {
  82233. this.bones[i].animations[0].createRange(name, from, to);
  82234. }
  82235. }
  82236. }
  82237. };
  82238. /**
  82239. * Delete a specific animation range
  82240. * @param name defines the name of the range
  82241. * @param deleteFrames defines if frames must be removed as well
  82242. */
  82243. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82244. if (deleteFrames === void 0) { deleteFrames = true; }
  82245. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82246. if (this.bones[i].animations[0]) {
  82247. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82248. }
  82249. }
  82250. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82251. };
  82252. /**
  82253. * Gets a specific animation range
  82254. * @param name defines the name of the range to look for
  82255. * @returns the requested animation range or null if not found
  82256. */
  82257. Skeleton.prototype.getAnimationRange = function (name) {
  82258. return this._ranges[name];
  82259. };
  82260. /**
  82261. * Gets the list of all animation ranges defined on this skeleton
  82262. * @returns an array
  82263. */
  82264. Skeleton.prototype.getAnimationRanges = function () {
  82265. var animationRanges = [];
  82266. var name;
  82267. var i = 0;
  82268. for (name in this._ranges) {
  82269. animationRanges[i] = this._ranges[name];
  82270. i++;
  82271. }
  82272. return animationRanges;
  82273. };
  82274. /**
  82275. * Copy animation range from a source skeleton.
  82276. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82277. * @param source defines the source skeleton
  82278. * @param name defines the name of the range to copy
  82279. * @param rescaleAsRequired defines if rescaling must be applied if required
  82280. * @returns true if operation was successful
  82281. */
  82282. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82283. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82284. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82285. return false;
  82286. }
  82287. var ret = true;
  82288. var frameOffset = this._getHighestAnimationFrame() + 1;
  82289. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82290. var boneDict = {};
  82291. var sourceBones = source.bones;
  82292. var nBones;
  82293. var i;
  82294. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82295. boneDict[sourceBones[i].name] = sourceBones[i];
  82296. }
  82297. if (this.bones.length !== sourceBones.length) {
  82298. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82299. ret = false;
  82300. }
  82301. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82302. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82303. var boneName = this.bones[i].name;
  82304. var sourceBone = boneDict[boneName];
  82305. if (sourceBone) {
  82306. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82307. }
  82308. else {
  82309. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82310. ret = false;
  82311. }
  82312. }
  82313. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82314. var range = source.getAnimationRange(name);
  82315. if (range) {
  82316. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82317. }
  82318. return ret;
  82319. };
  82320. /**
  82321. * Forces the skeleton to go to rest pose
  82322. */
  82323. Skeleton.prototype.returnToRest = function () {
  82324. for (var index = 0; index < this.bones.length; index++) {
  82325. this.bones[index].returnToRest();
  82326. }
  82327. };
  82328. Skeleton.prototype._getHighestAnimationFrame = function () {
  82329. var ret = 0;
  82330. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82331. if (this.bones[i].animations[0]) {
  82332. var highest = this.bones[i].animations[0].getHighestFrame();
  82333. if (ret < highest) {
  82334. ret = highest;
  82335. }
  82336. }
  82337. }
  82338. return ret;
  82339. };
  82340. /**
  82341. * Begin a specific animation range
  82342. * @param name defines the name of the range to start
  82343. * @param loop defines if looping must be turned on (false by default)
  82344. * @param speedRatio defines the speed ratio to apply (1 by default)
  82345. * @param onAnimationEnd defines a callback which will be called when animation will end
  82346. * @returns a new animatable
  82347. */
  82348. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82349. var range = this.getAnimationRange(name);
  82350. if (!range) {
  82351. return null;
  82352. }
  82353. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82354. };
  82355. /** @hidden */
  82356. Skeleton.prototype._markAsDirty = function () {
  82357. this._isDirty = true;
  82358. };
  82359. /** @hidden */
  82360. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82361. this._meshesWithPoseMatrix.push(mesh);
  82362. };
  82363. /** @hidden */
  82364. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82365. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82366. if (index > -1) {
  82367. this._meshesWithPoseMatrix.splice(index, 1);
  82368. }
  82369. };
  82370. /** @hidden */
  82371. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82372. this.onBeforeComputeObservable.notifyObservers(this);
  82373. for (var index = 0; index < this.bones.length; index++) {
  82374. var bone = this.bones[index];
  82375. var parentBone = bone.getParent();
  82376. if (parentBone) {
  82377. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82378. }
  82379. else {
  82380. if (initialSkinMatrix) {
  82381. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82382. }
  82383. else {
  82384. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82385. }
  82386. }
  82387. if (bone._index !== -1) {
  82388. var mappedIndex = bone._index === null ? index : bone._index;
  82389. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82390. }
  82391. }
  82392. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82393. };
  82394. /**
  82395. * Build all resources required to render a skeleton
  82396. */
  82397. Skeleton.prototype.prepare = function () {
  82398. if (!this._isDirty) {
  82399. return;
  82400. }
  82401. if (this.needInitialSkinMatrix) {
  82402. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82403. var mesh = this._meshesWithPoseMatrix[index];
  82404. var poseMatrix = mesh.getPoseMatrix();
  82405. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82406. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82407. }
  82408. if (this._synchronizedWithMesh !== mesh) {
  82409. this._synchronizedWithMesh = mesh;
  82410. // Prepare bones
  82411. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82412. var bone = this.bones[boneIndex];
  82413. if (!bone.getParent()) {
  82414. var matrix = bone.getBaseMatrix();
  82415. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82416. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82417. }
  82418. }
  82419. }
  82420. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82421. }
  82422. }
  82423. else {
  82424. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82425. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82426. }
  82427. this._computeTransformMatrices(this._transformMatrices, null);
  82428. }
  82429. this._isDirty = false;
  82430. this._scene._activeBones.addCount(this.bones.length, false);
  82431. };
  82432. /**
  82433. * Gets the list of animatables currently running for this skeleton
  82434. * @returns an array of animatables
  82435. */
  82436. Skeleton.prototype.getAnimatables = function () {
  82437. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82438. this._animatables = [];
  82439. for (var index = 0; index < this.bones.length; index++) {
  82440. this._animatables.push(this.bones[index]);
  82441. }
  82442. }
  82443. return this._animatables;
  82444. };
  82445. /**
  82446. * Clone the current skeleton
  82447. * @param name defines the name of the new skeleton
  82448. * @param id defines the id of the enw skeleton
  82449. * @returns the new skeleton
  82450. */
  82451. Skeleton.prototype.clone = function (name, id) {
  82452. var result = new Skeleton(name, id || name, this._scene);
  82453. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82454. for (var index = 0; index < this.bones.length; index++) {
  82455. var source = this.bones[index];
  82456. var parentBone = null;
  82457. var parent_1 = source.getParent();
  82458. if (parent_1) {
  82459. var parentIndex = this.bones.indexOf(parent_1);
  82460. parentBone = result.bones[parentIndex];
  82461. }
  82462. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82463. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82464. }
  82465. if (this._ranges) {
  82466. result._ranges = {};
  82467. for (var rangeName in this._ranges) {
  82468. var range = this._ranges[rangeName];
  82469. if (range) {
  82470. result._ranges[rangeName] = range.clone();
  82471. }
  82472. }
  82473. }
  82474. this._isDirty = true;
  82475. return result;
  82476. };
  82477. /**
  82478. * Enable animation blending for this skeleton
  82479. * @param blendingSpeed defines the blending speed to apply
  82480. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82481. */
  82482. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82483. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82484. this.bones.forEach(function (bone) {
  82485. bone.animations.forEach(function (animation) {
  82486. animation.enableBlending = true;
  82487. animation.blendingSpeed = blendingSpeed;
  82488. });
  82489. });
  82490. };
  82491. /**
  82492. * Releases all resources associated with the current skeleton
  82493. */
  82494. Skeleton.prototype.dispose = function () {
  82495. this._meshesWithPoseMatrix = [];
  82496. // Animations
  82497. this.getScene().stopAnimation(this);
  82498. // Remove from scene
  82499. this.getScene().removeSkeleton(this);
  82500. };
  82501. /**
  82502. * Serialize the skeleton in a JSON object
  82503. * @returns a JSON object
  82504. */
  82505. Skeleton.prototype.serialize = function () {
  82506. var serializationObject = {};
  82507. serializationObject.name = this.name;
  82508. serializationObject.id = this.id;
  82509. if (this.dimensionsAtRest) {
  82510. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82511. }
  82512. serializationObject.bones = [];
  82513. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82514. for (var index = 0; index < this.bones.length; index++) {
  82515. var bone = this.bones[index];
  82516. var parent_2 = bone.getParent();
  82517. var serializedBone = {
  82518. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82519. name: bone.name,
  82520. matrix: bone.getBaseMatrix().toArray(),
  82521. rest: bone.getRestPose().toArray()
  82522. };
  82523. serializationObject.bones.push(serializedBone);
  82524. if (bone.length) {
  82525. serializedBone.length = bone.length;
  82526. }
  82527. if (bone.metadata) {
  82528. serializedBone.metadata = bone.metadata;
  82529. }
  82530. if (bone.animations && bone.animations.length > 0) {
  82531. serializedBone.animation = bone.animations[0].serialize();
  82532. }
  82533. serializationObject.ranges = [];
  82534. for (var name in this._ranges) {
  82535. var source = this._ranges[name];
  82536. if (!source) {
  82537. continue;
  82538. }
  82539. var range = {};
  82540. range.name = name;
  82541. range.from = source.from;
  82542. range.to = source.to;
  82543. serializationObject.ranges.push(range);
  82544. }
  82545. }
  82546. return serializationObject;
  82547. };
  82548. /**
  82549. * Creates a new skeleton from serialized data
  82550. * @param parsedSkeleton defines the serialized data
  82551. * @param scene defines the hosting scene
  82552. * @returns a new skeleton
  82553. */
  82554. Skeleton.Parse = function (parsedSkeleton, scene) {
  82555. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82556. if (parsedSkeleton.dimensionsAtRest) {
  82557. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82558. }
  82559. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82560. var index;
  82561. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82562. var parsedBone = parsedSkeleton.bones[index];
  82563. var parentBone = null;
  82564. if (parsedBone.parentBoneIndex > -1) {
  82565. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82566. }
  82567. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82568. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82569. if (parsedBone.length) {
  82570. bone.length = parsedBone.length;
  82571. }
  82572. if (parsedBone.metadata) {
  82573. bone.metadata = parsedBone.metadata;
  82574. }
  82575. if (parsedBone.animation) {
  82576. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82577. }
  82578. }
  82579. // placed after bones, so createAnimationRange can cascade down
  82580. if (parsedSkeleton.ranges) {
  82581. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82582. var data = parsedSkeleton.ranges[index];
  82583. skeleton.createAnimationRange(data.name, data.from, data.to);
  82584. }
  82585. }
  82586. return skeleton;
  82587. };
  82588. /**
  82589. * Compute all node absolute transforms
  82590. * @param forceUpdate defines if computation must be done even if cache is up to date
  82591. */
  82592. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82593. if (forceUpdate === void 0) { forceUpdate = false; }
  82594. var renderId = this._scene.getRenderId();
  82595. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82596. this.bones[0].computeAbsoluteTransforms();
  82597. this._lastAbsoluteTransformsUpdateId = renderId;
  82598. }
  82599. };
  82600. /**
  82601. * Gets the root pose matrix
  82602. * @returns a matrix
  82603. */
  82604. Skeleton.prototype.getPoseMatrix = function () {
  82605. var poseMatrix = null;
  82606. if (this._meshesWithPoseMatrix.length > 0) {
  82607. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82608. }
  82609. return poseMatrix;
  82610. };
  82611. /**
  82612. * Sorts bones per internal index
  82613. */
  82614. Skeleton.prototype.sortBones = function () {
  82615. var bones = new Array();
  82616. var visited = new Array(this.bones.length);
  82617. for (var index = 0; index < this.bones.length; index++) {
  82618. this._sortBones(index, bones, visited);
  82619. }
  82620. this.bones = bones;
  82621. };
  82622. Skeleton.prototype._sortBones = function (index, bones, visited) {
  82623. if (visited[index]) {
  82624. return;
  82625. }
  82626. visited[index] = true;
  82627. var bone = this.bones[index];
  82628. if (bone._index === undefined) {
  82629. bone._index = index;
  82630. }
  82631. var parentBone = bone.getParent();
  82632. if (parentBone) {
  82633. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  82634. }
  82635. bones.push(bone);
  82636. };
  82637. return Skeleton;
  82638. }());
  82639. BABYLON.Skeleton = Skeleton;
  82640. })(BABYLON || (BABYLON = {}));
  82641. //# sourceMappingURL=babylon.skeleton.js.map
  82642. var BABYLON;
  82643. (function (BABYLON) {
  82644. /**
  82645. * Class representing spherical polynomial coefficients to the 3rd degree
  82646. */
  82647. var SphericalPolynomial = /** @class */ (function () {
  82648. function SphericalPolynomial() {
  82649. /**
  82650. * The x coefficients of the spherical polynomial
  82651. */
  82652. this.x = BABYLON.Vector3.Zero();
  82653. /**
  82654. * The y coefficients of the spherical polynomial
  82655. */
  82656. this.y = BABYLON.Vector3.Zero();
  82657. /**
  82658. * The z coefficients of the spherical polynomial
  82659. */
  82660. this.z = BABYLON.Vector3.Zero();
  82661. /**
  82662. * The xx coefficients of the spherical polynomial
  82663. */
  82664. this.xx = BABYLON.Vector3.Zero();
  82665. /**
  82666. * The yy coefficients of the spherical polynomial
  82667. */
  82668. this.yy = BABYLON.Vector3.Zero();
  82669. /**
  82670. * The zz coefficients of the spherical polynomial
  82671. */
  82672. this.zz = BABYLON.Vector3.Zero();
  82673. /**
  82674. * The xy coefficients of the spherical polynomial
  82675. */
  82676. this.xy = BABYLON.Vector3.Zero();
  82677. /**
  82678. * The yz coefficients of the spherical polynomial
  82679. */
  82680. this.yz = BABYLON.Vector3.Zero();
  82681. /**
  82682. * The zx coefficients of the spherical polynomial
  82683. */
  82684. this.zx = BABYLON.Vector3.Zero();
  82685. }
  82686. /**
  82687. * Adds an ambient color to the spherical polynomial
  82688. * @param color the color to add
  82689. */
  82690. SphericalPolynomial.prototype.addAmbient = function (color) {
  82691. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82692. this.xx = this.xx.add(colorVector);
  82693. this.yy = this.yy.add(colorVector);
  82694. this.zz = this.zz.add(colorVector);
  82695. };
  82696. /**
  82697. * Scales the spherical polynomial by the given amount
  82698. * @param scale the amount to scale
  82699. */
  82700. SphericalPolynomial.prototype.scale = function (scale) {
  82701. this.x = this.x.scale(scale);
  82702. this.y = this.y.scale(scale);
  82703. this.z = this.z.scale(scale);
  82704. this.xx = this.xx.scale(scale);
  82705. this.yy = this.yy.scale(scale);
  82706. this.zz = this.zz.scale(scale);
  82707. this.yz = this.yz.scale(scale);
  82708. this.zx = this.zx.scale(scale);
  82709. this.xy = this.xy.scale(scale);
  82710. };
  82711. /**
  82712. * Gets the spherical polynomial from harmonics
  82713. * @param harmonics the spherical harmonics
  82714. * @returns the spherical polynomial
  82715. */
  82716. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82717. var result = new SphericalPolynomial();
  82718. result.x = harmonics.l11.scale(1.02333);
  82719. result.y = harmonics.l1_1.scale(1.02333);
  82720. result.z = harmonics.l10.scale(1.02333);
  82721. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82722. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82723. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82724. result.yz = harmonics.l2_1.scale(0.858086);
  82725. result.zx = harmonics.l21.scale(0.858086);
  82726. result.xy = harmonics.l2_2.scale(0.858086);
  82727. result.scale(1.0 / Math.PI);
  82728. return result;
  82729. };
  82730. /**
  82731. * Constructs a spherical polynomial from an array.
  82732. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82733. * @returns the spherical polynomial
  82734. */
  82735. SphericalPolynomial.FromArray = function (data) {
  82736. var sp = new SphericalPolynomial();
  82737. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82738. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82739. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82740. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82741. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82742. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82743. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82744. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82745. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82746. return sp;
  82747. };
  82748. return SphericalPolynomial;
  82749. }());
  82750. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82751. /**
  82752. * Class representing spherical harmonics coefficients to the 3rd degree
  82753. */
  82754. var SphericalHarmonics = /** @class */ (function () {
  82755. function SphericalHarmonics() {
  82756. /**
  82757. * The l0,0 coefficients of the spherical harmonics
  82758. */
  82759. this.l00 = BABYLON.Vector3.Zero();
  82760. /**
  82761. * The l1,-1 coefficients of the spherical harmonics
  82762. */
  82763. this.l1_1 = BABYLON.Vector3.Zero();
  82764. /**
  82765. * The l1,0 coefficients of the spherical harmonics
  82766. */
  82767. this.l10 = BABYLON.Vector3.Zero();
  82768. /**
  82769. * The l1,1 coefficients of the spherical harmonics
  82770. */
  82771. this.l11 = BABYLON.Vector3.Zero();
  82772. /**
  82773. * The l2,-2 coefficients of the spherical harmonics
  82774. */
  82775. this.l2_2 = BABYLON.Vector3.Zero();
  82776. /**
  82777. * The l2,-1 coefficients of the spherical harmonics
  82778. */
  82779. this.l2_1 = BABYLON.Vector3.Zero();
  82780. /**
  82781. * The l2,0 coefficients of the spherical harmonics
  82782. */
  82783. this.l20 = BABYLON.Vector3.Zero();
  82784. /**
  82785. * The l2,1 coefficients of the spherical harmonics
  82786. */
  82787. this.l21 = BABYLON.Vector3.Zero();
  82788. /**
  82789. * The l2,2 coefficients of the spherical harmonics
  82790. */
  82791. this.lL22 = BABYLON.Vector3.Zero();
  82792. }
  82793. /**
  82794. * Adds a light to the spherical harmonics
  82795. * @param direction the direction of the light
  82796. * @param color the color of the light
  82797. * @param deltaSolidAngle the delta solid angle of the light
  82798. */
  82799. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82800. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82801. var c = colorVector.scale(deltaSolidAngle);
  82802. this.l00 = this.l00.add(c.scale(0.282095));
  82803. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82804. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82805. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82806. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82807. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82808. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82809. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82810. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82811. };
  82812. /**
  82813. * Scales the spherical harmonics by the given amount
  82814. * @param scale the amount to scale
  82815. */
  82816. SphericalHarmonics.prototype.scale = function (scale) {
  82817. this.l00 = this.l00.scale(scale);
  82818. this.l1_1 = this.l1_1.scale(scale);
  82819. this.l10 = this.l10.scale(scale);
  82820. this.l11 = this.l11.scale(scale);
  82821. this.l2_2 = this.l2_2.scale(scale);
  82822. this.l2_1 = this.l2_1.scale(scale);
  82823. this.l20 = this.l20.scale(scale);
  82824. this.l21 = this.l21.scale(scale);
  82825. this.lL22 = this.lL22.scale(scale);
  82826. };
  82827. /**
  82828. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82829. *
  82830. * ```
  82831. * E_lm = A_l * L_lm
  82832. * ```
  82833. *
  82834. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82835. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82836. * the scaling factors are given in equation 9.
  82837. */
  82838. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82839. // Constant (Band 0)
  82840. this.l00 = this.l00.scale(3.141593);
  82841. // Linear (Band 1)
  82842. this.l1_1 = this.l1_1.scale(2.094395);
  82843. this.l10 = this.l10.scale(2.094395);
  82844. this.l11 = this.l11.scale(2.094395);
  82845. // Quadratic (Band 2)
  82846. this.l2_2 = this.l2_2.scale(0.785398);
  82847. this.l2_1 = this.l2_1.scale(0.785398);
  82848. this.l20 = this.l20.scale(0.785398);
  82849. this.l21 = this.l21.scale(0.785398);
  82850. this.lL22 = this.lL22.scale(0.785398);
  82851. };
  82852. /**
  82853. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82854. *
  82855. * ```
  82856. * L = (1/pi) * E * rho
  82857. * ```
  82858. *
  82859. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82860. */
  82861. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82862. this.scale(1.0 / Math.PI);
  82863. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82864. // (The pixel shader must apply albedo after texture fetches, etc).
  82865. };
  82866. /**
  82867. * Gets the spherical harmonics from polynomial
  82868. * @param polynomial the spherical polynomial
  82869. * @returns the spherical harmonics
  82870. */
  82871. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82872. var result = new SphericalHarmonics();
  82873. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82874. result.l1_1 = polynomial.y.scale(0.977204);
  82875. result.l10 = polynomial.z.scale(0.977204);
  82876. result.l11 = polynomial.x.scale(0.977204);
  82877. result.l2_2 = polynomial.xy.scale(1.16538);
  82878. result.l2_1 = polynomial.yz.scale(1.16538);
  82879. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82880. result.l21 = polynomial.zx.scale(1.16538);
  82881. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82882. result.scale(Math.PI);
  82883. return result;
  82884. };
  82885. /**
  82886. * Constructs a spherical harmonics from an array.
  82887. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82888. * @returns the spherical harmonics
  82889. */
  82890. SphericalHarmonics.FromArray = function (data) {
  82891. var sh = new SphericalHarmonics();
  82892. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82893. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82894. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82895. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82896. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82897. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82898. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82899. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82900. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82901. return sh;
  82902. };
  82903. return SphericalHarmonics;
  82904. }());
  82905. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82906. })(BABYLON || (BABYLON = {}));
  82907. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82908. var BABYLON;
  82909. (function (BABYLON) {
  82910. var FileFaceOrientation = /** @class */ (function () {
  82911. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82912. this.name = name;
  82913. this.worldAxisForNormal = worldAxisForNormal;
  82914. this.worldAxisForFileX = worldAxisForFileX;
  82915. this.worldAxisForFileY = worldAxisForFileY;
  82916. }
  82917. return FileFaceOrientation;
  82918. }());
  82919. ;
  82920. /**
  82921. * Helper class dealing with the extraction of spherical polynomial dataArray
  82922. * from a cube map.
  82923. */
  82924. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82925. function CubeMapToSphericalPolynomialTools() {
  82926. }
  82927. /**
  82928. * Converts a texture to the according Spherical Polynomial data.
  82929. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82930. *
  82931. * @param texture The texture to extract the information from.
  82932. * @return The Spherical Polynomial data.
  82933. */
  82934. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82935. if (!texture.isCube) {
  82936. // Only supports cube Textures currently.
  82937. return null;
  82938. }
  82939. var size = texture.getSize().width;
  82940. var right = texture.readPixels(0);
  82941. var left = texture.readPixels(1);
  82942. var up;
  82943. var down;
  82944. if (texture.isRenderTarget) {
  82945. up = texture.readPixels(3);
  82946. down = texture.readPixels(2);
  82947. }
  82948. else {
  82949. up = texture.readPixels(2);
  82950. down = texture.readPixels(3);
  82951. }
  82952. var front = texture.readPixels(4);
  82953. var back = texture.readPixels(5);
  82954. var gammaSpace = texture.gammaSpace;
  82955. // Always read as RGBA.
  82956. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82957. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82958. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82959. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82960. }
  82961. var cubeInfo = {
  82962. size: size,
  82963. right: right,
  82964. left: left,
  82965. up: up,
  82966. down: down,
  82967. front: front,
  82968. back: back,
  82969. format: format,
  82970. type: type,
  82971. gammaSpace: gammaSpace,
  82972. };
  82973. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82974. };
  82975. /**
  82976. * Converts a cubemap to the according Spherical Polynomial data.
  82977. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82978. *
  82979. * @param cubeInfo The Cube map to extract the information from.
  82980. * @return The Spherical Polynomial data.
  82981. */
  82982. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82983. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82984. var totalSolidAngle = 0.0;
  82985. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82986. var du = 2.0 / cubeInfo.size;
  82987. var dv = du;
  82988. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82989. var minUV = du * 0.5 - 1.0;
  82990. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82991. var fileFace = this.FileFaces[faceIndex];
  82992. var dataArray = cubeInfo[fileFace.name];
  82993. var v = minUV;
  82994. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82995. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82996. // Because SP is still linear, so summation is fine in that basis.
  82997. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82998. for (var y = 0; y < cubeInfo.size; y++) {
  82999. var u = minUV;
  83000. for (var x = 0; x < cubeInfo.size; x++) {
  83001. // World direction (not normalised)
  83002. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  83003. worldDirection.normalize();
  83004. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  83005. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  83006. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  83007. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  83008. // Handle Integer types.
  83009. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  83010. r /= 255;
  83011. g /= 255;
  83012. b /= 255;
  83013. }
  83014. // Handle Gamma space textures.
  83015. if (cubeInfo.gammaSpace) {
  83016. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  83017. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  83018. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  83019. }
  83020. var color = new BABYLON.Color3(r, g, b);
  83021. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  83022. totalSolidAngle += deltaSolidAngle;
  83023. u += du;
  83024. }
  83025. v += dv;
  83026. }
  83027. }
  83028. // Solid angle for entire sphere is 4*pi
  83029. var sphereSolidAngle = 4.0 * Math.PI;
  83030. // Adjust the solid angle to allow for how many faces we processed.
  83031. var facesProcessed = 6.0;
  83032. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  83033. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  83034. // This is needed because the numerical integration over the cube uses a
  83035. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  83036. // and also to compensate for accumulative error due to float precision in the summation.
  83037. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  83038. sphericalHarmonics.scale(correctionFactor);
  83039. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  83040. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  83041. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  83042. };
  83043. CubeMapToSphericalPolynomialTools.FileFaces = [
  83044. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  83045. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  83046. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  83047. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  83048. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  83049. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  83050. ];
  83051. return CubeMapToSphericalPolynomialTools;
  83052. }());
  83053. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  83054. })(BABYLON || (BABYLON = {}));
  83055. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  83056. var BABYLON;
  83057. (function (BABYLON) {
  83058. /**
  83059. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83060. */
  83061. var PanoramaToCubeMapTools = /** @class */ (function () {
  83062. function PanoramaToCubeMapTools() {
  83063. }
  83064. /**
  83065. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83066. *
  83067. * @param float32Array The source data.
  83068. * @param inputWidth The width of the input panorama.
  83069. * @param inputhHeight The height of the input panorama.
  83070. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83071. * @return The cubemap data
  83072. */
  83073. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83074. if (!float32Array) {
  83075. throw "ConvertPanoramaToCubemap: input cannot be null";
  83076. }
  83077. if (float32Array.length != inputWidth * inputHeight * 3) {
  83078. throw "ConvertPanoramaToCubemap: input size is wrong";
  83079. }
  83080. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83081. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83082. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83083. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83084. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83085. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83086. return {
  83087. front: textureFront,
  83088. back: textureBack,
  83089. left: textureLeft,
  83090. right: textureRight,
  83091. up: textureUp,
  83092. down: textureDown,
  83093. size: size,
  83094. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83095. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83096. gammaSpace: false,
  83097. };
  83098. };
  83099. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83100. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83101. var textureArray = new Float32Array(buffer);
  83102. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83103. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83104. var dy = 1 / texSize;
  83105. var fy = 0;
  83106. for (var y = 0; y < texSize; y++) {
  83107. var xv1 = faceData[0];
  83108. var xv2 = faceData[2];
  83109. for (var x = 0; x < texSize; x++) {
  83110. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83111. v.normalize();
  83112. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83113. // 3 channels per pixels
  83114. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83115. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83116. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83117. xv1 = xv1.add(rotDX1);
  83118. xv2 = xv2.add(rotDX2);
  83119. }
  83120. fy += dy;
  83121. }
  83122. return textureArray;
  83123. };
  83124. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83125. var theta = Math.atan2(vDir.z, vDir.x);
  83126. var phi = Math.acos(vDir.y);
  83127. while (theta < -Math.PI)
  83128. theta += 2 * Math.PI;
  83129. while (theta > Math.PI)
  83130. theta -= 2 * Math.PI;
  83131. var dx = theta / Math.PI;
  83132. var dy = phi / Math.PI;
  83133. // recenter.
  83134. dx = dx * 0.5 + 0.5;
  83135. var px = Math.round(dx * inputWidth);
  83136. if (px < 0)
  83137. px = 0;
  83138. else if (px >= inputWidth)
  83139. px = inputWidth - 1;
  83140. var py = Math.round(dy * inputHeight);
  83141. if (py < 0)
  83142. py = 0;
  83143. else if (py >= inputHeight)
  83144. py = inputHeight - 1;
  83145. var inputY = (inputHeight - py - 1);
  83146. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83147. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83148. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83149. return {
  83150. r: r,
  83151. g: g,
  83152. b: b
  83153. };
  83154. };
  83155. PanoramaToCubeMapTools.FACE_FRONT = [
  83156. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83157. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83158. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83159. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83160. ];
  83161. PanoramaToCubeMapTools.FACE_BACK = [
  83162. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83163. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83164. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83165. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83166. ];
  83167. PanoramaToCubeMapTools.FACE_RIGHT = [
  83168. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83169. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83170. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83171. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83172. ];
  83173. PanoramaToCubeMapTools.FACE_LEFT = [
  83174. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83175. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83176. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83177. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83178. ];
  83179. PanoramaToCubeMapTools.FACE_DOWN = [
  83180. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83181. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83182. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83183. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83184. ];
  83185. PanoramaToCubeMapTools.FACE_UP = [
  83186. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83187. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83188. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83189. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83190. ];
  83191. return PanoramaToCubeMapTools;
  83192. }());
  83193. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83194. })(BABYLON || (BABYLON = {}));
  83195. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83196. var BABYLON;
  83197. (function (BABYLON) {
  83198. ;
  83199. /**
  83200. * This groups tools to convert HDR texture to native colors array.
  83201. */
  83202. var HDRTools = /** @class */ (function () {
  83203. function HDRTools() {
  83204. }
  83205. HDRTools.Ldexp = function (mantissa, exponent) {
  83206. if (exponent > 1023) {
  83207. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83208. }
  83209. if (exponent < -1074) {
  83210. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83211. }
  83212. return mantissa * Math.pow(2, exponent);
  83213. };
  83214. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83215. if (exponent > 0) { /*nonzero pixel*/
  83216. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83217. float32array[index + 0] = red * exponent;
  83218. float32array[index + 1] = green * exponent;
  83219. float32array[index + 2] = blue * exponent;
  83220. }
  83221. else {
  83222. float32array[index + 0] = 0;
  83223. float32array[index + 1] = 0;
  83224. float32array[index + 2] = 0;
  83225. }
  83226. };
  83227. HDRTools.readStringLine = function (uint8array, startIndex) {
  83228. var line = "";
  83229. var character = "";
  83230. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83231. character = String.fromCharCode(uint8array[i]);
  83232. if (character == "\n") {
  83233. break;
  83234. }
  83235. line += character;
  83236. }
  83237. return line;
  83238. };
  83239. /**
  83240. * Reads header information from an RGBE texture stored in a native array.
  83241. * More information on this format are available here:
  83242. * https://en.wikipedia.org/wiki/RGBE_image_format
  83243. *
  83244. * @param uint8array The binary file stored in native array.
  83245. * @return The header information.
  83246. */
  83247. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83248. var height = 0;
  83249. var width = 0;
  83250. var line = this.readStringLine(uint8array, 0);
  83251. if (line[0] != '#' || line[1] != '?') {
  83252. throw "Bad HDR Format.";
  83253. }
  83254. var endOfHeader = false;
  83255. var findFormat = false;
  83256. var lineIndex = 0;
  83257. do {
  83258. lineIndex += (line.length + 1);
  83259. line = this.readStringLine(uint8array, lineIndex);
  83260. if (line == "FORMAT=32-bit_rle_rgbe") {
  83261. findFormat = true;
  83262. }
  83263. else if (line.length == 0) {
  83264. endOfHeader = true;
  83265. }
  83266. } while (!endOfHeader);
  83267. if (!findFormat) {
  83268. throw "HDR Bad header format, unsupported FORMAT";
  83269. }
  83270. lineIndex += (line.length + 1);
  83271. line = this.readStringLine(uint8array, lineIndex);
  83272. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83273. var match = sizeRegexp.exec(line);
  83274. // TODO. Support +Y and -X if needed.
  83275. if (!match || match.length < 3) {
  83276. throw "HDR Bad header format, no size";
  83277. }
  83278. width = parseInt(match[2]);
  83279. height = parseInt(match[1]);
  83280. if (width < 8 || width > 0x7fff) {
  83281. throw "HDR Bad header format, unsupported size";
  83282. }
  83283. lineIndex += (line.length + 1);
  83284. return {
  83285. height: height,
  83286. width: width,
  83287. dataPosition: lineIndex
  83288. };
  83289. };
  83290. /**
  83291. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83292. * This RGBE texture needs to store the information as a panorama.
  83293. *
  83294. * More information on this format are available here:
  83295. * https://en.wikipedia.org/wiki/RGBE_image_format
  83296. *
  83297. * @param buffer The binary file stored in an array buffer.
  83298. * @param size The expected size of the extracted cubemap.
  83299. * @return The Cube Map information.
  83300. */
  83301. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83302. var uint8array = new Uint8Array(buffer);
  83303. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83304. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83305. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83306. return cubeMapData;
  83307. };
  83308. /**
  83309. * Returns the pixels data extracted from an RGBE texture.
  83310. * This pixels will be stored left to right up to down in the R G B order in one array.
  83311. *
  83312. * More information on this format are available here:
  83313. * https://en.wikipedia.org/wiki/RGBE_image_format
  83314. *
  83315. * @param uint8array The binary file stored in an array buffer.
  83316. * @param hdrInfo The header information of the file.
  83317. * @return The pixels data in RGB right to left up to down order.
  83318. */
  83319. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83320. // Keep for multi format supports.
  83321. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83322. };
  83323. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83324. var num_scanlines = hdrInfo.height;
  83325. var scanline_width = hdrInfo.width;
  83326. var a, b, c, d, count;
  83327. var dataIndex = hdrInfo.dataPosition;
  83328. var index = 0, endIndex = 0, i = 0;
  83329. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83330. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83331. // 3 channels of 4 bytes per pixel in float.
  83332. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83333. var resultArray = new Float32Array(resultBuffer);
  83334. // read in each successive scanline
  83335. while (num_scanlines > 0) {
  83336. a = uint8array[dataIndex++];
  83337. b = uint8array[dataIndex++];
  83338. c = uint8array[dataIndex++];
  83339. d = uint8array[dataIndex++];
  83340. if (a != 2 || b != 2 || (c & 0x80)) {
  83341. // this file is not run length encoded
  83342. throw "HDR Bad header format, not RLE";
  83343. }
  83344. if (((c << 8) | d) != scanline_width) {
  83345. throw "HDR Bad header format, wrong scan line width";
  83346. }
  83347. index = 0;
  83348. // read each of the four channels for the scanline into the buffer
  83349. for (i = 0; i < 4; i++) {
  83350. endIndex = (i + 1) * scanline_width;
  83351. while (index < endIndex) {
  83352. a = uint8array[dataIndex++];
  83353. b = uint8array[dataIndex++];
  83354. if (a > 128) {
  83355. // a run of the same value
  83356. count = a - 128;
  83357. if ((count == 0) || (count > endIndex - index)) {
  83358. throw "HDR Bad Format, bad scanline data (run)";
  83359. }
  83360. while (count-- > 0) {
  83361. scanLineArray[index++] = b;
  83362. }
  83363. }
  83364. else {
  83365. // a non-run
  83366. count = a;
  83367. if ((count == 0) || (count > endIndex - index)) {
  83368. throw "HDR Bad Format, bad scanline data (non-run)";
  83369. }
  83370. scanLineArray[index++] = b;
  83371. if (--count > 0) {
  83372. for (var j = 0; j < count; j++) {
  83373. scanLineArray[index++] = uint8array[dataIndex++];
  83374. }
  83375. }
  83376. }
  83377. }
  83378. }
  83379. // now convert data from buffer into floats
  83380. for (i = 0; i < scanline_width; i++) {
  83381. a = scanLineArray[i];
  83382. b = scanLineArray[i + scanline_width];
  83383. c = scanLineArray[i + 2 * scanline_width];
  83384. d = scanLineArray[i + 3 * scanline_width];
  83385. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83386. }
  83387. num_scanlines--;
  83388. }
  83389. return resultArray;
  83390. };
  83391. return HDRTools;
  83392. }());
  83393. BABYLON.HDRTools = HDRTools;
  83394. })(BABYLON || (BABYLON = {}));
  83395. //# sourceMappingURL=babylon.hdr.js.map
  83396. var BABYLON;
  83397. (function (BABYLON) {
  83398. /**
  83399. * Sets of helpers addressing the serialization and deserialization of environment texture
  83400. * stored in a BabylonJS env file.
  83401. * Those files are usually stored as .env files.
  83402. */
  83403. var EnvironmentTextureTools = /** @class */ (function () {
  83404. function EnvironmentTextureTools() {
  83405. }
  83406. /**
  83407. * Gets the environment info from an env file.
  83408. * @param data The array buffer containing the .env bytes.
  83409. * @returns the environment file info (the json header) if successfully parsed.
  83410. */
  83411. EnvironmentTextureTools.GetEnvInfo = function (data) {
  83412. var dataView = new DataView(data);
  83413. var pos = 0;
  83414. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  83415. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  83416. BABYLON.Tools.Error('Not a babylon environment map');
  83417. return null;
  83418. }
  83419. }
  83420. // Read json manifest - collect characters up to null terminator
  83421. var manifestString = '';
  83422. var charCode = 0x00;
  83423. while ((charCode = dataView.getUint8(pos++))) {
  83424. manifestString += String.fromCharCode(charCode);
  83425. }
  83426. var manifest = JSON.parse(manifestString);
  83427. if (manifest.specular) {
  83428. // Extend the header with the position of the payload.
  83429. manifest.specular.specularDataPosition = pos;
  83430. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  83431. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  83432. }
  83433. return manifest;
  83434. };
  83435. /**
  83436. * Creates an environment texture from a loaded cube texture.
  83437. * @param texture defines the cube texture to convert in env file
  83438. * @return a promise containing the environment data if succesfull.
  83439. */
  83440. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  83441. var _this = this;
  83442. var internalTexture = texture.getInternalTexture();
  83443. if (!internalTexture) {
  83444. return Promise.reject("The cube texture is invalid.");
  83445. }
  83446. if (!texture._prefiltered) {
  83447. return Promise.reject("The cube texture is invalid (not prefiltered).");
  83448. }
  83449. var engine = internalTexture.getEngine();
  83450. if (engine && engine.premultipliedAlpha) {
  83451. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  83452. }
  83453. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  83454. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  83455. }
  83456. var canvas = engine.getRenderingCanvas();
  83457. if (!canvas) {
  83458. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  83459. }
  83460. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83461. if (!engine.getCaps().textureFloatRender) {
  83462. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83463. if (!engine.getCaps().textureHalfFloatRender) {
  83464. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  83465. }
  83466. }
  83467. var cubeWidth = internalTexture.width;
  83468. var hostingScene = new BABYLON.Scene(engine);
  83469. var specularTextures = {};
  83470. var promises = [];
  83471. // Read and collect all mipmaps data from the cube.
  83472. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  83473. mipmapsCount = Math.round(mipmapsCount);
  83474. var _loop_1 = function (i) {
  83475. var faceWidth = Math.pow(2, mipmapsCount - i);
  83476. var _loop_2 = function (face) {
  83477. var data = texture.readPixels(face, i);
  83478. // Creates a temp texture with the face data.
  83479. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  83480. // And rgbdEncode them.
  83481. var promise = new Promise(function (resolve, reject) {
  83482. 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);
  83483. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83484. rgbdPostProcess.onApply = function (effect) {
  83485. effect._bindTexture("textureSampler", tempTexture);
  83486. };
  83487. // As the process needs to happen on the main canvas, keep track of the current size
  83488. var currentW = engine.getRenderWidth();
  83489. var currentH = engine.getRenderHeight();
  83490. // Set the desired size for the texture
  83491. engine.setSize(faceWidth, faceWidth);
  83492. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  83493. // Reading datas from WebGL
  83494. BABYLON.Tools.ToBlob(canvas, function (blob) {
  83495. var fileReader = new FileReader();
  83496. fileReader.onload = function (event) {
  83497. var arrayBuffer = event.target.result;
  83498. specularTextures[i * 6 + face] = arrayBuffer;
  83499. resolve();
  83500. };
  83501. fileReader.readAsArrayBuffer(blob);
  83502. });
  83503. // Reapply the previous canvas size
  83504. engine.setSize(currentW, currentH);
  83505. });
  83506. });
  83507. promises.push(promise);
  83508. };
  83509. // All faces of the cube.
  83510. for (var face = 0; face < 6; face++) {
  83511. _loop_2(face);
  83512. }
  83513. };
  83514. for (var i = 0; i <= mipmapsCount; i++) {
  83515. _loop_1(i);
  83516. }
  83517. // Once all the textures haves been collected as RGBD stored in PNGs
  83518. return Promise.all(promises).then(function () {
  83519. // We can delete the hosting scene keeping track of all the creation objects
  83520. hostingScene.dispose();
  83521. // Creates the json header for the env texture
  83522. var info = {
  83523. version: 1,
  83524. width: cubeWidth,
  83525. irradiance: _this._CreateEnvTextureIrradiance(texture),
  83526. specular: {
  83527. mipmaps: [],
  83528. lodGenerationScale: texture.lodGenerationScale
  83529. }
  83530. };
  83531. // Sets the specular image data information
  83532. var position = 0;
  83533. for (var i = 0; i <= mipmapsCount; i++) {
  83534. for (var face = 0; face < 6; face++) {
  83535. var byteLength = specularTextures[i * 6 + face].byteLength;
  83536. info.specular.mipmaps.push({
  83537. length: byteLength,
  83538. position: position
  83539. });
  83540. position += byteLength;
  83541. }
  83542. }
  83543. // Encode the JSON as an array buffer
  83544. var infoString = JSON.stringify(info);
  83545. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  83546. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  83547. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  83548. infoView[i] = infoString.charCodeAt(i);
  83549. }
  83550. // Ends up with a null terminator for easier parsing
  83551. infoView[infoString.length] = 0x00;
  83552. // Computes the final required size and creates the storage
  83553. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  83554. var finalBuffer = new ArrayBuffer(totalSize);
  83555. var finalBufferView = new Uint8Array(finalBuffer);
  83556. var dataView = new DataView(finalBuffer);
  83557. // Copy the magic bytes identifying the file in
  83558. var pos = 0;
  83559. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  83560. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  83561. }
  83562. // Add the json info
  83563. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  83564. pos += infoBuffer.byteLength;
  83565. // Finally inserts the texture data
  83566. for (var i = 0; i <= mipmapsCount; i++) {
  83567. for (var face = 0; face < 6; face++) {
  83568. var dataBuffer = specularTextures[i * 6 + face];
  83569. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  83570. pos += dataBuffer.byteLength;
  83571. }
  83572. }
  83573. // Voila
  83574. return finalBuffer;
  83575. });
  83576. };
  83577. /**
  83578. * Creates a JSON representation of the spherical data.
  83579. * @param texture defines the texture containing the polynomials
  83580. * @return the JSON representation of the spherical info
  83581. */
  83582. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  83583. var polynmials = texture.sphericalPolynomial;
  83584. if (polynmials == null) {
  83585. return null;
  83586. }
  83587. return {
  83588. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  83589. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  83590. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  83591. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  83592. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  83593. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  83594. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  83595. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  83596. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  83597. };
  83598. };
  83599. /**
  83600. * Uploads the texture info contained in the env file to the GPU.
  83601. * @param texture defines the internal texture to upload to
  83602. * @param arrayBuffer defines the buffer cotaining the data to load
  83603. * @param info defines the texture info retrieved through the GetEnvInfo method
  83604. * @returns a promise
  83605. */
  83606. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  83607. if (info.version !== 1) {
  83608. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  83609. }
  83610. var specularInfo = info.specular;
  83611. if (!specularInfo) {
  83612. // Nothing else parsed so far
  83613. return Promise.resolve();
  83614. }
  83615. // Double checks the enclosed info
  83616. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  83617. mipmapsCount = Math.round(mipmapsCount) + 1;
  83618. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  83619. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  83620. }
  83621. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  83622. var imageData = new Array(mipmapsCount);
  83623. for (var i = 0; i < mipmapsCount; i++) {
  83624. imageData[i] = new Array(6);
  83625. for (var face = 0; face < 6; face++) {
  83626. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  83627. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  83628. }
  83629. }
  83630. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  83631. };
  83632. /**
  83633. * Uploads the levels of image data to the GPU.
  83634. * @param texture defines the internal texture to upload to
  83635. * @param imageData defines the array buffer views of image data [mipmap][face]
  83636. * @returns a promise
  83637. */
  83638. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  83639. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  83640. throw new Error("Texture size must be a power of two");
  83641. }
  83642. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  83643. // Gets everything ready.
  83644. var engine = texture.getEngine();
  83645. var expandTexture = false;
  83646. var generateNonLODTextures = false;
  83647. var rgbdPostProcess = null;
  83648. var cubeRtt = null;
  83649. var lodTextures = null;
  83650. var caps = engine.getCaps();
  83651. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  83652. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83653. texture.generateMipMaps = true;
  83654. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  83655. // Add extra process if texture lod is not supported
  83656. if (!caps.textureLOD) {
  83657. expandTexture = false;
  83658. generateNonLODTextures = true;
  83659. lodTextures = {};
  83660. }
  83661. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  83662. else if (engine.webGLVersion < 2) {
  83663. expandTexture = false;
  83664. }
  83665. // If half float available we can uncompress the texture
  83666. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  83667. expandTexture = true;
  83668. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83669. }
  83670. // If full float available we can uncompress the texture
  83671. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  83672. expandTexture = true;
  83673. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83674. }
  83675. // Expand the texture if possible
  83676. if (expandTexture) {
  83677. // Simply run through the decode PP
  83678. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  83679. texture._isRGBD = false;
  83680. texture.invertY = false;
  83681. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  83682. generateDepthBuffer: false,
  83683. generateMipMaps: true,
  83684. generateStencilBuffer: false,
  83685. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  83686. type: texture.type,
  83687. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  83688. });
  83689. }
  83690. else {
  83691. texture._isRGBD = true;
  83692. texture.invertY = true;
  83693. // In case of missing support, applies the same patch than DDS files.
  83694. if (generateNonLODTextures) {
  83695. var mipSlices = 3;
  83696. var scale = texture._lodGenerationScale;
  83697. var offset = texture._lodGenerationOffset;
  83698. for (var i = 0; i < mipSlices; i++) {
  83699. //compute LOD from even spacing in smoothness (matching shader calculation)
  83700. var smoothness = i / (mipSlices - 1);
  83701. var roughness = 1 - smoothness;
  83702. var minLODIndex = offset; // roughness = 0
  83703. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  83704. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  83705. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  83706. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  83707. glTextureFromLod.isCube = true;
  83708. glTextureFromLod.invertY = true;
  83709. glTextureFromLod.generateMipMaps = false;
  83710. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  83711. // Wrap in a base texture for easy binding.
  83712. var lodTexture = new BABYLON.BaseTexture(null);
  83713. lodTexture.isCube = true;
  83714. lodTexture._texture = glTextureFromLod;
  83715. lodTextures[mipmapIndex] = lodTexture;
  83716. switch (i) {
  83717. case 0:
  83718. texture._lodTextureLow = lodTexture;
  83719. break;
  83720. case 1:
  83721. texture._lodTextureMid = lodTexture;
  83722. break;
  83723. case 2:
  83724. texture._lodTextureHigh = lodTexture;
  83725. break;
  83726. }
  83727. }
  83728. }
  83729. }
  83730. var promises = [];
  83731. var _loop_3 = function (i) {
  83732. var _loop_4 = function (face) {
  83733. // Constructs an image element from image data
  83734. var bytes = imageData[i][face];
  83735. var blob = new Blob([bytes], { type: 'image/png' });
  83736. var url = URL.createObjectURL(blob);
  83737. var image = new Image();
  83738. image.src = url;
  83739. // Enqueue promise to upload to the texture.
  83740. var promise = new Promise(function (resolve, reject) {
  83741. image.onload = function () {
  83742. if (expandTexture) {
  83743. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83744. reject(message);
  83745. }, image);
  83746. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83747. // Uncompress the data to a RTT
  83748. rgbdPostProcess.onApply = function (effect) {
  83749. effect._bindTexture("textureSampler", tempTexture_1);
  83750. effect.setFloat2("scale", 1, 1);
  83751. };
  83752. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83753. // Cleanup
  83754. engine.restoreDefaultFramebuffer();
  83755. tempTexture_1.dispose();
  83756. window.URL.revokeObjectURL(url);
  83757. resolve();
  83758. });
  83759. }
  83760. else {
  83761. engine._uploadImageToTexture(texture, image, face, i);
  83762. // Upload the face to the non lod texture support
  83763. if (generateNonLODTextures) {
  83764. var lodTexture = lodTextures[i];
  83765. if (lodTexture) {
  83766. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  83767. }
  83768. }
  83769. resolve();
  83770. }
  83771. };
  83772. image.onerror = function (error) {
  83773. reject(error);
  83774. };
  83775. });
  83776. promises.push(promise);
  83777. };
  83778. // All faces
  83779. for (var face = 0; face < 6; face++) {
  83780. _loop_4(face);
  83781. }
  83782. };
  83783. // All mipmaps up to provided number of images
  83784. for (var i = 0; i < imageData.length; i++) {
  83785. _loop_3(i);
  83786. }
  83787. // Fill remaining mipmaps with black textures.
  83788. if (imageData.length < mipmapsCount) {
  83789. var data = void 0;
  83790. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  83791. var dataLength = size * size * 4;
  83792. switch (texture.type) {
  83793. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  83794. data = new Uint8Array(dataLength);
  83795. break;
  83796. }
  83797. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  83798. data = new Uint16Array(dataLength);
  83799. break;
  83800. }
  83801. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  83802. data = new Float32Array(dataLength);
  83803. break;
  83804. }
  83805. }
  83806. for (var i = imageData.length; i < mipmapsCount; i++) {
  83807. for (var face = 0; face < 6; face++) {
  83808. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  83809. }
  83810. }
  83811. }
  83812. // Once all done, finishes the cleanup and return
  83813. return Promise.all(promises).then(function () {
  83814. // Release temp RTT.
  83815. if (cubeRtt) {
  83816. engine._releaseFramebufferObjects(cubeRtt);
  83817. cubeRtt._swapAndDie(texture);
  83818. }
  83819. // Release temp Post Process.
  83820. if (rgbdPostProcess) {
  83821. rgbdPostProcess.dispose();
  83822. }
  83823. // Flag internal texture as ready in case they are in use.
  83824. if (generateNonLODTextures) {
  83825. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83826. texture._lodTextureHigh._texture.isReady = true;
  83827. }
  83828. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83829. texture._lodTextureMid._texture.isReady = true;
  83830. }
  83831. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83832. texture._lodTextureLow._texture.isReady = true;
  83833. }
  83834. }
  83835. });
  83836. };
  83837. /**
  83838. * Uploads spherical polynomials information to the texture.
  83839. * @param texture defines the texture we are trying to upload the information to
  83840. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83841. */
  83842. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83843. if (info.version !== 1) {
  83844. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83845. }
  83846. var irradianceInfo = info.irradiance;
  83847. if (!irradianceInfo) {
  83848. return;
  83849. }
  83850. var sp = new BABYLON.SphericalPolynomial();
  83851. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83852. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83853. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83854. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83855. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83856. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83857. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83858. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83859. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83860. texture._sphericalPolynomial = sp;
  83861. };
  83862. /**
  83863. * Magic number identifying the env file.
  83864. */
  83865. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83866. return EnvironmentTextureTools;
  83867. }());
  83868. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83869. })(BABYLON || (BABYLON = {}));
  83870. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83871. var BABYLON;
  83872. (function (BABYLON) {
  83873. /**
  83874. * This represents a texture coming from an HDR input.
  83875. *
  83876. * The only supported format is currently panorama picture stored in RGBE format.
  83877. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83878. */
  83879. var HDRCubeTexture = /** @class */ (function (_super) {
  83880. __extends(HDRCubeTexture, _super);
  83881. /**
  83882. * Instantiates an HDRTexture from the following parameters.
  83883. *
  83884. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83885. * @param scene The scene the texture will be used in
  83886. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83887. * @param noMipmap Forces to not generate the mipmap if true
  83888. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83889. * @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)
  83890. * @param reserved Reserved flag for internal use.
  83891. */
  83892. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83893. if (noMipmap === void 0) { noMipmap = false; }
  83894. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83895. if (gammaSpace === void 0) { gammaSpace = false; }
  83896. if (reserved === void 0) { reserved = false; }
  83897. if (onLoad === void 0) { onLoad = null; }
  83898. if (onError === void 0) { onError = null; }
  83899. var _this = _super.call(this, scene) || this;
  83900. _this._generateHarmonics = true;
  83901. _this._onLoad = null;
  83902. _this._onError = null;
  83903. /**
  83904. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83905. */
  83906. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83907. _this._isBlocking = true;
  83908. _this._rotationY = 0;
  83909. /**
  83910. * Gets or sets the center of the bounding box associated with the cube texture
  83911. * It must define where the camera used to render the texture was set
  83912. */
  83913. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83914. if (!url) {
  83915. return _this;
  83916. }
  83917. _this.name = url;
  83918. _this.url = url;
  83919. _this.hasAlpha = false;
  83920. _this.isCube = true;
  83921. _this._textureMatrix = BABYLON.Matrix.Identity();
  83922. _this._onLoad = onLoad;
  83923. _this._onError = onError;
  83924. _this.gammaSpace = gammaSpace;
  83925. _this._noMipmap = noMipmap;
  83926. _this._size = size;
  83927. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83928. if (!_this._texture) {
  83929. if (!scene.useDelayedTextureLoading) {
  83930. _this.loadTexture();
  83931. }
  83932. else {
  83933. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83934. }
  83935. }
  83936. return _this;
  83937. }
  83938. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83939. /**
  83940. * Gets wether or not the texture is blocking during loading.
  83941. */
  83942. get: function () {
  83943. return this._isBlocking;
  83944. },
  83945. /**
  83946. * Sets wether or not the texture is blocking during loading.
  83947. */
  83948. set: function (value) {
  83949. this._isBlocking = value;
  83950. },
  83951. enumerable: true,
  83952. configurable: true
  83953. });
  83954. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83955. /**
  83956. * Gets texture matrix rotation angle around Y axis radians.
  83957. */
  83958. get: function () {
  83959. return this._rotationY;
  83960. },
  83961. /**
  83962. * Sets texture matrix rotation angle around Y axis in radians.
  83963. */
  83964. set: function (value) {
  83965. this._rotationY = value;
  83966. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83967. },
  83968. enumerable: true,
  83969. configurable: true
  83970. });
  83971. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83972. get: function () {
  83973. return this._boundingBoxSize;
  83974. },
  83975. /**
  83976. * Gets or sets the size of the bounding box associated with the cube texture
  83977. * When defined, the cubemap will switch to local mode
  83978. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83979. * @example https://www.babylonjs-playground.com/#RNASML
  83980. */
  83981. set: function (value) {
  83982. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83983. return;
  83984. }
  83985. this._boundingBoxSize = value;
  83986. var scene = this.getScene();
  83987. if (scene) {
  83988. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83989. }
  83990. },
  83991. enumerable: true,
  83992. configurable: true
  83993. });
  83994. /**
  83995. * Occurs when the file is raw .hdr file.
  83996. */
  83997. HDRCubeTexture.prototype.loadTexture = function () {
  83998. var _this = this;
  83999. var callback = function (buffer) {
  84000. _this.lodGenerationOffset = 0.0;
  84001. _this.lodGenerationScale = 0.8;
  84002. var scene = _this.getScene();
  84003. if (!scene) {
  84004. return null;
  84005. }
  84006. // Extract the raw linear data.
  84007. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  84008. // Generate harmonics if needed.
  84009. if (_this._generateHarmonics) {
  84010. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  84011. _this.sphericalPolynomial = sphericalPolynomial;
  84012. }
  84013. var results = [];
  84014. var byteArray = null;
  84015. // Push each faces.
  84016. for (var j = 0; j < 6; j++) {
  84017. // Create uintarray fallback.
  84018. if (!scene.getEngine().getCaps().textureFloat) {
  84019. // 3 channels of 1 bytes per pixel in bytes.
  84020. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  84021. byteArray = new Uint8Array(byteBuffer);
  84022. }
  84023. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  84024. // If special cases.
  84025. if (_this.gammaSpace || byteArray) {
  84026. for (var i = 0; i < _this._size * _this._size; i++) {
  84027. // Put in gamma space if requested.
  84028. if (_this.gammaSpace) {
  84029. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  84030. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  84031. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  84032. }
  84033. // Convert to int texture for fallback.
  84034. if (byteArray) {
  84035. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  84036. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  84037. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  84038. // May use luminance instead if the result is not accurate.
  84039. var max = Math.max(Math.max(r, g), b);
  84040. if (max > 255) {
  84041. var scale = 255 / max;
  84042. r *= scale;
  84043. g *= scale;
  84044. b *= scale;
  84045. }
  84046. byteArray[(i * 3) + 0] = r;
  84047. byteArray[(i * 3) + 1] = g;
  84048. byteArray[(i * 3) + 2] = b;
  84049. }
  84050. }
  84051. }
  84052. if (byteArray) {
  84053. results.push(byteArray);
  84054. }
  84055. else {
  84056. results.push(dataFace);
  84057. }
  84058. }
  84059. return results;
  84060. };
  84061. var scene = this.getScene();
  84062. if (scene) {
  84063. 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);
  84064. }
  84065. };
  84066. HDRCubeTexture.prototype.clone = function () {
  84067. var scene = this.getScene();
  84068. if (!scene) {
  84069. return this;
  84070. }
  84071. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  84072. // Base texture
  84073. newTexture.level = this.level;
  84074. newTexture.wrapU = this.wrapU;
  84075. newTexture.wrapV = this.wrapV;
  84076. newTexture.coordinatesIndex = this.coordinatesIndex;
  84077. newTexture.coordinatesMode = this.coordinatesMode;
  84078. return newTexture;
  84079. };
  84080. // Methods
  84081. HDRCubeTexture.prototype.delayLoad = function () {
  84082. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84083. return;
  84084. }
  84085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84086. this._texture = this._getFromCache(this.url, this._noMipmap);
  84087. if (!this._texture) {
  84088. this.loadTexture();
  84089. }
  84090. };
  84091. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84092. return this._textureMatrix;
  84093. };
  84094. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84095. this._textureMatrix = value;
  84096. };
  84097. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84098. var texture = null;
  84099. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84100. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84101. texture.name = parsedTexture.name;
  84102. texture.hasAlpha = parsedTexture.hasAlpha;
  84103. texture.level = parsedTexture.level;
  84104. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84105. texture.isBlocking = parsedTexture.isBlocking;
  84106. }
  84107. if (texture) {
  84108. if (parsedTexture.boundingBoxPosition) {
  84109. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84110. }
  84111. if (parsedTexture.boundingBoxSize) {
  84112. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84113. }
  84114. if (parsedTexture.rotationY) {
  84115. texture.rotationY = parsedTexture.rotationY;
  84116. }
  84117. }
  84118. return texture;
  84119. };
  84120. HDRCubeTexture.prototype.serialize = function () {
  84121. if (!this.name) {
  84122. return null;
  84123. }
  84124. var serializationObject = {};
  84125. serializationObject.name = this.name;
  84126. serializationObject.hasAlpha = this.hasAlpha;
  84127. serializationObject.isCube = true;
  84128. serializationObject.level = this.level;
  84129. serializationObject.size = this._size;
  84130. serializationObject.coordinatesMode = this.coordinatesMode;
  84131. serializationObject.useInGammaSpace = this.gammaSpace;
  84132. serializationObject.generateHarmonics = this._generateHarmonics;
  84133. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84134. serializationObject.noMipmap = this._noMipmap;
  84135. serializationObject.isBlocking = this._isBlocking;
  84136. serializationObject.rotationY = this._rotationY;
  84137. return serializationObject;
  84138. };
  84139. HDRCubeTexture._facesMapping = [
  84140. "right",
  84141. "left",
  84142. "up",
  84143. "down",
  84144. "front",
  84145. "back"
  84146. ];
  84147. return HDRCubeTexture;
  84148. }(BABYLON.BaseTexture));
  84149. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84150. })(BABYLON || (BABYLON = {}));
  84151. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84152. var BABYLON;
  84153. (function (BABYLON) {
  84154. var IndexedVector2 = /** @class */ (function (_super) {
  84155. __extends(IndexedVector2, _super);
  84156. function IndexedVector2(original, index) {
  84157. var _this = _super.call(this, original.x, original.y) || this;
  84158. _this.index = index;
  84159. return _this;
  84160. }
  84161. return IndexedVector2;
  84162. }(BABYLON.Vector2));
  84163. var PolygonPoints = /** @class */ (function () {
  84164. function PolygonPoints() {
  84165. this.elements = new Array();
  84166. }
  84167. PolygonPoints.prototype.add = function (originalPoints) {
  84168. var _this = this;
  84169. var result = new Array();
  84170. originalPoints.forEach(function (point) {
  84171. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84172. var newPoint = new IndexedVector2(point, _this.elements.length);
  84173. result.push(newPoint);
  84174. _this.elements.push(newPoint);
  84175. }
  84176. });
  84177. return result;
  84178. };
  84179. PolygonPoints.prototype.computeBounds = function () {
  84180. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84181. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84182. this.elements.forEach(function (point) {
  84183. // x
  84184. if (point.x < lmin.x) {
  84185. lmin.x = point.x;
  84186. }
  84187. else if (point.x > lmax.x) {
  84188. lmax.x = point.x;
  84189. }
  84190. // y
  84191. if (point.y < lmin.y) {
  84192. lmin.y = point.y;
  84193. }
  84194. else if (point.y > lmax.y) {
  84195. lmax.y = point.y;
  84196. }
  84197. });
  84198. return {
  84199. min: lmin,
  84200. max: lmax,
  84201. width: lmax.x - lmin.x,
  84202. height: lmax.y - lmin.y
  84203. };
  84204. };
  84205. return PolygonPoints;
  84206. }());
  84207. var Polygon = /** @class */ (function () {
  84208. function Polygon() {
  84209. }
  84210. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84211. return [
  84212. new BABYLON.Vector2(xmin, ymin),
  84213. new BABYLON.Vector2(xmax, ymin),
  84214. new BABYLON.Vector2(xmax, ymax),
  84215. new BABYLON.Vector2(xmin, ymax)
  84216. ];
  84217. };
  84218. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84219. if (cx === void 0) { cx = 0; }
  84220. if (cy === void 0) { cy = 0; }
  84221. if (numberOfSides === void 0) { numberOfSides = 32; }
  84222. var result = new Array();
  84223. var angle = 0;
  84224. var increment = (Math.PI * 2) / numberOfSides;
  84225. for (var i = 0; i < numberOfSides; i++) {
  84226. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84227. angle -= increment;
  84228. }
  84229. return result;
  84230. };
  84231. Polygon.Parse = function (input) {
  84232. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84233. var i, result = [];
  84234. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84235. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84236. }
  84237. return result;
  84238. };
  84239. Polygon.StartingAt = function (x, y) {
  84240. return BABYLON.Path2.StartingAt(x, y);
  84241. };
  84242. return Polygon;
  84243. }());
  84244. BABYLON.Polygon = Polygon;
  84245. var PolygonMeshBuilder = /** @class */ (function () {
  84246. function PolygonMeshBuilder(name, contours, scene) {
  84247. this._points = new PolygonPoints();
  84248. this._outlinepoints = new PolygonPoints();
  84249. this._holes = new Array();
  84250. this._epoints = new Array();
  84251. this._eholes = new Array();
  84252. this._name = name;
  84253. this._scene = scene;
  84254. var points;
  84255. if (contours instanceof BABYLON.Path2) {
  84256. points = contours.getPoints();
  84257. }
  84258. else {
  84259. points = contours;
  84260. }
  84261. this._addToepoint(points);
  84262. this._points.add(points);
  84263. this._outlinepoints.add(points);
  84264. if (typeof earcut === 'undefined') {
  84265. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84266. }
  84267. }
  84268. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84269. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84270. var p = points_1[_i];
  84271. this._epoints.push(p.x, p.y);
  84272. }
  84273. };
  84274. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84275. this._points.add(hole);
  84276. var holepoints = new PolygonPoints();
  84277. holepoints.add(hole);
  84278. this._holes.push(holepoints);
  84279. this._eholes.push(this._epoints.length / 2);
  84280. this._addToepoint(hole);
  84281. return this;
  84282. };
  84283. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84284. var _this = this;
  84285. if (updatable === void 0) { updatable = false; }
  84286. if (depth === void 0) { depth = 0; }
  84287. var result = new BABYLON.Mesh(this._name, this._scene);
  84288. var normals = new Array();
  84289. var positions = new Array();
  84290. var uvs = new Array();
  84291. var bounds = this._points.computeBounds();
  84292. this._points.elements.forEach(function (p) {
  84293. normals.push(0, 1.0, 0);
  84294. positions.push(p.x, 0, p.y);
  84295. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84296. });
  84297. var indices = new Array();
  84298. var res = earcut(this._epoints, this._eholes, 2);
  84299. for (var i = 0; i < res.length; i++) {
  84300. indices.push(res[i]);
  84301. }
  84302. if (depth > 0) {
  84303. var positionscount = (positions.length / 3); //get the current pointcount
  84304. this._points.elements.forEach(function (p) {
  84305. normals.push(0, -1.0, 0);
  84306. positions.push(p.x, -depth, p.y);
  84307. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84308. });
  84309. var totalCount = indices.length;
  84310. for (var i = 0; i < totalCount; i += 3) {
  84311. var i0 = indices[i + 0];
  84312. var i1 = indices[i + 1];
  84313. var i2 = indices[i + 2];
  84314. indices.push(i2 + positionscount);
  84315. indices.push(i1 + positionscount);
  84316. indices.push(i0 + positionscount);
  84317. }
  84318. //Add the sides
  84319. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84320. this._holes.forEach(function (hole) {
  84321. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84322. });
  84323. }
  84324. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84325. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84326. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84327. result.setIndices(indices);
  84328. return result;
  84329. };
  84330. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84331. var StartIndex = positions.length / 3;
  84332. var ulength = 0;
  84333. for (var i = 0; i < points.elements.length; i++) {
  84334. var p = points.elements[i];
  84335. var p1;
  84336. if ((i + 1) > points.elements.length - 1) {
  84337. p1 = points.elements[0];
  84338. }
  84339. else {
  84340. p1 = points.elements[i + 1];
  84341. }
  84342. positions.push(p.x, 0, p.y);
  84343. positions.push(p.x, -depth, p.y);
  84344. positions.push(p1.x, 0, p1.y);
  84345. positions.push(p1.x, -depth, p1.y);
  84346. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84347. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84348. var v3 = v2.subtract(v1);
  84349. var v4 = new BABYLON.Vector3(0, 1, 0);
  84350. var vn = BABYLON.Vector3.Cross(v3, v4);
  84351. vn = vn.normalize();
  84352. uvs.push(ulength / bounds.width, 0);
  84353. uvs.push(ulength / bounds.width, 1);
  84354. ulength += v3.length();
  84355. uvs.push((ulength / bounds.width), 0);
  84356. uvs.push((ulength / bounds.width), 1);
  84357. if (!flip) {
  84358. normals.push(-vn.x, -vn.y, -vn.z);
  84359. normals.push(-vn.x, -vn.y, -vn.z);
  84360. normals.push(-vn.x, -vn.y, -vn.z);
  84361. normals.push(-vn.x, -vn.y, -vn.z);
  84362. indices.push(StartIndex);
  84363. indices.push(StartIndex + 1);
  84364. indices.push(StartIndex + 2);
  84365. indices.push(StartIndex + 1);
  84366. indices.push(StartIndex + 3);
  84367. indices.push(StartIndex + 2);
  84368. }
  84369. else {
  84370. normals.push(vn.x, vn.y, vn.z);
  84371. normals.push(vn.x, vn.y, vn.z);
  84372. normals.push(vn.x, vn.y, vn.z);
  84373. normals.push(vn.x, vn.y, vn.z);
  84374. indices.push(StartIndex);
  84375. indices.push(StartIndex + 2);
  84376. indices.push(StartIndex + 1);
  84377. indices.push(StartIndex + 1);
  84378. indices.push(StartIndex + 2);
  84379. indices.push(StartIndex + 3);
  84380. }
  84381. StartIndex += 4;
  84382. }
  84383. ;
  84384. };
  84385. return PolygonMeshBuilder;
  84386. }());
  84387. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84388. })(BABYLON || (BABYLON = {}));
  84389. //# sourceMappingURL=babylon.polygonMesh.js.map
  84390. var BABYLON;
  84391. (function (BABYLON) {
  84392. // Unique ID when we import meshes from Babylon to CSG
  84393. var currentCSGMeshId = 0;
  84394. // # class Vertex
  84395. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84396. // one to provide additional features like texture coordinates and vertex
  84397. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84398. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84399. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84400. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84401. // is not used anywhere else.
  84402. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84403. var Vertex = /** @class */ (function () {
  84404. function Vertex(pos, normal, uv) {
  84405. this.pos = pos;
  84406. this.normal = normal;
  84407. this.uv = uv;
  84408. }
  84409. Vertex.prototype.clone = function () {
  84410. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84411. };
  84412. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84413. // orientation of a polygon is flipped.
  84414. Vertex.prototype.flip = function () {
  84415. this.normal = this.normal.scale(-1);
  84416. };
  84417. // Create a new vertex between this vertex and `other` by linearly
  84418. // interpolating all properties using a parameter of `t`. Subclasses should
  84419. // override this to interpolate additional properties.
  84420. Vertex.prototype.interpolate = function (other, t) {
  84421. 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));
  84422. };
  84423. return Vertex;
  84424. }());
  84425. // # class Plane
  84426. // Represents a plane in 3D space.
  84427. var Plane = /** @class */ (function () {
  84428. function Plane(normal, w) {
  84429. this.normal = normal;
  84430. this.w = w;
  84431. }
  84432. Plane.FromPoints = function (a, b, c) {
  84433. var v0 = c.subtract(a);
  84434. var v1 = b.subtract(a);
  84435. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84436. return null;
  84437. }
  84438. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84439. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84440. };
  84441. Plane.prototype.clone = function () {
  84442. return new Plane(this.normal.clone(), this.w);
  84443. };
  84444. Plane.prototype.flip = function () {
  84445. this.normal.scaleInPlace(-1);
  84446. this.w = -this.w;
  84447. };
  84448. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84449. // fragments in the appropriate lists. Coplanar polygons go into either
  84450. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84451. // respect to this plane. Polygons in front or in back of this plane go into
  84452. // either `front` or `back`.
  84453. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84454. var COPLANAR = 0;
  84455. var FRONT = 1;
  84456. var BACK = 2;
  84457. var SPANNING = 3;
  84458. // Classify each point as well as the entire polygon into one of the above
  84459. // four classes.
  84460. var polygonType = 0;
  84461. var types = [];
  84462. var i;
  84463. var t;
  84464. for (i = 0; i < polygon.vertices.length; i++) {
  84465. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84466. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84467. polygonType |= type;
  84468. types.push(type);
  84469. }
  84470. // Put the polygon in the correct list, splitting it when necessary.
  84471. switch (polygonType) {
  84472. case COPLANAR:
  84473. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84474. break;
  84475. case FRONT:
  84476. front.push(polygon);
  84477. break;
  84478. case BACK:
  84479. back.push(polygon);
  84480. break;
  84481. case SPANNING:
  84482. var f = [], b = [];
  84483. for (i = 0; i < polygon.vertices.length; i++) {
  84484. var j = (i + 1) % polygon.vertices.length;
  84485. var ti = types[i], tj = types[j];
  84486. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84487. if (ti !== BACK)
  84488. f.push(vi);
  84489. if (ti !== FRONT)
  84490. b.push(ti !== BACK ? vi.clone() : vi);
  84491. if ((ti | tj) === SPANNING) {
  84492. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84493. var v = vi.interpolate(vj, t);
  84494. f.push(v);
  84495. b.push(v.clone());
  84496. }
  84497. }
  84498. var poly;
  84499. if (f.length >= 3) {
  84500. poly = new Polygon(f, polygon.shared);
  84501. if (poly.plane)
  84502. front.push(poly);
  84503. }
  84504. if (b.length >= 3) {
  84505. poly = new Polygon(b, polygon.shared);
  84506. if (poly.plane)
  84507. back.push(poly);
  84508. }
  84509. break;
  84510. }
  84511. };
  84512. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84513. // point is on the plane.
  84514. Plane.EPSILON = 1e-5;
  84515. return Plane;
  84516. }());
  84517. // # class Polygon
  84518. // Represents a convex polygon. The vertices used to initialize a polygon must
  84519. // be coplanar and form a convex loop.
  84520. //
  84521. // Each convex polygon has a `shared` property, which is shared between all
  84522. // polygons that are clones of each other or were split from the same polygon.
  84523. // This can be used to define per-polygon properties (such as surface color).
  84524. var Polygon = /** @class */ (function () {
  84525. function Polygon(vertices, shared) {
  84526. this.vertices = vertices;
  84527. this.shared = shared;
  84528. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84529. }
  84530. Polygon.prototype.clone = function () {
  84531. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84532. return new Polygon(vertices, this.shared);
  84533. };
  84534. Polygon.prototype.flip = function () {
  84535. this.vertices.reverse().map(function (v) { v.flip(); });
  84536. this.plane.flip();
  84537. };
  84538. return Polygon;
  84539. }());
  84540. // # class Node
  84541. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84542. // by picking a polygon to split along. That polygon (and all other coplanar
  84543. // polygons) are added directly to that node and the other polygons are added to
  84544. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84545. // no distinction between internal and leaf nodes.
  84546. var Node = /** @class */ (function () {
  84547. function Node(polygons) {
  84548. this.plane = null;
  84549. this.front = null;
  84550. this.back = null;
  84551. this.polygons = new Array();
  84552. if (polygons) {
  84553. this.build(polygons);
  84554. }
  84555. }
  84556. Node.prototype.clone = function () {
  84557. var node = new Node();
  84558. node.plane = this.plane && this.plane.clone();
  84559. node.front = this.front && this.front.clone();
  84560. node.back = this.back && this.back.clone();
  84561. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84562. return node;
  84563. };
  84564. // Convert solid space to empty space and empty space to solid space.
  84565. Node.prototype.invert = function () {
  84566. for (var i = 0; i < this.polygons.length; i++) {
  84567. this.polygons[i].flip();
  84568. }
  84569. if (this.plane) {
  84570. this.plane.flip();
  84571. }
  84572. if (this.front) {
  84573. this.front.invert();
  84574. }
  84575. if (this.back) {
  84576. this.back.invert();
  84577. }
  84578. var temp = this.front;
  84579. this.front = this.back;
  84580. this.back = temp;
  84581. };
  84582. // Recursively remove all polygons in `polygons` that are inside this BSP
  84583. // tree.
  84584. Node.prototype.clipPolygons = function (polygons) {
  84585. if (!this.plane)
  84586. return polygons.slice();
  84587. var front = new Array(), back = new Array();
  84588. for (var i = 0; i < polygons.length; i++) {
  84589. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84590. }
  84591. if (this.front) {
  84592. front = this.front.clipPolygons(front);
  84593. }
  84594. if (this.back) {
  84595. back = this.back.clipPolygons(back);
  84596. }
  84597. else {
  84598. back = [];
  84599. }
  84600. return front.concat(back);
  84601. };
  84602. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84603. // `bsp`.
  84604. Node.prototype.clipTo = function (bsp) {
  84605. this.polygons = bsp.clipPolygons(this.polygons);
  84606. if (this.front)
  84607. this.front.clipTo(bsp);
  84608. if (this.back)
  84609. this.back.clipTo(bsp);
  84610. };
  84611. // Return a list of all polygons in this BSP tree.
  84612. Node.prototype.allPolygons = function () {
  84613. var polygons = this.polygons.slice();
  84614. if (this.front)
  84615. polygons = polygons.concat(this.front.allPolygons());
  84616. if (this.back)
  84617. polygons = polygons.concat(this.back.allPolygons());
  84618. return polygons;
  84619. };
  84620. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84621. // new polygons are filtered down to the bottom of the tree and become new
  84622. // nodes there. Each set of polygons is partitioned using the first polygon
  84623. // (no heuristic is used to pick a good split).
  84624. Node.prototype.build = function (polygons) {
  84625. if (!polygons.length)
  84626. return;
  84627. if (!this.plane)
  84628. this.plane = polygons[0].plane.clone();
  84629. var front = new Array(), back = new Array();
  84630. for (var i = 0; i < polygons.length; i++) {
  84631. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84632. }
  84633. if (front.length) {
  84634. if (!this.front)
  84635. this.front = new Node();
  84636. this.front.build(front);
  84637. }
  84638. if (back.length) {
  84639. if (!this.back)
  84640. this.back = new Node();
  84641. this.back.build(back);
  84642. }
  84643. };
  84644. return Node;
  84645. }());
  84646. var CSG = /** @class */ (function () {
  84647. function CSG() {
  84648. this.polygons = new Array();
  84649. }
  84650. // Convert BABYLON.Mesh to BABYLON.CSG
  84651. CSG.FromMesh = function (mesh) {
  84652. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84653. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84654. if (mesh instanceof BABYLON.Mesh) {
  84655. mesh.computeWorldMatrix(true);
  84656. matrix = mesh.getWorldMatrix();
  84657. meshPosition = mesh.position.clone();
  84658. meshRotation = mesh.rotation.clone();
  84659. if (mesh.rotationQuaternion) {
  84660. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84661. }
  84662. meshScaling = mesh.scaling.clone();
  84663. }
  84664. else {
  84665. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84666. }
  84667. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84668. var subMeshes = mesh.subMeshes;
  84669. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84670. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84671. vertices = [];
  84672. for (var j = 0; j < 3; j++) {
  84673. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84674. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84675. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84676. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84677. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84678. vertex = new Vertex(position, normal, uv);
  84679. vertices.push(vertex);
  84680. }
  84681. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84682. // To handle the case of degenerated triangle
  84683. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84684. if (polygon.plane)
  84685. polygons.push(polygon);
  84686. }
  84687. }
  84688. var csg = CSG.FromPolygons(polygons);
  84689. csg.matrix = matrix;
  84690. csg.position = meshPosition;
  84691. csg.rotation = meshRotation;
  84692. csg.scaling = meshScaling;
  84693. csg.rotationQuaternion = meshRotationQuaternion;
  84694. currentCSGMeshId++;
  84695. return csg;
  84696. };
  84697. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84698. CSG.FromPolygons = function (polygons) {
  84699. var csg = new CSG();
  84700. csg.polygons = polygons;
  84701. return csg;
  84702. };
  84703. CSG.prototype.clone = function () {
  84704. var csg = new CSG();
  84705. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84706. csg.copyTransformAttributes(this);
  84707. return csg;
  84708. };
  84709. CSG.prototype.union = function (csg) {
  84710. var a = new Node(this.clone().polygons);
  84711. var b = new Node(csg.clone().polygons);
  84712. a.clipTo(b);
  84713. b.clipTo(a);
  84714. b.invert();
  84715. b.clipTo(a);
  84716. b.invert();
  84717. a.build(b.allPolygons());
  84718. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84719. };
  84720. CSG.prototype.unionInPlace = function (csg) {
  84721. var a = new Node(this.polygons);
  84722. var b = new Node(csg.polygons);
  84723. a.clipTo(b);
  84724. b.clipTo(a);
  84725. b.invert();
  84726. b.clipTo(a);
  84727. b.invert();
  84728. a.build(b.allPolygons());
  84729. this.polygons = a.allPolygons();
  84730. };
  84731. CSG.prototype.subtract = function (csg) {
  84732. var a = new Node(this.clone().polygons);
  84733. var b = new Node(csg.clone().polygons);
  84734. a.invert();
  84735. a.clipTo(b);
  84736. b.clipTo(a);
  84737. b.invert();
  84738. b.clipTo(a);
  84739. b.invert();
  84740. a.build(b.allPolygons());
  84741. a.invert();
  84742. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84743. };
  84744. CSG.prototype.subtractInPlace = function (csg) {
  84745. var a = new Node(this.polygons);
  84746. var b = new Node(csg.polygons);
  84747. a.invert();
  84748. a.clipTo(b);
  84749. b.clipTo(a);
  84750. b.invert();
  84751. b.clipTo(a);
  84752. b.invert();
  84753. a.build(b.allPolygons());
  84754. a.invert();
  84755. this.polygons = a.allPolygons();
  84756. };
  84757. CSG.prototype.intersect = function (csg) {
  84758. var a = new Node(this.clone().polygons);
  84759. var b = new Node(csg.clone().polygons);
  84760. a.invert();
  84761. b.clipTo(a);
  84762. b.invert();
  84763. a.clipTo(b);
  84764. b.clipTo(a);
  84765. a.build(b.allPolygons());
  84766. a.invert();
  84767. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84768. };
  84769. CSG.prototype.intersectInPlace = function (csg) {
  84770. var a = new Node(this.polygons);
  84771. var b = new Node(csg.polygons);
  84772. a.invert();
  84773. b.clipTo(a);
  84774. b.invert();
  84775. a.clipTo(b);
  84776. b.clipTo(a);
  84777. a.build(b.allPolygons());
  84778. a.invert();
  84779. this.polygons = a.allPolygons();
  84780. };
  84781. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84782. // not modified.
  84783. CSG.prototype.inverse = function () {
  84784. var csg = this.clone();
  84785. csg.inverseInPlace();
  84786. return csg;
  84787. };
  84788. CSG.prototype.inverseInPlace = function () {
  84789. this.polygons.map(function (p) { p.flip(); });
  84790. };
  84791. // This is used to keep meshes transformations so they can be restored
  84792. // when we build back a Babylon Mesh
  84793. // NB : All CSG operations are performed in world coordinates
  84794. CSG.prototype.copyTransformAttributes = function (csg) {
  84795. this.matrix = csg.matrix;
  84796. this.position = csg.position;
  84797. this.rotation = csg.rotation;
  84798. this.scaling = csg.scaling;
  84799. this.rotationQuaternion = csg.rotationQuaternion;
  84800. return this;
  84801. };
  84802. // Build Raw mesh from CSG
  84803. // Coordinates here are in world space
  84804. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84805. var matrix = this.matrix.clone();
  84806. matrix.invert();
  84807. 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;
  84808. if (keepSubMeshes) {
  84809. // Sort Polygons, since subMeshes are indices range
  84810. polygons.sort(function (a, b) {
  84811. if (a.shared.meshId === b.shared.meshId) {
  84812. return a.shared.subMeshId - b.shared.subMeshId;
  84813. }
  84814. else {
  84815. return a.shared.meshId - b.shared.meshId;
  84816. }
  84817. });
  84818. }
  84819. for (var i = 0, il = polygons.length; i < il; i++) {
  84820. polygon = polygons[i];
  84821. // Building SubMeshes
  84822. if (!subMesh_dict[polygon.shared.meshId]) {
  84823. subMesh_dict[polygon.shared.meshId] = {};
  84824. }
  84825. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84826. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84827. indexStart: +Infinity,
  84828. indexEnd: -Infinity,
  84829. materialIndex: polygon.shared.materialIndex
  84830. };
  84831. }
  84832. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84833. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84834. polygonIndices[0] = 0;
  84835. polygonIndices[1] = j - 1;
  84836. polygonIndices[2] = j;
  84837. for (var k = 0; k < 3; k++) {
  84838. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84839. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84840. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84841. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84842. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84843. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84844. // Check if 2 points can be merged
  84845. if (!(typeof vertex_idx !== 'undefined' &&
  84846. normals[vertex_idx * 3] === localNormal.x &&
  84847. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84848. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84849. uvs[vertex_idx * 2] === uv.x &&
  84850. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84851. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84852. uvs.push(uv.x, uv.y);
  84853. normals.push(normal.x, normal.y, normal.z);
  84854. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84855. }
  84856. indices.push(vertex_idx);
  84857. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84858. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84859. currentIndex++;
  84860. }
  84861. }
  84862. }
  84863. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84864. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84865. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84866. mesh.setIndices(indices, null);
  84867. if (keepSubMeshes) {
  84868. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84869. var materialIndexOffset = 0, materialMaxIndex;
  84870. mesh.subMeshes = new Array();
  84871. for (var m in subMesh_dict) {
  84872. materialMaxIndex = -1;
  84873. for (var sm in subMesh_dict[m]) {
  84874. subMesh_obj = subMesh_dict[m][sm];
  84875. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84876. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84877. }
  84878. materialIndexOffset += ++materialMaxIndex;
  84879. }
  84880. }
  84881. return mesh;
  84882. };
  84883. // Build Mesh from CSG taking material and transforms into account
  84884. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84885. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84886. mesh.material = material;
  84887. mesh.position.copyFrom(this.position);
  84888. mesh.rotation.copyFrom(this.rotation);
  84889. if (this.rotationQuaternion) {
  84890. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84891. }
  84892. mesh.scaling.copyFrom(this.scaling);
  84893. mesh.computeWorldMatrix(true);
  84894. return mesh;
  84895. };
  84896. return CSG;
  84897. }());
  84898. BABYLON.CSG = CSG;
  84899. })(BABYLON || (BABYLON = {}));
  84900. //# sourceMappingURL=babylon.csg.js.map
  84901. var BABYLON;
  84902. (function (BABYLON) {
  84903. var LensFlare = /** @class */ (function () {
  84904. function LensFlare(size, position, color, imgUrl, system) {
  84905. this.size = size;
  84906. this.position = position;
  84907. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84908. this.color = color || new BABYLON.Color3(1, 1, 1);
  84909. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84910. this._system = system;
  84911. system.lensFlares.push(this);
  84912. }
  84913. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84914. return new LensFlare(size, position, color, imgUrl, system);
  84915. };
  84916. LensFlare.prototype.dispose = function () {
  84917. if (this.texture) {
  84918. this.texture.dispose();
  84919. }
  84920. // Remove from scene
  84921. var index = this._system.lensFlares.indexOf(this);
  84922. this._system.lensFlares.splice(index, 1);
  84923. };
  84924. ;
  84925. return LensFlare;
  84926. }());
  84927. BABYLON.LensFlare = LensFlare;
  84928. })(BABYLON || (BABYLON = {}));
  84929. //# sourceMappingURL=babylon.lensFlare.js.map
  84930. var BABYLON;
  84931. (function (BABYLON) {
  84932. // Adds the parser to the scene parsers.
  84933. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84934. // Lens flares
  84935. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84936. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84937. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84938. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84939. container.lensFlareSystems.push(lf);
  84940. }
  84941. }
  84942. });
  84943. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84944. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84945. if (this.lensFlareSystems[index].name === name) {
  84946. return this.lensFlareSystems[index];
  84947. }
  84948. }
  84949. return null;
  84950. };
  84951. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84952. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84953. if (this.lensFlareSystems[index].id === id) {
  84954. return this.lensFlareSystems[index];
  84955. }
  84956. }
  84957. return null;
  84958. };
  84959. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84960. var index = this.lensFlareSystems.indexOf(toRemove);
  84961. if (index !== -1) {
  84962. this.lensFlareSystems.splice(index, 1);
  84963. }
  84964. return index;
  84965. };
  84966. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84967. this.lensFlareSystems.push(newLensFlareSystem);
  84968. };
  84969. /**
  84970. * Defines the lens flare scene component responsible to manage any lens flares
  84971. * in a given scene.
  84972. */
  84973. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84974. /**
  84975. * Creates a new instance of the component for the given scene
  84976. * @param scene Defines the scene to register the component in
  84977. */
  84978. function LensFlareSystemSceneComponent(scene) {
  84979. /**
  84980. * The component name helpfull to identify the component in the list of scene components.
  84981. */
  84982. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84983. this.scene = scene;
  84984. scene.lensFlareSystems = new Array();
  84985. }
  84986. /**
  84987. * Registers the component in a given scene
  84988. */
  84989. LensFlareSystemSceneComponent.prototype.register = function () {
  84990. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84991. };
  84992. /**
  84993. * Rebuilds the elements related to this component in case of
  84994. * context lost for instance.
  84995. */
  84996. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84997. // Nothing to do for lens flare
  84998. };
  84999. /**
  85000. * Adds all the element from the container to the scene
  85001. * @param container the container holding the elements
  85002. */
  85003. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  85004. var _this = this;
  85005. if (!container.lensFlareSystems) {
  85006. return;
  85007. }
  85008. container.lensFlareSystems.forEach(function (o) {
  85009. _this.scene.addLensFlareSystem(o);
  85010. });
  85011. };
  85012. /**
  85013. * Removes all the elements in the container from the scene
  85014. * @param container contains the elements to remove
  85015. */
  85016. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  85017. var _this = this;
  85018. if (!container.lensFlareSystems) {
  85019. return;
  85020. }
  85021. container.lensFlareSystems.forEach(function (o) {
  85022. _this.scene.removeLensFlareSystem(o);
  85023. });
  85024. };
  85025. /**
  85026. * Serializes the component data to the specified json object
  85027. * @param serializationObject The object to serialize to
  85028. */
  85029. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  85030. // Lens flares
  85031. serializationObject.lensFlareSystems = [];
  85032. var lensFlareSystems = this.scene.lensFlareSystems;
  85033. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  85034. var lensFlareSystem = lensFlareSystems_1[_i];
  85035. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  85036. }
  85037. };
  85038. /**
  85039. * Disposes the component and the associated ressources.
  85040. */
  85041. LensFlareSystemSceneComponent.prototype.dispose = function () {
  85042. var lensFlareSystems = this.scene.lensFlareSystems;
  85043. while (lensFlareSystems.length) {
  85044. lensFlareSystems[0].dispose();
  85045. }
  85046. };
  85047. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85048. // Lens flares
  85049. if (this.scene.lensFlaresEnabled) {
  85050. var lensFlareSystems = this.scene.lensFlareSystems;
  85051. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85052. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85053. var lensFlareSystem = lensFlareSystems_2[_i];
  85054. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85055. lensFlareSystem.render();
  85056. }
  85057. }
  85058. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85059. }
  85060. };
  85061. return LensFlareSystemSceneComponent;
  85062. }());
  85063. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85064. })(BABYLON || (BABYLON = {}));
  85065. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85066. var BABYLON;
  85067. (function (BABYLON) {
  85068. var LensFlareSystem = /** @class */ (function () {
  85069. function LensFlareSystem(name, emitter, scene) {
  85070. this.name = name;
  85071. this.lensFlares = new Array();
  85072. this.borderLimit = 300;
  85073. this.viewportBorder = 0;
  85074. this.layerMask = 0x0FFFFFFF;
  85075. this._vertexBuffers = {};
  85076. this._isEnabled = true;
  85077. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85078. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85079. if (!component) {
  85080. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85081. scene._addComponent(component);
  85082. }
  85083. this._emitter = emitter;
  85084. this.id = name;
  85085. scene.lensFlareSystems.push(this);
  85086. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85087. var engine = scene.getEngine();
  85088. // VBO
  85089. var vertices = [];
  85090. vertices.push(1, 1);
  85091. vertices.push(-1, 1);
  85092. vertices.push(-1, -1);
  85093. vertices.push(1, -1);
  85094. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85095. // Indices
  85096. var indices = [];
  85097. indices.push(0);
  85098. indices.push(1);
  85099. indices.push(2);
  85100. indices.push(0);
  85101. indices.push(2);
  85102. indices.push(3);
  85103. this._indexBuffer = engine.createIndexBuffer(indices);
  85104. // Effects
  85105. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85106. }
  85107. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85108. get: function () {
  85109. return this._isEnabled;
  85110. },
  85111. set: function (value) {
  85112. this._isEnabled = value;
  85113. },
  85114. enumerable: true,
  85115. configurable: true
  85116. });
  85117. LensFlareSystem.prototype.getScene = function () {
  85118. return this._scene;
  85119. };
  85120. LensFlareSystem.prototype.getEmitter = function () {
  85121. return this._emitter;
  85122. };
  85123. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85124. this._emitter = newEmitter;
  85125. };
  85126. LensFlareSystem.prototype.getEmitterPosition = function () {
  85127. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85128. };
  85129. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85130. var position = this.getEmitterPosition();
  85131. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85132. this._positionX = position.x;
  85133. this._positionY = position.y;
  85134. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85135. if (this.viewportBorder > 0) {
  85136. globalViewport.x -= this.viewportBorder;
  85137. globalViewport.y -= this.viewportBorder;
  85138. globalViewport.width += this.viewportBorder * 2;
  85139. globalViewport.height += this.viewportBorder * 2;
  85140. position.x += this.viewportBorder;
  85141. position.y += this.viewportBorder;
  85142. this._positionX += this.viewportBorder;
  85143. this._positionY += this.viewportBorder;
  85144. }
  85145. if (position.z > 0) {
  85146. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85147. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85148. return true;
  85149. }
  85150. return true;
  85151. }
  85152. return false;
  85153. };
  85154. LensFlareSystem.prototype._isVisible = function () {
  85155. if (!this._isEnabled || !this._scene.activeCamera) {
  85156. return false;
  85157. }
  85158. var emitterPosition = this.getEmitterPosition();
  85159. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85160. var distance = direction.length();
  85161. direction.normalize();
  85162. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85163. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85164. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85165. };
  85166. LensFlareSystem.prototype.render = function () {
  85167. if (!this._effect.isReady() || !this._scene.activeCamera)
  85168. return false;
  85169. var engine = this._scene.getEngine();
  85170. var viewport = this._scene.activeCamera.viewport;
  85171. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85172. // Position
  85173. if (!this.computeEffectivePosition(globalViewport)) {
  85174. return false;
  85175. }
  85176. // Visibility
  85177. if (!this._isVisible()) {
  85178. return false;
  85179. }
  85180. // Intensity
  85181. var awayX;
  85182. var awayY;
  85183. if (this._positionX < this.borderLimit + globalViewport.x) {
  85184. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85185. }
  85186. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85187. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85188. }
  85189. else {
  85190. awayX = 0;
  85191. }
  85192. if (this._positionY < this.borderLimit + globalViewport.y) {
  85193. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85194. }
  85195. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85196. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85197. }
  85198. else {
  85199. awayY = 0;
  85200. }
  85201. var away = (awayX > awayY) ? awayX : awayY;
  85202. away -= this.viewportBorder;
  85203. if (away > this.borderLimit) {
  85204. away = this.borderLimit;
  85205. }
  85206. var intensity = 1.0 - (away / this.borderLimit);
  85207. if (intensity < 0) {
  85208. return false;
  85209. }
  85210. if (intensity > 1.0) {
  85211. intensity = 1.0;
  85212. }
  85213. if (this.viewportBorder > 0) {
  85214. globalViewport.x += this.viewportBorder;
  85215. globalViewport.y += this.viewportBorder;
  85216. globalViewport.width -= this.viewportBorder * 2;
  85217. globalViewport.height -= this.viewportBorder * 2;
  85218. this._positionX -= this.viewportBorder;
  85219. this._positionY -= this.viewportBorder;
  85220. }
  85221. // Position
  85222. var centerX = globalViewport.x + globalViewport.width / 2;
  85223. var centerY = globalViewport.y + globalViewport.height / 2;
  85224. var distX = centerX - this._positionX;
  85225. var distY = centerY - this._positionY;
  85226. // Effects
  85227. engine.enableEffect(this._effect);
  85228. engine.setState(false);
  85229. engine.setDepthBuffer(false);
  85230. // VBOs
  85231. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85232. // Flares
  85233. for (var index = 0; index < this.lensFlares.length; index++) {
  85234. var flare = this.lensFlares[index];
  85235. engine.setAlphaMode(flare.alphaMode);
  85236. var x = centerX - (distX * flare.position);
  85237. var y = centerY - (distY * flare.position);
  85238. var cw = flare.size;
  85239. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85240. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85241. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85242. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85243. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85244. // Texture
  85245. this._effect.setTexture("textureSampler", flare.texture);
  85246. // Color
  85247. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85248. // Draw order
  85249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85250. }
  85251. engine.setDepthBuffer(true);
  85252. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85253. return true;
  85254. };
  85255. LensFlareSystem.prototype.dispose = function () {
  85256. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85257. if (vertexBuffer) {
  85258. vertexBuffer.dispose();
  85259. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85260. }
  85261. if (this._indexBuffer) {
  85262. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85263. this._indexBuffer = null;
  85264. }
  85265. while (this.lensFlares.length) {
  85266. this.lensFlares[0].dispose();
  85267. }
  85268. // Remove from scene
  85269. var index = this._scene.lensFlareSystems.indexOf(this);
  85270. this._scene.lensFlareSystems.splice(index, 1);
  85271. };
  85272. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85273. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85274. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85275. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85276. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85277. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85278. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85279. var parsedFlare = parsedLensFlareSystem.flares[index];
  85280. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85281. }
  85282. return lensFlareSystem;
  85283. };
  85284. LensFlareSystem.prototype.serialize = function () {
  85285. var serializationObject = {};
  85286. serializationObject.id = this.id;
  85287. serializationObject.name = this.name;
  85288. serializationObject.emitterId = this.getEmitter().id;
  85289. serializationObject.borderLimit = this.borderLimit;
  85290. serializationObject.flares = [];
  85291. for (var index = 0; index < this.lensFlares.length; index++) {
  85292. var flare = this.lensFlares[index];
  85293. serializationObject.flares.push({
  85294. size: flare.size,
  85295. position: flare.position,
  85296. color: flare.color.asArray(),
  85297. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85298. });
  85299. }
  85300. return serializationObject;
  85301. };
  85302. return LensFlareSystem;
  85303. }());
  85304. BABYLON.LensFlareSystem = LensFlareSystem;
  85305. })(BABYLON || (BABYLON = {}));
  85306. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85307. var BABYLON;
  85308. (function (BABYLON) {
  85309. /**
  85310. * This is a holder class for the physics joint created by the physics plugin.
  85311. * It holds a set of functions to control the underlying joint.
  85312. */
  85313. var PhysicsJoint = /** @class */ (function () {
  85314. function PhysicsJoint(type, jointData) {
  85315. this.type = type;
  85316. this.jointData = jointData;
  85317. jointData.nativeParams = jointData.nativeParams || {};
  85318. }
  85319. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85320. get: function () {
  85321. return this._physicsJoint;
  85322. },
  85323. set: function (newJoint) {
  85324. if (this._physicsJoint) {
  85325. //remove from the wolrd
  85326. }
  85327. this._physicsJoint = newJoint;
  85328. },
  85329. enumerable: true,
  85330. configurable: true
  85331. });
  85332. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85333. set: function (physicsPlugin) {
  85334. this._physicsPlugin = physicsPlugin;
  85335. },
  85336. enumerable: true,
  85337. configurable: true
  85338. });
  85339. /**
  85340. * Execute a function that is physics-plugin specific.
  85341. * @param {Function} func the function that will be executed.
  85342. * It accepts two parameters: the physics world and the physics joint.
  85343. */
  85344. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85345. func(this._physicsPlugin.world, this._physicsJoint);
  85346. };
  85347. //TODO check if the native joints are the same
  85348. //Joint Types
  85349. PhysicsJoint.DistanceJoint = 0;
  85350. PhysicsJoint.HingeJoint = 1;
  85351. PhysicsJoint.BallAndSocketJoint = 2;
  85352. PhysicsJoint.WheelJoint = 3;
  85353. PhysicsJoint.SliderJoint = 4;
  85354. //OIMO
  85355. PhysicsJoint.PrismaticJoint = 5;
  85356. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85357. PhysicsJoint.UniversalJoint = 6;
  85358. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85359. //Cannon
  85360. //Similar to a Ball-Joint. Different in params
  85361. PhysicsJoint.PointToPointJoint = 8;
  85362. //Cannon only at the moment
  85363. PhysicsJoint.SpringJoint = 9;
  85364. PhysicsJoint.LockJoint = 10;
  85365. return PhysicsJoint;
  85366. }());
  85367. BABYLON.PhysicsJoint = PhysicsJoint;
  85368. /**
  85369. * A class representing a physics distance joint.
  85370. */
  85371. var DistanceJoint = /** @class */ (function (_super) {
  85372. __extends(DistanceJoint, _super);
  85373. function DistanceJoint(jointData) {
  85374. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85375. }
  85376. /**
  85377. * Update the predefined distance.
  85378. */
  85379. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85380. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85381. };
  85382. return DistanceJoint;
  85383. }(PhysicsJoint));
  85384. BABYLON.DistanceJoint = DistanceJoint;
  85385. var MotorEnabledJoint = /** @class */ (function (_super) {
  85386. __extends(MotorEnabledJoint, _super);
  85387. function MotorEnabledJoint(type, jointData) {
  85388. return _super.call(this, type, jointData) || this;
  85389. }
  85390. /**
  85391. * Set the motor values.
  85392. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85393. * @param {number} force the force to apply
  85394. * @param {number} maxForce max force for this motor.
  85395. */
  85396. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85397. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85398. };
  85399. /**
  85400. * Set the motor's limits.
  85401. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85402. */
  85403. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85404. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85405. };
  85406. return MotorEnabledJoint;
  85407. }(PhysicsJoint));
  85408. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85409. /**
  85410. * This class represents a single hinge physics joint
  85411. */
  85412. var HingeJoint = /** @class */ (function (_super) {
  85413. __extends(HingeJoint, _super);
  85414. function HingeJoint(jointData) {
  85415. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85416. }
  85417. /**
  85418. * Set the motor values.
  85419. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85420. * @param {number} force the force to apply
  85421. * @param {number} maxForce max force for this motor.
  85422. */
  85423. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85424. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85425. };
  85426. /**
  85427. * Set the motor's limits.
  85428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85429. */
  85430. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85431. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85432. };
  85433. return HingeJoint;
  85434. }(MotorEnabledJoint));
  85435. BABYLON.HingeJoint = HingeJoint;
  85436. /**
  85437. * This class represents a dual hinge physics joint (same as wheel joint)
  85438. */
  85439. var Hinge2Joint = /** @class */ (function (_super) {
  85440. __extends(Hinge2Joint, _super);
  85441. function Hinge2Joint(jointData) {
  85442. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85443. }
  85444. /**
  85445. * Set the motor values.
  85446. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85447. * @param {number} force the force to apply
  85448. * @param {number} maxForce max force for this motor.
  85449. * @param {motorIndex} the motor's index, 0 or 1.
  85450. */
  85451. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85452. if (motorIndex === void 0) { motorIndex = 0; }
  85453. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85454. };
  85455. /**
  85456. * Set the motor limits.
  85457. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85458. * @param {number} upperLimit the upper limit
  85459. * @param {number} lowerLimit lower limit
  85460. * @param {motorIndex} the motor's index, 0 or 1.
  85461. */
  85462. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85463. if (motorIndex === void 0) { motorIndex = 0; }
  85464. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85465. };
  85466. return Hinge2Joint;
  85467. }(MotorEnabledJoint));
  85468. BABYLON.Hinge2Joint = Hinge2Joint;
  85469. })(BABYLON || (BABYLON = {}));
  85470. //# sourceMappingURL=babylon.physicsJoint.js.map
  85471. var BABYLON;
  85472. (function (BABYLON) {
  85473. var PhysicsImpostor = /** @class */ (function () {
  85474. function PhysicsImpostor(object, type, _options, _scene) {
  85475. if (_options === void 0) { _options = { mass: 0 }; }
  85476. var _this = this;
  85477. this.object = object;
  85478. this.type = type;
  85479. this._options = _options;
  85480. this._scene = _scene;
  85481. this._bodyUpdateRequired = false;
  85482. this._onBeforePhysicsStepCallbacks = new Array();
  85483. this._onAfterPhysicsStepCallbacks = new Array();
  85484. this._onPhysicsCollideCallbacks = [];
  85485. this._deltaPosition = BABYLON.Vector3.Zero();
  85486. this._isDisposed = false;
  85487. //temp variables for parent rotation calculations
  85488. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85489. this._tmpQuat = new BABYLON.Quaternion();
  85490. this._tmpQuat2 = new BABYLON.Quaternion();
  85491. /**
  85492. * this function is executed by the physics engine.
  85493. */
  85494. this.beforeStep = function () {
  85495. if (!_this._physicsEngine) {
  85496. return;
  85497. }
  85498. _this.object.translate(_this._deltaPosition, -1);
  85499. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85500. _this.object.computeWorldMatrix(false);
  85501. if (_this.object.parent && _this.object.rotationQuaternion) {
  85502. _this.getParentsRotation();
  85503. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85504. }
  85505. else {
  85506. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85507. }
  85508. if (!_this._options.disableBidirectionalTransformation) {
  85509. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85510. }
  85511. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85512. func(_this);
  85513. });
  85514. };
  85515. /**
  85516. * this function is executed by the physics engine.
  85517. */
  85518. this.afterStep = function () {
  85519. if (!_this._physicsEngine) {
  85520. return;
  85521. }
  85522. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85523. func(_this);
  85524. });
  85525. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85526. // object has now its world rotation. needs to be converted to local.
  85527. if (_this.object.parent && _this.object.rotationQuaternion) {
  85528. _this.getParentsRotation();
  85529. _this._tmpQuat.conjugateInPlace();
  85530. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85531. }
  85532. // take the position set and make it the absolute position of this object.
  85533. _this.object.setAbsolutePosition(_this.object.position);
  85534. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85535. _this.object.translate(_this._deltaPosition, 1);
  85536. };
  85537. /**
  85538. * Legacy collision detection event support
  85539. */
  85540. this.onCollideEvent = null;
  85541. //event and body object due to cannon's event-based architecture.
  85542. this.onCollide = function (e) {
  85543. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85544. return;
  85545. }
  85546. if (!_this._physicsEngine) {
  85547. return;
  85548. }
  85549. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85550. if (otherImpostor) {
  85551. // Legacy collision detection event support
  85552. if (_this.onCollideEvent) {
  85553. _this.onCollideEvent(_this, otherImpostor);
  85554. }
  85555. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85556. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85557. }).forEach(function (obj) {
  85558. obj.callback(_this, otherImpostor);
  85559. });
  85560. }
  85561. };
  85562. //sanity check!
  85563. if (!this.object) {
  85564. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85565. return;
  85566. }
  85567. //legacy support for old syntax.
  85568. if (!this._scene && object.getScene) {
  85569. this._scene = object.getScene();
  85570. }
  85571. if (!this._scene) {
  85572. return;
  85573. }
  85574. this._physicsEngine = this._scene.getPhysicsEngine();
  85575. if (!this._physicsEngine) {
  85576. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85577. }
  85578. else {
  85579. //set the object's quaternion, if not set
  85580. if (!this.object.rotationQuaternion) {
  85581. if (this.object.rotation) {
  85582. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85583. }
  85584. else {
  85585. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85586. }
  85587. }
  85588. //default options params
  85589. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85590. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85591. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85592. this._joints = [];
  85593. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85594. if (!this.object.parent || this._options.ignoreParent) {
  85595. this._init();
  85596. }
  85597. else if (this.object.parent.physicsImpostor) {
  85598. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85599. }
  85600. }
  85601. }
  85602. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85603. get: function () {
  85604. return this._isDisposed;
  85605. },
  85606. enumerable: true,
  85607. configurable: true
  85608. });
  85609. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85610. get: function () {
  85611. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85612. },
  85613. set: function (value) {
  85614. this.setMass(value);
  85615. },
  85616. enumerable: true,
  85617. configurable: true
  85618. });
  85619. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85620. get: function () {
  85621. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85622. },
  85623. set: function (value) {
  85624. if (!this._physicsEngine) {
  85625. return;
  85626. }
  85627. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85628. },
  85629. enumerable: true,
  85630. configurable: true
  85631. });
  85632. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85633. get: function () {
  85634. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85635. },
  85636. set: function (value) {
  85637. if (!this._physicsEngine) {
  85638. return;
  85639. }
  85640. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85641. },
  85642. enumerable: true,
  85643. configurable: true
  85644. });
  85645. /**
  85646. * This function will completly initialize this impostor.
  85647. * It will create a new body - but only if this mesh has no parent.
  85648. * If it has, this impostor will not be used other than to define the impostor
  85649. * of the child mesh.
  85650. */
  85651. PhysicsImpostor.prototype._init = function () {
  85652. if (!this._physicsEngine) {
  85653. return;
  85654. }
  85655. this._physicsEngine.removeImpostor(this);
  85656. this.physicsBody = null;
  85657. this._parent = this._parent || this._getPhysicsParent();
  85658. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85659. this._physicsEngine.addImpostor(this);
  85660. }
  85661. };
  85662. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85663. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85664. var parentMesh = this.object.parent;
  85665. return parentMesh.physicsImpostor;
  85666. }
  85667. return null;
  85668. };
  85669. /**
  85670. * Should a new body be generated.
  85671. */
  85672. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85673. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85674. };
  85675. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85676. this.forceUpdate();
  85677. };
  85678. /**
  85679. * Force a regeneration of this or the parent's impostor's body.
  85680. * Use under cautious - This will remove all joints already implemented.
  85681. */
  85682. PhysicsImpostor.prototype.forceUpdate = function () {
  85683. this._init();
  85684. if (this.parent && !this._options.ignoreParent) {
  85685. this.parent.forceUpdate();
  85686. }
  85687. };
  85688. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85689. /*public get mesh(): AbstractMesh {
  85690. return this._mesh;
  85691. }*/
  85692. /**
  85693. * Gets the body that holds this impostor. Either its own, or its parent.
  85694. */
  85695. get: function () {
  85696. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85697. },
  85698. /**
  85699. * Set the physics body. Used mainly by the physics engine/plugin
  85700. */
  85701. set: function (physicsBody) {
  85702. if (this._physicsBody && this._physicsEngine) {
  85703. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85704. }
  85705. this._physicsBody = physicsBody;
  85706. this.resetUpdateFlags();
  85707. },
  85708. enumerable: true,
  85709. configurable: true
  85710. });
  85711. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85712. get: function () {
  85713. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85714. },
  85715. set: function (value) {
  85716. this._parent = value;
  85717. },
  85718. enumerable: true,
  85719. configurable: true
  85720. });
  85721. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85722. this._bodyUpdateRequired = false;
  85723. };
  85724. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85725. if (this.object.getBoundingInfo) {
  85726. var q = this.object.rotationQuaternion;
  85727. //reset rotation
  85728. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85729. //calculate the world matrix with no rotation
  85730. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85731. var boundingInfo = this.object.getBoundingInfo();
  85732. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85733. //bring back the rotation
  85734. this.object.rotationQuaternion = q;
  85735. //calculate the world matrix with the new rotation
  85736. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85737. return size;
  85738. }
  85739. else {
  85740. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85741. }
  85742. };
  85743. PhysicsImpostor.prototype.getObjectCenter = function () {
  85744. if (this.object.getBoundingInfo) {
  85745. var boundingInfo = this.object.getBoundingInfo();
  85746. return boundingInfo.boundingBox.centerWorld;
  85747. }
  85748. else {
  85749. return this.object.position;
  85750. }
  85751. };
  85752. /**
  85753. * Get a specific parametes from the options parameter.
  85754. */
  85755. PhysicsImpostor.prototype.getParam = function (paramName) {
  85756. return this._options[paramName];
  85757. };
  85758. /**
  85759. * Sets a specific parameter in the options given to the physics plugin
  85760. */
  85761. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85762. this._options[paramName] = value;
  85763. this._bodyUpdateRequired = true;
  85764. };
  85765. /**
  85766. * Specifically change the body's mass option. Won't recreate the physics body object
  85767. */
  85768. PhysicsImpostor.prototype.setMass = function (mass) {
  85769. if (this.getParam("mass") !== mass) {
  85770. this.setParam("mass", mass);
  85771. }
  85772. if (this._physicsEngine) {
  85773. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85774. }
  85775. };
  85776. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85777. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85778. };
  85779. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85780. if (this._physicsEngine) {
  85781. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85782. }
  85783. };
  85784. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85785. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85786. };
  85787. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85788. if (this._physicsEngine) {
  85789. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85790. }
  85791. };
  85792. /**
  85793. * Execute a function with the physics plugin native code.
  85794. * Provide a function the will have two variables - the world object and the physics body object.
  85795. */
  85796. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85797. if (this._physicsEngine) {
  85798. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85799. }
  85800. };
  85801. /**
  85802. * Register a function that will be executed before the physics world is stepping forward.
  85803. */
  85804. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85805. this._onBeforePhysicsStepCallbacks.push(func);
  85806. };
  85807. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85808. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85809. if (index > -1) {
  85810. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85811. }
  85812. else {
  85813. BABYLON.Tools.Warn("Function to remove was not found");
  85814. }
  85815. };
  85816. /**
  85817. * Register a function that will be executed after the physics step
  85818. */
  85819. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85820. this._onAfterPhysicsStepCallbacks.push(func);
  85821. };
  85822. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85823. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85824. if (index > -1) {
  85825. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85826. }
  85827. else {
  85828. BABYLON.Tools.Warn("Function to remove was not found");
  85829. }
  85830. };
  85831. /**
  85832. * register a function that will be executed when this impostor collides against a different body.
  85833. */
  85834. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85835. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85836. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85837. };
  85838. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85839. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85840. var index = -1;
  85841. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85842. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85843. // chcek the arrays match
  85844. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85845. return collidedAgainstList.indexOf(impostor) > -1;
  85846. });
  85847. if (sameList) {
  85848. index = idx;
  85849. }
  85850. return sameList;
  85851. }
  85852. return false;
  85853. });
  85854. if (found) {
  85855. this._onPhysicsCollideCallbacks.splice(index, 1);
  85856. }
  85857. else {
  85858. BABYLON.Tools.Warn("Function to remove was not found");
  85859. }
  85860. };
  85861. PhysicsImpostor.prototype.getParentsRotation = function () {
  85862. var parent = this.object.parent;
  85863. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85864. while (parent) {
  85865. if (parent.rotationQuaternion) {
  85866. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85867. }
  85868. else {
  85869. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85870. }
  85871. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85872. parent = parent.parent;
  85873. }
  85874. return this._tmpQuat;
  85875. };
  85876. /**
  85877. * Apply a force
  85878. */
  85879. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85880. if (this._physicsEngine) {
  85881. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85882. }
  85883. return this;
  85884. };
  85885. /**
  85886. * Apply an impulse
  85887. */
  85888. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85889. if (this._physicsEngine) {
  85890. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85891. }
  85892. return this;
  85893. };
  85894. /**
  85895. * A help function to create a joint.
  85896. */
  85897. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85898. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85899. this.addJoint(otherImpostor, joint);
  85900. return this;
  85901. };
  85902. /**
  85903. * Add a joint to this impostor with a different impostor.
  85904. */
  85905. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85906. this._joints.push({
  85907. otherImpostor: otherImpostor,
  85908. joint: joint
  85909. });
  85910. if (this._physicsEngine) {
  85911. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85912. }
  85913. return this;
  85914. };
  85915. /**
  85916. * Will keep this body still, in a sleep mode.
  85917. */
  85918. PhysicsImpostor.prototype.sleep = function () {
  85919. if (this._physicsEngine) {
  85920. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85921. }
  85922. return this;
  85923. };
  85924. /**
  85925. * Wake the body up.
  85926. */
  85927. PhysicsImpostor.prototype.wakeUp = function () {
  85928. if (this._physicsEngine) {
  85929. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85930. }
  85931. return this;
  85932. };
  85933. PhysicsImpostor.prototype.clone = function (newObject) {
  85934. if (!newObject)
  85935. return null;
  85936. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85937. };
  85938. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85939. var _this = this;
  85940. //no dispose if no physics engine is available.
  85941. if (!this._physicsEngine) {
  85942. return;
  85943. }
  85944. this._joints.forEach(function (j) {
  85945. if (_this._physicsEngine) {
  85946. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85947. }
  85948. });
  85949. //dispose the physics body
  85950. this._physicsEngine.removeImpostor(this);
  85951. if (this.parent) {
  85952. this.parent.forceUpdate();
  85953. }
  85954. else {
  85955. /*this._object.getChildMeshes().forEach(function(mesh) {
  85956. if (mesh.physicsImpostor) {
  85957. if (disposeChildren) {
  85958. mesh.physicsImpostor.dispose();
  85959. mesh.physicsImpostor = null;
  85960. }
  85961. }
  85962. })*/
  85963. }
  85964. this._isDisposed = true;
  85965. };
  85966. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85967. this._deltaPosition.copyFrom(position);
  85968. };
  85969. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85970. if (!this._deltaRotation) {
  85971. this._deltaRotation = new BABYLON.Quaternion();
  85972. }
  85973. this._deltaRotation.copyFrom(rotation);
  85974. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85975. };
  85976. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85977. if (this._physicsEngine) {
  85978. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85979. }
  85980. return this;
  85981. };
  85982. PhysicsImpostor.prototype.getRadius = function () {
  85983. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85984. };
  85985. /**
  85986. * Sync a bone with this impostor
  85987. * @param bone The bone to sync to the impostor.
  85988. * @param boneMesh The mesh that the bone is influencing.
  85989. * @param jointPivot The pivot of the joint / bone in local space.
  85990. * @param distToJoint Optional distance from the impostor to the joint.
  85991. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85992. */
  85993. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85994. var tempVec = PhysicsImpostor._tmpVecs[0];
  85995. var mesh = this.object;
  85996. if (mesh.rotationQuaternion) {
  85997. if (adjustRotation) {
  85998. var tempQuat = PhysicsImpostor._tmpQuat;
  85999. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  86000. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  86001. }
  86002. else {
  86003. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  86004. }
  86005. }
  86006. tempVec.x = 0;
  86007. tempVec.y = 0;
  86008. tempVec.z = 0;
  86009. if (jointPivot) {
  86010. tempVec.x = jointPivot.x;
  86011. tempVec.y = jointPivot.y;
  86012. tempVec.z = jointPivot.z;
  86013. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  86014. if (distToJoint === undefined || distToJoint === null) {
  86015. distToJoint = jointPivot.length();
  86016. }
  86017. tempVec.x *= distToJoint;
  86018. tempVec.y *= distToJoint;
  86019. tempVec.z *= distToJoint;
  86020. }
  86021. if (bone.getParent()) {
  86022. tempVec.addInPlace(mesh.getAbsolutePosition());
  86023. bone.setAbsolutePosition(tempVec, boneMesh);
  86024. }
  86025. else {
  86026. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  86027. boneMesh.position.x -= tempVec.x;
  86028. boneMesh.position.y -= tempVec.y;
  86029. boneMesh.position.z -= tempVec.z;
  86030. }
  86031. };
  86032. /**
  86033. * Sync impostor to a bone
  86034. * @param bone The bone that the impostor will be synced to.
  86035. * @param boneMesh The mesh that the bone is influencing.
  86036. * @param jointPivot The pivot of the joint / bone in local space.
  86037. * @param distToJoint Optional distance from the impostor to the joint.
  86038. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86039. * @param boneAxis Optional vector3 axis the bone is aligned with
  86040. */
  86041. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  86042. var mesh = this.object;
  86043. if (mesh.rotationQuaternion) {
  86044. if (adjustRotation) {
  86045. var tempQuat = PhysicsImpostor._tmpQuat;
  86046. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  86047. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86048. }
  86049. else {
  86050. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86051. }
  86052. }
  86053. var pos = PhysicsImpostor._tmpVecs[0];
  86054. var boneDir = PhysicsImpostor._tmpVecs[1];
  86055. if (!boneAxis) {
  86056. boneAxis = PhysicsImpostor._tmpVecs[2];
  86057. boneAxis.x = 0;
  86058. boneAxis.y = 1;
  86059. boneAxis.z = 0;
  86060. }
  86061. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86062. bone.getAbsolutePositionToRef(boneMesh, pos);
  86063. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86064. distToJoint = jointPivot.length();
  86065. }
  86066. if (distToJoint !== undefined && distToJoint !== null) {
  86067. pos.x += boneDir.x * distToJoint;
  86068. pos.y += boneDir.y * distToJoint;
  86069. pos.z += boneDir.z * distToJoint;
  86070. }
  86071. mesh.setAbsolutePosition(pos);
  86072. };
  86073. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86074. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86075. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86076. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86077. //Impostor types
  86078. PhysicsImpostor.NoImpostor = 0;
  86079. PhysicsImpostor.SphereImpostor = 1;
  86080. PhysicsImpostor.BoxImpostor = 2;
  86081. PhysicsImpostor.PlaneImpostor = 3;
  86082. PhysicsImpostor.MeshImpostor = 4;
  86083. PhysicsImpostor.CylinderImpostor = 7;
  86084. PhysicsImpostor.ParticleImpostor = 8;
  86085. PhysicsImpostor.HeightmapImpostor = 9;
  86086. return PhysicsImpostor;
  86087. }());
  86088. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86089. })(BABYLON || (BABYLON = {}));
  86090. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86091. var BABYLON;
  86092. (function (BABYLON) {
  86093. var PhysicsEngine = /** @class */ (function () {
  86094. function PhysicsEngine(gravity, _physicsPlugin) {
  86095. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86096. this._physicsPlugin = _physicsPlugin;
  86097. //new methods and parameters
  86098. this._impostors = [];
  86099. this._joints = [];
  86100. if (!this._physicsPlugin.isSupported()) {
  86101. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86102. + "Please make sure it is included.");
  86103. }
  86104. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86105. this.setGravity(gravity);
  86106. this.setTimeStep();
  86107. }
  86108. PhysicsEngine.prototype.setGravity = function (gravity) {
  86109. this.gravity = gravity;
  86110. this._physicsPlugin.setGravity(this.gravity);
  86111. };
  86112. /**
  86113. * Set the time step of the physics engine.
  86114. * default is 1/60.
  86115. * To slow it down, enter 1/600 for example.
  86116. * To speed it up, 1/30
  86117. * @param {number} newTimeStep the new timestep to apply to this world.
  86118. */
  86119. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86120. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86121. this._physicsPlugin.setTimeStep(newTimeStep);
  86122. };
  86123. /**
  86124. * Get the time step of the physics engine.
  86125. */
  86126. PhysicsEngine.prototype.getTimeStep = function () {
  86127. return this._physicsPlugin.getTimeStep();
  86128. };
  86129. PhysicsEngine.prototype.dispose = function () {
  86130. this._impostors.forEach(function (impostor) {
  86131. impostor.dispose();
  86132. });
  86133. this._physicsPlugin.dispose();
  86134. };
  86135. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86136. return this._physicsPlugin.name;
  86137. };
  86138. /**
  86139. * Adding a new impostor for the impostor tracking.
  86140. * This will be done by the impostor itself.
  86141. * @param {PhysicsImpostor} impostor the impostor to add
  86142. */
  86143. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86144. impostor.uniqueId = this._impostors.push(impostor);
  86145. //if no parent, generate the body
  86146. if (!impostor.parent) {
  86147. this._physicsPlugin.generatePhysicsBody(impostor);
  86148. }
  86149. };
  86150. /**
  86151. * Remove an impostor from the engine.
  86152. * This impostor and its mesh will not longer be updated by the physics engine.
  86153. * @param {PhysicsImpostor} impostor the impostor to remove
  86154. */
  86155. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86156. var index = this._impostors.indexOf(impostor);
  86157. if (index > -1) {
  86158. var removed = this._impostors.splice(index, 1);
  86159. //Is it needed?
  86160. if (removed.length) {
  86161. //this will also remove it from the world.
  86162. removed[0].physicsBody = null;
  86163. }
  86164. }
  86165. };
  86166. /**
  86167. * Add a joint to the physics engine
  86168. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86169. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86170. * @param {PhysicsJoint} the joint that will connect both impostors.
  86171. */
  86172. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86173. var impostorJoint = {
  86174. mainImpostor: mainImpostor,
  86175. connectedImpostor: connectedImpostor,
  86176. joint: joint
  86177. };
  86178. joint.physicsPlugin = this._physicsPlugin;
  86179. this._joints.push(impostorJoint);
  86180. this._physicsPlugin.generateJoint(impostorJoint);
  86181. };
  86182. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86183. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86184. return (impostorJoint.connectedImpostor === connectedImpostor
  86185. && impostorJoint.joint === joint
  86186. && impostorJoint.mainImpostor === mainImpostor);
  86187. });
  86188. if (matchingJoints.length) {
  86189. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86190. //TODO remove it from the list as well
  86191. }
  86192. };
  86193. /**
  86194. * Called by the scene. no need to call it.
  86195. */
  86196. PhysicsEngine.prototype._step = function (delta) {
  86197. var _this = this;
  86198. //check if any mesh has no body / requires an update
  86199. this._impostors.forEach(function (impostor) {
  86200. if (impostor.isBodyInitRequired()) {
  86201. _this._physicsPlugin.generatePhysicsBody(impostor);
  86202. }
  86203. });
  86204. if (delta > 0.1) {
  86205. delta = 0.1;
  86206. }
  86207. else if (delta <= 0) {
  86208. delta = 1.0 / 60.0;
  86209. }
  86210. this._physicsPlugin.executeStep(delta, this._impostors);
  86211. };
  86212. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86213. return this._physicsPlugin;
  86214. };
  86215. PhysicsEngine.prototype.getImpostors = function () {
  86216. return this._impostors;
  86217. };
  86218. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86219. for (var i = 0; i < this._impostors.length; ++i) {
  86220. if (this._impostors[i].object === object) {
  86221. return this._impostors[i];
  86222. }
  86223. }
  86224. return null;
  86225. };
  86226. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86227. for (var i = 0; i < this._impostors.length; ++i) {
  86228. if (this._impostors[i].physicsBody === body) {
  86229. return this._impostors[i];
  86230. }
  86231. }
  86232. return null;
  86233. };
  86234. // Statics
  86235. PhysicsEngine.Epsilon = 0.001;
  86236. return PhysicsEngine;
  86237. }());
  86238. BABYLON.PhysicsEngine = PhysicsEngine;
  86239. })(BABYLON || (BABYLON = {}));
  86240. //# sourceMappingURL=babylon.physicsEngine.js.map
  86241. var BABYLON;
  86242. (function (BABYLON) {
  86243. var PhysicsHelper = /** @class */ (function () {
  86244. function PhysicsHelper(scene) {
  86245. this._scene = scene;
  86246. this._physicsEngine = this._scene.getPhysicsEngine();
  86247. if (!this._physicsEngine) {
  86248. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86249. }
  86250. }
  86251. /**
  86252. * @param {Vector3} origin the origin of the explosion
  86253. * @param {number} radius the explosion radius
  86254. * @param {number} strength the explosion strength
  86255. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86256. */
  86257. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86258. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86259. if (!this._physicsEngine) {
  86260. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86261. return null;
  86262. }
  86263. var impostors = this._physicsEngine.getImpostors();
  86264. if (impostors.length === 0) {
  86265. return null;
  86266. }
  86267. var event = new PhysicsRadialExplosionEvent(this._scene);
  86268. impostors.forEach(function (impostor) {
  86269. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86270. if (!impostorForceAndContactPoint) {
  86271. return;
  86272. }
  86273. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86274. });
  86275. event.dispose(false);
  86276. return event;
  86277. };
  86278. /**
  86279. * @param {Vector3} origin the origin of the explosion
  86280. * @param {number} radius the explosion radius
  86281. * @param {number} strength the explosion strength
  86282. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86283. */
  86284. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86285. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86286. if (!this._physicsEngine) {
  86287. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86288. return null;
  86289. }
  86290. var impostors = this._physicsEngine.getImpostors();
  86291. if (impostors.length === 0) {
  86292. return null;
  86293. }
  86294. var event = new PhysicsRadialExplosionEvent(this._scene);
  86295. impostors.forEach(function (impostor) {
  86296. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86297. if (!impostorForceAndContactPoint) {
  86298. return;
  86299. }
  86300. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86301. });
  86302. event.dispose(false);
  86303. return event;
  86304. };
  86305. /**
  86306. * @param {Vector3} origin the origin of the explosion
  86307. * @param {number} radius the explosion radius
  86308. * @param {number} strength the explosion strength
  86309. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86310. */
  86311. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86312. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86313. if (!this._physicsEngine) {
  86314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86315. return null;
  86316. }
  86317. var impostors = this._physicsEngine.getImpostors();
  86318. if (impostors.length === 0) {
  86319. return null;
  86320. }
  86321. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86322. event.dispose(false);
  86323. return event;
  86324. };
  86325. /**
  86326. * @param {Vector3} origin the origin of the updraft
  86327. * @param {number} radius the radius of the updraft
  86328. * @param {number} strength the strength of the updraft
  86329. * @param {number} height the height of the updraft
  86330. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86331. */
  86332. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86333. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86334. if (!this._physicsEngine) {
  86335. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86336. return null;
  86337. }
  86338. if (this._physicsEngine.getImpostors().length === 0) {
  86339. return null;
  86340. }
  86341. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86342. event.dispose(false);
  86343. return event;
  86344. };
  86345. /**
  86346. * @param {Vector3} origin the of the vortex
  86347. * @param {number} radius the radius of the vortex
  86348. * @param {number} strength the strength of the vortex
  86349. * @param {number} height the height of the vortex
  86350. */
  86351. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86352. if (!this._physicsEngine) {
  86353. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86354. return null;
  86355. }
  86356. if (this._physicsEngine.getImpostors().length === 0) {
  86357. return null;
  86358. }
  86359. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86360. event.dispose(false);
  86361. return event;
  86362. };
  86363. return PhysicsHelper;
  86364. }());
  86365. BABYLON.PhysicsHelper = PhysicsHelper;
  86366. /***** Radial explosion *****/
  86367. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86368. function PhysicsRadialExplosionEvent(scene) {
  86369. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86370. this._rays = [];
  86371. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86372. this._scene = scene;
  86373. }
  86374. /**
  86375. * Returns the data related to the radial explosion event (sphere & rays).
  86376. * @returns {PhysicsRadialExplosionEventData}
  86377. */
  86378. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86379. this._dataFetched = true;
  86380. return {
  86381. sphere: this._sphere,
  86382. rays: this._rays,
  86383. };
  86384. };
  86385. /**
  86386. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86387. * @param impostor
  86388. * @param {Vector3} origin the origin of the explosion
  86389. * @param {number} radius the explosion radius
  86390. * @param {number} strength the explosion strength
  86391. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86392. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86393. */
  86394. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86395. if (impostor.mass === 0) {
  86396. return null;
  86397. }
  86398. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86399. return null;
  86400. }
  86401. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86402. return null;
  86403. }
  86404. var impostorObjectCenter = impostor.getObjectCenter();
  86405. var direction = impostorObjectCenter.subtract(origin);
  86406. var ray = new BABYLON.Ray(origin, direction, radius);
  86407. this._rays.push(ray);
  86408. var hit = ray.intersectsMesh(impostor.object);
  86409. var contactPoint = hit.pickedPoint;
  86410. if (!contactPoint) {
  86411. return null;
  86412. }
  86413. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86414. if (distanceFromOrigin > radius) {
  86415. return null;
  86416. }
  86417. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86418. ? strength
  86419. : strength * (1 - (distanceFromOrigin / radius));
  86420. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86421. return { force: force, contactPoint: contactPoint };
  86422. };
  86423. /**
  86424. * Disposes the sphere.
  86425. * @param {bolean} force
  86426. */
  86427. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86428. var _this = this;
  86429. if (force === void 0) { force = true; }
  86430. if (force) {
  86431. this._sphere.dispose();
  86432. }
  86433. else {
  86434. setTimeout(function () {
  86435. if (!_this._dataFetched) {
  86436. _this._sphere.dispose();
  86437. }
  86438. }, 0);
  86439. }
  86440. };
  86441. /*** Helpers ***/
  86442. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86443. if (!this._sphere) {
  86444. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86445. this._sphere.isVisible = false;
  86446. }
  86447. };
  86448. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86449. var impostorObject = impostor.object;
  86450. this._prepareSphere();
  86451. this._sphere.position = origin;
  86452. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86453. this._sphere._updateBoundingInfo();
  86454. this._sphere.computeWorldMatrix(true);
  86455. return this._sphere.intersectsMesh(impostorObject, true);
  86456. };
  86457. return PhysicsRadialExplosionEvent;
  86458. }());
  86459. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86460. /***** Gravitational Field *****/
  86461. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86462. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86463. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86464. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86465. this._physicsHelper = physicsHelper;
  86466. this._scene = scene;
  86467. this._origin = origin;
  86468. this._radius = radius;
  86469. this._strength = strength;
  86470. this._falloff = falloff;
  86471. this._tickCallback = this._tick.bind(this);
  86472. }
  86473. /**
  86474. * Returns the data related to the gravitational field event (sphere).
  86475. * @returns {PhysicsGravitationalFieldEventData}
  86476. */
  86477. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86478. this._dataFetched = true;
  86479. return {
  86480. sphere: this._sphere,
  86481. };
  86482. };
  86483. /**
  86484. * Enables the gravitational field.
  86485. */
  86486. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86487. this._tickCallback.call(this);
  86488. this._scene.registerBeforeRender(this._tickCallback);
  86489. };
  86490. /**
  86491. * Disables the gravitational field.
  86492. */
  86493. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86494. this._scene.unregisterBeforeRender(this._tickCallback);
  86495. };
  86496. /**
  86497. * Disposes the sphere.
  86498. * @param {bolean} force
  86499. */
  86500. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86501. var _this = this;
  86502. if (force === void 0) { force = true; }
  86503. if (force) {
  86504. this._sphere.dispose();
  86505. }
  86506. else {
  86507. setTimeout(function () {
  86508. if (!_this._dataFetched) {
  86509. _this._sphere.dispose();
  86510. }
  86511. }, 0);
  86512. }
  86513. };
  86514. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86515. // Since the params won't change, we fetch the event only once
  86516. if (this._sphere) {
  86517. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86518. }
  86519. else {
  86520. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86521. if (radialExplosionEvent) {
  86522. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86523. }
  86524. }
  86525. };
  86526. return PhysicsGravitationalFieldEvent;
  86527. }());
  86528. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86529. /***** Updraft *****/
  86530. var PhysicsUpdraftEvent = /** @class */ (function () {
  86531. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86532. this._scene = _scene;
  86533. this._origin = _origin;
  86534. this._radius = _radius;
  86535. this._strength = _strength;
  86536. this._height = _height;
  86537. this._updraftMode = _updraftMode;
  86538. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86539. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86540. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86541. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86542. this._physicsEngine = this._scene.getPhysicsEngine();
  86543. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86544. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86545. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86546. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86547. }
  86548. this._tickCallback = this._tick.bind(this);
  86549. }
  86550. /**
  86551. * Returns the data related to the updraft event (cylinder).
  86552. * @returns {PhysicsUpdraftEventData}
  86553. */
  86554. PhysicsUpdraftEvent.prototype.getData = function () {
  86555. this._dataFetched = true;
  86556. return {
  86557. cylinder: this._cylinder,
  86558. };
  86559. };
  86560. /**
  86561. * Enables the updraft.
  86562. */
  86563. PhysicsUpdraftEvent.prototype.enable = function () {
  86564. this._tickCallback.call(this);
  86565. this._scene.registerBeforeRender(this._tickCallback);
  86566. };
  86567. /**
  86568. * Disables the cortex.
  86569. */
  86570. PhysicsUpdraftEvent.prototype.disable = function () {
  86571. this._scene.unregisterBeforeRender(this._tickCallback);
  86572. };
  86573. /**
  86574. * Disposes the sphere.
  86575. * @param {bolean} force
  86576. */
  86577. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86578. var _this = this;
  86579. if (force === void 0) { force = true; }
  86580. if (force) {
  86581. this._cylinder.dispose();
  86582. }
  86583. else {
  86584. setTimeout(function () {
  86585. if (!_this._dataFetched) {
  86586. _this._cylinder.dispose();
  86587. }
  86588. }, 0);
  86589. }
  86590. };
  86591. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86592. if (impostor.mass === 0) {
  86593. return null;
  86594. }
  86595. if (!this._intersectsWithCylinder(impostor)) {
  86596. return null;
  86597. }
  86598. var impostorObjectCenter = impostor.getObjectCenter();
  86599. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86600. var direction = this._originDirection;
  86601. }
  86602. else {
  86603. var direction = impostorObjectCenter.subtract(this._originTop);
  86604. }
  86605. var multiplier = this._strength * -1;
  86606. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86607. return { force: force, contactPoint: impostorObjectCenter };
  86608. };
  86609. PhysicsUpdraftEvent.prototype._tick = function () {
  86610. var _this = this;
  86611. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86612. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86613. if (!impostorForceAndContactPoint) {
  86614. return;
  86615. }
  86616. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86617. });
  86618. };
  86619. /*** Helpers ***/
  86620. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86621. if (!this._cylinder) {
  86622. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86623. height: this._height,
  86624. diameter: this._radius * 2,
  86625. }, this._scene);
  86626. this._cylinder.isVisible = false;
  86627. }
  86628. };
  86629. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86630. var impostorObject = impostor.object;
  86631. this._prepareCylinder();
  86632. this._cylinder.position = this._cylinderPosition;
  86633. return this._cylinder.intersectsMesh(impostorObject, true);
  86634. };
  86635. return PhysicsUpdraftEvent;
  86636. }());
  86637. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86638. /***** Vortex *****/
  86639. var PhysicsVortexEvent = /** @class */ (function () {
  86640. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86641. this._scene = _scene;
  86642. this._origin = _origin;
  86643. this._radius = _radius;
  86644. this._strength = _strength;
  86645. this._height = _height;
  86646. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86647. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86648. this._updraftMultiplier = 0.02;
  86649. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86650. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86651. this._physicsEngine = this._scene.getPhysicsEngine();
  86652. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86653. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86654. this._tickCallback = this._tick.bind(this);
  86655. }
  86656. /**
  86657. * Returns the data related to the vortex event (cylinder).
  86658. * @returns {PhysicsVortexEventData}
  86659. */
  86660. PhysicsVortexEvent.prototype.getData = function () {
  86661. this._dataFetched = true;
  86662. return {
  86663. cylinder: this._cylinder,
  86664. };
  86665. };
  86666. /**
  86667. * Enables the vortex.
  86668. */
  86669. PhysicsVortexEvent.prototype.enable = function () {
  86670. this._tickCallback.call(this);
  86671. this._scene.registerBeforeRender(this._tickCallback);
  86672. };
  86673. /**
  86674. * Disables the cortex.
  86675. */
  86676. PhysicsVortexEvent.prototype.disable = function () {
  86677. this._scene.unregisterBeforeRender(this._tickCallback);
  86678. };
  86679. /**
  86680. * Disposes the sphere.
  86681. * @param {bolean} force
  86682. */
  86683. PhysicsVortexEvent.prototype.dispose = function (force) {
  86684. var _this = this;
  86685. if (force === void 0) { force = true; }
  86686. if (force) {
  86687. this._cylinder.dispose();
  86688. }
  86689. else {
  86690. setTimeout(function () {
  86691. if (!_this._dataFetched) {
  86692. _this._cylinder.dispose();
  86693. }
  86694. }, 0);
  86695. }
  86696. };
  86697. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86698. if (impostor.mass === 0) {
  86699. return null;
  86700. }
  86701. if (!this._intersectsWithCylinder(impostor)) {
  86702. return null;
  86703. }
  86704. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86705. return null;
  86706. }
  86707. var impostorObjectCenter = impostor.getObjectCenter();
  86708. 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)
  86709. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86710. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86711. var hit = ray.intersectsMesh(impostor.object);
  86712. var contactPoint = hit.pickedPoint;
  86713. if (!contactPoint) {
  86714. return null;
  86715. }
  86716. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86717. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86718. var directionToOrigin = contactPoint.normalize();
  86719. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86720. directionToOrigin = directionToOrigin.negate();
  86721. }
  86722. // TODO: find a more physically based solution
  86723. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86724. var forceX = directionToOrigin.x * this._strength / 8;
  86725. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86726. var forceZ = directionToOrigin.z * this._strength / 8;
  86727. }
  86728. else {
  86729. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86730. var forceY = this._originTop.y * this._updraftMultiplier;
  86731. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86732. }
  86733. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86734. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86735. return { force: force, contactPoint: impostorObjectCenter };
  86736. };
  86737. PhysicsVortexEvent.prototype._tick = function () {
  86738. var _this = this;
  86739. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86740. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86741. if (!impostorForceAndContactPoint) {
  86742. return;
  86743. }
  86744. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86745. });
  86746. };
  86747. /*** Helpers ***/
  86748. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86749. if (!this._cylinder) {
  86750. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86751. height: this._height,
  86752. diameter: this._radius * 2,
  86753. }, this._scene);
  86754. this._cylinder.isVisible = false;
  86755. }
  86756. };
  86757. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86758. var impostorObject = impostor.object;
  86759. this._prepareCylinder();
  86760. this._cylinder.position = this._cylinderPosition;
  86761. return this._cylinder.intersectsMesh(impostorObject, true);
  86762. };
  86763. return PhysicsVortexEvent;
  86764. }());
  86765. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86766. /***** Enums *****/
  86767. /**
  86768. * The strenght of the force in correspondence to the distance of the affected object
  86769. */
  86770. var PhysicsRadialImpulseFalloff;
  86771. (function (PhysicsRadialImpulseFalloff) {
  86772. /** Defines that impulse is constant in strength across it's whole radius */
  86773. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86774. /** DEfines that impulse gets weaker if it's further from the origin */
  86775. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86776. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86777. /**
  86778. * The strenght of the force in correspondence to the distance of the affected object
  86779. */
  86780. var PhysicsUpdraftMode;
  86781. (function (PhysicsUpdraftMode) {
  86782. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86783. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86784. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86785. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86786. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86787. })(BABYLON || (BABYLON = {}));
  86788. //# sourceMappingURL=babylon.physicsHelper.js.map
  86789. var BABYLON;
  86790. (function (BABYLON) {
  86791. var CannonJSPlugin = /** @class */ (function () {
  86792. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86793. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86794. if (iterations === void 0) { iterations = 10; }
  86795. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86796. this.name = "CannonJSPlugin";
  86797. this._physicsMaterials = new Array();
  86798. this._fixedTimeStep = 1 / 60;
  86799. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86800. this.BJSCANNON = CANNON;
  86801. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86802. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86803. this._tmpPosition = BABYLON.Vector3.Zero();
  86804. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86805. this._tmpUnityRotation = new BABYLON.Quaternion();
  86806. if (!this.isSupported()) {
  86807. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86808. return;
  86809. }
  86810. this._extendNamespace();
  86811. this.world = new this.BJSCANNON.World();
  86812. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86813. this.world.solver.iterations = iterations;
  86814. }
  86815. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86816. this.world.gravity.copy(gravity);
  86817. };
  86818. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86819. this._fixedTimeStep = timeStep;
  86820. };
  86821. CannonJSPlugin.prototype.getTimeStep = function () {
  86822. return this._fixedTimeStep;
  86823. };
  86824. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86825. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86826. };
  86827. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86828. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86829. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86830. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86831. };
  86832. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86833. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86834. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86835. impostor.physicsBody.applyForce(impulse, worldPoint);
  86836. };
  86837. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86838. //parent-child relationship. Does this impostor has a parent impostor?
  86839. if (impostor.parent) {
  86840. if (impostor.physicsBody) {
  86841. this.removePhysicsBody(impostor);
  86842. //TODO is that needed?
  86843. impostor.forceUpdate();
  86844. }
  86845. return;
  86846. }
  86847. //should a new body be created for this impostor?
  86848. if (impostor.isBodyInitRequired()) {
  86849. var shape = this._createShape(impostor);
  86850. //unregister events, if body is being changed
  86851. var oldBody = impostor.physicsBody;
  86852. if (oldBody) {
  86853. this.removePhysicsBody(impostor);
  86854. }
  86855. //create the body and material
  86856. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86857. var bodyCreationObject = {
  86858. mass: impostor.getParam("mass"),
  86859. material: material
  86860. };
  86861. // A simple extend, in case native options were used.
  86862. var nativeOptions = impostor.getParam("nativeOptions");
  86863. for (var key in nativeOptions) {
  86864. if (nativeOptions.hasOwnProperty(key)) {
  86865. bodyCreationObject[key] = nativeOptions[key];
  86866. }
  86867. }
  86868. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86869. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86870. this.world.addEventListener("preStep", impostor.beforeStep);
  86871. this.world.addEventListener("postStep", impostor.afterStep);
  86872. impostor.physicsBody.addShape(shape);
  86873. this.world.add(impostor.physicsBody);
  86874. //try to keep the body moving in the right direction by taking old properties.
  86875. //Should be tested!
  86876. if (oldBody) {
  86877. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86878. impostor.physicsBody[param].copy(oldBody[param]);
  86879. });
  86880. }
  86881. this._processChildMeshes(impostor);
  86882. }
  86883. //now update the body's transformation
  86884. this._updatePhysicsBodyTransformation(impostor);
  86885. };
  86886. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86887. var _this = this;
  86888. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86889. var currentRotation = mainImpostor.object.rotationQuaternion;
  86890. if (meshChildren.length) {
  86891. var processMesh = function (localPosition, mesh) {
  86892. if (!currentRotation || !mesh.rotationQuaternion) {
  86893. return;
  86894. }
  86895. var childImpostor = mesh.getPhysicsImpostor();
  86896. if (childImpostor) {
  86897. var parent = childImpostor.parent;
  86898. if (parent !== mainImpostor) {
  86899. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86900. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86901. if (childImpostor.physicsBody) {
  86902. _this.removePhysicsBody(childImpostor);
  86903. childImpostor.physicsBody = null;
  86904. }
  86905. childImpostor.parent = mainImpostor;
  86906. childImpostor.resetUpdateFlags();
  86907. 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));
  86908. //Add the mass of the children.
  86909. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86910. }
  86911. }
  86912. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86913. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86914. };
  86915. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86916. }
  86917. };
  86918. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86919. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86920. this.world.removeEventListener("preStep", impostor.beforeStep);
  86921. this.world.removeEventListener("postStep", impostor.afterStep);
  86922. this.world.remove(impostor.physicsBody);
  86923. };
  86924. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86925. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86926. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86927. if (!mainBody || !connectedBody) {
  86928. return;
  86929. }
  86930. var constraint;
  86931. var jointData = impostorJoint.joint.jointData;
  86932. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86933. var constraintData = {
  86934. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86935. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86936. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86937. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86938. maxForce: jointData.nativeParams.maxForce,
  86939. collideConnected: !!jointData.collision
  86940. };
  86941. switch (impostorJoint.joint.type) {
  86942. case BABYLON.PhysicsJoint.HingeJoint:
  86943. case BABYLON.PhysicsJoint.Hinge2Joint:
  86944. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86945. break;
  86946. case BABYLON.PhysicsJoint.DistanceJoint:
  86947. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86948. break;
  86949. case BABYLON.PhysicsJoint.SpringJoint:
  86950. var springData = jointData;
  86951. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86952. restLength: springData.length,
  86953. stiffness: springData.stiffness,
  86954. damping: springData.damping,
  86955. localAnchorA: constraintData.pivotA,
  86956. localAnchorB: constraintData.pivotB
  86957. });
  86958. break;
  86959. case BABYLON.PhysicsJoint.LockJoint:
  86960. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86961. break;
  86962. case BABYLON.PhysicsJoint.PointToPointJoint:
  86963. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86964. default:
  86965. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86966. break;
  86967. }
  86968. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86969. constraint.collideConnected = !!jointData.collision;
  86970. impostorJoint.joint.physicsJoint = constraint;
  86971. //don't add spring as constraint, as it is not one.
  86972. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86973. this.world.addConstraint(constraint);
  86974. }
  86975. else {
  86976. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86977. constraint.applyForce();
  86978. });
  86979. }
  86980. };
  86981. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86982. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86983. };
  86984. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86985. var index;
  86986. var mat;
  86987. for (index = 0; index < this._physicsMaterials.length; index++) {
  86988. mat = this._physicsMaterials[index];
  86989. if (mat.friction === friction && mat.restitution === restitution) {
  86990. return mat;
  86991. }
  86992. }
  86993. var currentMat = new this.BJSCANNON.Material(name);
  86994. currentMat.friction = friction;
  86995. currentMat.restitution = restitution;
  86996. this._physicsMaterials.push(currentMat);
  86997. return currentMat;
  86998. };
  86999. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  87000. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  87001. };
  87002. CannonJSPlugin.prototype._createShape = function (impostor) {
  87003. var object = impostor.object;
  87004. var returnValue;
  87005. var extendSize = impostor.getObjectExtendSize();
  87006. switch (impostor.type) {
  87007. case BABYLON.PhysicsImpostor.SphereImpostor:
  87008. var radiusX = extendSize.x;
  87009. var radiusY = extendSize.y;
  87010. var radiusZ = extendSize.z;
  87011. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  87012. break;
  87013. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  87014. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87015. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  87016. break;
  87017. case BABYLON.PhysicsImpostor.BoxImpostor:
  87018. var box = extendSize.scale(0.5);
  87019. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87020. break;
  87021. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87022. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  87023. returnValue = new this.BJSCANNON.Plane();
  87024. break;
  87025. case BABYLON.PhysicsImpostor.MeshImpostor:
  87026. // should transform the vertex data to world coordinates!!
  87027. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  87028. var rawFaces = object.getIndices ? object.getIndices() : [];
  87029. if (!rawVerts)
  87030. return;
  87031. // get only scale! so the object could transform correctly.
  87032. var oldPosition = object.position.clone();
  87033. var oldRotation = object.rotation && object.rotation.clone();
  87034. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  87035. object.position.copyFromFloats(0, 0, 0);
  87036. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87037. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87038. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87039. var transform = object.computeWorldMatrix(true);
  87040. // convert rawVerts to object space
  87041. var temp = new Array();
  87042. var index;
  87043. for (index = 0; index < rawVerts.length; index += 3) {
  87044. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  87045. }
  87046. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  87047. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87048. //now set back the transformation!
  87049. object.position.copyFrom(oldPosition);
  87050. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87051. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87052. break;
  87053. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87054. var oldPosition2 = object.position.clone();
  87055. var oldRotation2 = object.rotation && object.rotation.clone();
  87056. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87057. object.position.copyFromFloats(0, 0, 0);
  87058. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87059. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87060. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87061. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87062. returnValue = this._createHeightmap(object);
  87063. object.position.copyFrom(oldPosition2);
  87064. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87065. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87066. object.computeWorldMatrix(true);
  87067. break;
  87068. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87069. returnValue = new this.BJSCANNON.Particle();
  87070. break;
  87071. }
  87072. return returnValue;
  87073. };
  87074. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87075. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87076. var transform = object.computeWorldMatrix(true);
  87077. // convert rawVerts to object space
  87078. var temp = new Array();
  87079. var index;
  87080. for (index = 0; index < pos.length; index += 3) {
  87081. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87082. }
  87083. pos = temp;
  87084. var matrix = new Array();
  87085. //For now pointDepth will not be used and will be automatically calculated.
  87086. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87087. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87088. var boundingInfo = object.getBoundingInfo();
  87089. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87090. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87091. var elementSize = dim * 2 / arraySize;
  87092. for (var i = 0; i < pos.length; i = i + 3) {
  87093. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87094. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87095. var y = -pos[i + 2] + minY;
  87096. if (!matrix[x]) {
  87097. matrix[x] = [];
  87098. }
  87099. if (!matrix[x][z]) {
  87100. matrix[x][z] = y;
  87101. }
  87102. matrix[x][z] = Math.max(y, matrix[x][z]);
  87103. }
  87104. for (var x = 0; x <= arraySize; ++x) {
  87105. if (!matrix[x]) {
  87106. var loc = 1;
  87107. while (!matrix[(x + loc) % arraySize]) {
  87108. loc++;
  87109. }
  87110. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87111. //console.log("missing x", x);
  87112. }
  87113. for (var z = 0; z <= arraySize; ++z) {
  87114. if (!matrix[x][z]) {
  87115. var loc = 1;
  87116. var newValue;
  87117. while (newValue === undefined) {
  87118. newValue = matrix[x][(z + loc++) % arraySize];
  87119. }
  87120. matrix[x][z] = newValue;
  87121. }
  87122. }
  87123. }
  87124. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87125. elementSize: elementSize
  87126. });
  87127. //For future reference, needed for body transformation
  87128. shape.minY = minY;
  87129. return shape;
  87130. };
  87131. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87132. var object = impostor.object;
  87133. //make sure it is updated...
  87134. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87135. // The delta between the mesh position and the mesh bounding box center
  87136. var bInfo = object.getBoundingInfo();
  87137. if (!bInfo)
  87138. return;
  87139. var center = impostor.getObjectCenter();
  87140. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87141. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87142. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87143. this._tmpPosition.copyFrom(center);
  87144. var quaternion = object.rotationQuaternion;
  87145. if (!quaternion) {
  87146. return;
  87147. }
  87148. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87149. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87150. //-90 DEG in X, precalculated
  87151. quaternion = quaternion.multiply(this._minus90X);
  87152. //Invert! (Precalculated, 90 deg in X)
  87153. //No need to clone. this will never change.
  87154. impostor.setDeltaRotation(this._plus90X);
  87155. }
  87156. //If it is a heightfield, if should be centered.
  87157. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87158. var mesh = object;
  87159. var boundingInfo = mesh.getBoundingInfo();
  87160. //calculate the correct body position:
  87161. var rotationQuaternion = mesh.rotationQuaternion;
  87162. mesh.rotationQuaternion = this._tmpUnityRotation;
  87163. mesh.computeWorldMatrix(true);
  87164. //get original center with no rotation
  87165. var c = center.clone();
  87166. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87167. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87168. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87169. mesh.setPreTransformMatrix(p);
  87170. mesh.computeWorldMatrix(true);
  87171. //calculate the translation
  87172. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87173. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87174. //add it inverted to the delta
  87175. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87176. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87177. //rotation is back
  87178. mesh.rotationQuaternion = rotationQuaternion;
  87179. mesh.setPreTransformMatrix(oldPivot);
  87180. mesh.computeWorldMatrix(true);
  87181. }
  87182. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87183. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87184. //this._tmpPosition.copyFrom(object.position);
  87185. }
  87186. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87187. //Now update the impostor object
  87188. impostor.physicsBody.position.copy(this._tmpPosition);
  87189. impostor.physicsBody.quaternion.copy(quaternion);
  87190. };
  87191. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87192. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87193. if (impostor.object.rotationQuaternion) {
  87194. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87195. }
  87196. };
  87197. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87198. impostor.physicsBody.position.copy(newPosition);
  87199. impostor.physicsBody.quaternion.copy(newRotation);
  87200. };
  87201. CannonJSPlugin.prototype.isSupported = function () {
  87202. return this.BJSCANNON !== undefined;
  87203. };
  87204. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87205. impostor.physicsBody.velocity.copy(velocity);
  87206. };
  87207. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87208. impostor.physicsBody.angularVelocity.copy(velocity);
  87209. };
  87210. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87211. var v = impostor.physicsBody.velocity;
  87212. if (!v) {
  87213. return null;
  87214. }
  87215. return new BABYLON.Vector3(v.x, v.y, v.z);
  87216. };
  87217. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87218. var v = impostor.physicsBody.angularVelocity;
  87219. if (!v) {
  87220. return null;
  87221. }
  87222. return new BABYLON.Vector3(v.x, v.y, v.z);
  87223. };
  87224. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87225. impostor.physicsBody.mass = mass;
  87226. impostor.physicsBody.updateMassProperties();
  87227. };
  87228. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87229. return impostor.physicsBody.mass;
  87230. };
  87231. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87232. return impostor.physicsBody.material.friction;
  87233. };
  87234. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87235. impostor.physicsBody.material.friction = friction;
  87236. };
  87237. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87238. return impostor.physicsBody.material.restitution;
  87239. };
  87240. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87241. impostor.physicsBody.material.restitution = restitution;
  87242. };
  87243. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87244. impostor.physicsBody.sleep();
  87245. };
  87246. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87247. impostor.physicsBody.wakeUp();
  87248. };
  87249. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87250. joint.physicsJoint.distance = maxDistance;
  87251. };
  87252. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87253. // if (!motorIndex) {
  87254. // joint.physicsJoint.enableMotor();
  87255. // }
  87256. // }
  87257. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87258. // if (!motorIndex) {
  87259. // joint.physicsJoint.disableMotor();
  87260. // }
  87261. // }
  87262. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87263. if (!motorIndex) {
  87264. joint.physicsJoint.enableMotor();
  87265. joint.physicsJoint.setMotorSpeed(speed);
  87266. if (maxForce) {
  87267. this.setLimit(joint, maxForce);
  87268. }
  87269. }
  87270. };
  87271. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87272. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87273. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87274. };
  87275. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87276. var body = impostor.physicsBody;
  87277. mesh.position.x = body.position.x;
  87278. mesh.position.y = body.position.y;
  87279. mesh.position.z = body.position.z;
  87280. if (mesh.rotationQuaternion) {
  87281. mesh.rotationQuaternion.x = body.quaternion.x;
  87282. mesh.rotationQuaternion.y = body.quaternion.y;
  87283. mesh.rotationQuaternion.z = body.quaternion.z;
  87284. mesh.rotationQuaternion.w = body.quaternion.w;
  87285. }
  87286. };
  87287. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87288. var shape = impostor.physicsBody.shapes[0];
  87289. return shape.boundingSphereRadius;
  87290. };
  87291. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87292. var shape = impostor.physicsBody.shapes[0];
  87293. result.x = shape.halfExtents.x * 2;
  87294. result.y = shape.halfExtents.y * 2;
  87295. result.z = shape.halfExtents.z * 2;
  87296. };
  87297. CannonJSPlugin.prototype.dispose = function () {
  87298. };
  87299. CannonJSPlugin.prototype._extendNamespace = function () {
  87300. //this will force cannon to execute at least one step when using interpolation
  87301. var step_tmp1 = new this.BJSCANNON.Vec3();
  87302. var Engine = this.BJSCANNON;
  87303. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87304. maxSubSteps = maxSubSteps || 10;
  87305. timeSinceLastCalled = timeSinceLastCalled || 0;
  87306. if (timeSinceLastCalled === 0) {
  87307. this.internalStep(dt);
  87308. this.time += dt;
  87309. }
  87310. else {
  87311. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87312. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87313. var t0 = performance.now();
  87314. for (var i = 0; i !== internalSteps; i++) {
  87315. this.internalStep(dt);
  87316. if (performance.now() - t0 > dt * 1000) {
  87317. break;
  87318. }
  87319. }
  87320. this.time += timeSinceLastCalled;
  87321. var h = this.time % dt;
  87322. var h_div_dt = h / dt;
  87323. var interpvelo = step_tmp1;
  87324. var bodies = this.bodies;
  87325. for (var j = 0; j !== bodies.length; j++) {
  87326. var b = bodies[j];
  87327. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87328. b.position.vsub(b.previousPosition, interpvelo);
  87329. interpvelo.scale(h_div_dt, interpvelo);
  87330. b.position.vadd(interpvelo, b.interpolatedPosition);
  87331. }
  87332. else {
  87333. b.interpolatedPosition.copy(b.position);
  87334. b.interpolatedQuaternion.copy(b.quaternion);
  87335. }
  87336. }
  87337. }
  87338. };
  87339. };
  87340. return CannonJSPlugin;
  87341. }());
  87342. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87343. })(BABYLON || (BABYLON = {}));
  87344. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87345. var BABYLON;
  87346. (function (BABYLON) {
  87347. var OimoJSPlugin = /** @class */ (function () {
  87348. function OimoJSPlugin(iterations) {
  87349. this.name = "OimoJSPlugin";
  87350. this._tmpImpostorsArray = [];
  87351. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87352. this.BJSOIMO = OIMO;
  87353. this.world = new this.BJSOIMO.World({
  87354. iterations: iterations
  87355. });
  87356. this.world.clear();
  87357. }
  87358. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87359. this.world.gravity.copy(gravity);
  87360. };
  87361. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87362. this.world.timeStep = timeStep;
  87363. };
  87364. OimoJSPlugin.prototype.getTimeStep = function () {
  87365. return this.world.timeStep;
  87366. };
  87367. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87368. var _this = this;
  87369. impostors.forEach(function (impostor) {
  87370. impostor.beforeStep();
  87371. });
  87372. this.world.step();
  87373. impostors.forEach(function (impostor) {
  87374. impostor.afterStep();
  87375. //update the ordered impostors array
  87376. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87377. });
  87378. //check for collisions
  87379. var contact = this.world.contacts;
  87380. while (contact !== null) {
  87381. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87382. contact = contact.next;
  87383. continue;
  87384. }
  87385. //is this body colliding with any other? get the impostor
  87386. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87387. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87388. if (!mainImpostor || !collidingImpostor) {
  87389. contact = contact.next;
  87390. continue;
  87391. }
  87392. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87393. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87394. contact = contact.next;
  87395. }
  87396. };
  87397. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87398. var mass = impostor.physicsBody.mass;
  87399. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87400. };
  87401. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87402. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87403. this.applyImpulse(impostor, force, contactPoint);
  87404. };
  87405. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87406. var _this = this;
  87407. //parent-child relationship. Does this impostor has a parent impostor?
  87408. if (impostor.parent) {
  87409. if (impostor.physicsBody) {
  87410. this.removePhysicsBody(impostor);
  87411. //TODO is that needed?
  87412. impostor.forceUpdate();
  87413. }
  87414. return;
  87415. }
  87416. if (impostor.isBodyInitRequired()) {
  87417. var bodyConfig = {
  87418. name: impostor.uniqueId,
  87419. //Oimo must have mass, also for static objects.
  87420. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87421. size: [],
  87422. type: [],
  87423. pos: [],
  87424. posShape: [],
  87425. rot: [],
  87426. rotShape: [],
  87427. move: impostor.getParam("mass") !== 0,
  87428. density: impostor.getParam("mass"),
  87429. friction: impostor.getParam("friction"),
  87430. restitution: impostor.getParam("restitution"),
  87431. //Supporting older versions of Oimo
  87432. world: this.world
  87433. };
  87434. var impostors = [impostor];
  87435. var addToArray = function (parent) {
  87436. if (!parent.getChildMeshes)
  87437. return;
  87438. parent.getChildMeshes().forEach(function (m) {
  87439. if (m.physicsImpostor) {
  87440. impostors.push(m.physicsImpostor);
  87441. //m.physicsImpostor._init();
  87442. }
  87443. });
  87444. };
  87445. addToArray(impostor.object);
  87446. var checkWithEpsilon_1 = function (value) {
  87447. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87448. };
  87449. var globalQuaternion_1 = new BABYLON.Quaternion();
  87450. impostors.forEach(function (i) {
  87451. if (!i.object.rotationQuaternion) {
  87452. return;
  87453. }
  87454. //get the correct bounding box
  87455. var oldQuaternion = i.object.rotationQuaternion;
  87456. globalQuaternion_1 = oldQuaternion.clone();
  87457. var rot = oldQuaternion.toEulerAngles();
  87458. var extendSize = i.getObjectExtendSize();
  87459. var radToDeg = 57.295779513082320876;
  87460. if (i === impostor) {
  87461. var center = impostor.getObjectCenter();
  87462. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87463. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87464. //Can also use Array.prototype.push.apply
  87465. bodyConfig.pos.push(center.x);
  87466. bodyConfig.pos.push(center.y);
  87467. bodyConfig.pos.push(center.z);
  87468. bodyConfig.posShape.push(0, 0, 0);
  87469. //tmp solution
  87470. bodyConfig.rot.push(0);
  87471. bodyConfig.rot.push(0);
  87472. bodyConfig.rot.push(0);
  87473. bodyConfig.rotShape.push(0, 0, 0);
  87474. }
  87475. else {
  87476. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87477. bodyConfig.posShape.push(localPosition.x);
  87478. bodyConfig.posShape.push(localPosition.y);
  87479. bodyConfig.posShape.push(localPosition.z);
  87480. bodyConfig.pos.push(0, 0, 0);
  87481. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87482. bodyConfig.rot.push(0);
  87483. bodyConfig.rot.push(0);
  87484. bodyConfig.rot.push(0);
  87485. bodyConfig.rotShape.push(rot.x * radToDeg);
  87486. bodyConfig.rotShape.push(rot.y * radToDeg);
  87487. bodyConfig.rotShape.push(rot.z * radToDeg);
  87488. }
  87489. // register mesh
  87490. switch (i.type) {
  87491. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87492. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87493. case BABYLON.PhysicsImpostor.SphereImpostor:
  87494. var radiusX = extendSize.x;
  87495. var radiusY = extendSize.y;
  87496. var radiusZ = extendSize.z;
  87497. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87498. bodyConfig.type.push('sphere');
  87499. //due to the way oimo works with compounds, add 3 times
  87500. bodyConfig.size.push(size);
  87501. bodyConfig.size.push(size);
  87502. bodyConfig.size.push(size);
  87503. break;
  87504. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87505. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87506. var sizeY = checkWithEpsilon_1(extendSize.y);
  87507. bodyConfig.type.push('cylinder');
  87508. bodyConfig.size.push(sizeX);
  87509. bodyConfig.size.push(sizeY);
  87510. //due to the way oimo works with compounds, add one more value.
  87511. bodyConfig.size.push(sizeY);
  87512. break;
  87513. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87514. case BABYLON.PhysicsImpostor.BoxImpostor:
  87515. default:
  87516. var sizeX = checkWithEpsilon_1(extendSize.x);
  87517. var sizeY = checkWithEpsilon_1(extendSize.y);
  87518. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87519. bodyConfig.type.push('box');
  87520. //if (i === impostor) {
  87521. bodyConfig.size.push(sizeX);
  87522. bodyConfig.size.push(sizeY);
  87523. bodyConfig.size.push(sizeZ);
  87524. //} else {
  87525. // bodyConfig.size.push(0,0,0);
  87526. //}
  87527. break;
  87528. }
  87529. //actually not needed, but hey...
  87530. i.object.rotationQuaternion = oldQuaternion;
  87531. });
  87532. impostor.physicsBody = this.world.add(bodyConfig);
  87533. // set the quaternion, ignoring the previously defined (euler) rotation
  87534. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87535. // update with delta 0, so the body will reveive the new rotation.
  87536. impostor.physicsBody.updatePosition(0);
  87537. }
  87538. else {
  87539. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87540. }
  87541. impostor.setDeltaPosition(this._tmpPositionVector);
  87542. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87543. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87544. };
  87545. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87546. //impostor.physicsBody.dispose();
  87547. //Same as : (older oimo versions)
  87548. this.world.removeRigidBody(impostor.physicsBody);
  87549. };
  87550. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87551. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87552. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87553. if (!mainBody || !connectedBody) {
  87554. return;
  87555. }
  87556. var jointData = impostorJoint.joint.jointData;
  87557. var options = jointData.nativeParams || {};
  87558. var type;
  87559. var nativeJointData = {
  87560. body1: mainBody,
  87561. body2: connectedBody,
  87562. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87563. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87564. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87565. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87566. min: options.min,
  87567. max: options.max,
  87568. collision: options.collision || jointData.collision,
  87569. spring: options.spring,
  87570. //supporting older version of Oimo
  87571. world: this.world
  87572. };
  87573. switch (impostorJoint.joint.type) {
  87574. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87575. type = "jointBall";
  87576. break;
  87577. case BABYLON.PhysicsJoint.SpringJoint:
  87578. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87579. var springData = jointData;
  87580. nativeJointData.min = springData.length || nativeJointData.min;
  87581. //Max should also be set, just make sure it is at least min
  87582. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87583. case BABYLON.PhysicsJoint.DistanceJoint:
  87584. type = "jointDistance";
  87585. nativeJointData.max = jointData.maxDistance;
  87586. break;
  87587. case BABYLON.PhysicsJoint.PrismaticJoint:
  87588. type = "jointPrisme";
  87589. break;
  87590. case BABYLON.PhysicsJoint.SliderJoint:
  87591. type = "jointSlide";
  87592. break;
  87593. case BABYLON.PhysicsJoint.WheelJoint:
  87594. type = "jointWheel";
  87595. break;
  87596. case BABYLON.PhysicsJoint.HingeJoint:
  87597. default:
  87598. type = "jointHinge";
  87599. break;
  87600. }
  87601. nativeJointData.type = type;
  87602. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87603. };
  87604. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87605. //Bug in Oimo prevents us from disposing a joint in the playground
  87606. //joint.joint.physicsJoint.dispose();
  87607. //So we will bruteforce it!
  87608. try {
  87609. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87610. }
  87611. catch (e) {
  87612. BABYLON.Tools.Warn(e);
  87613. }
  87614. };
  87615. OimoJSPlugin.prototype.isSupported = function () {
  87616. return this.BJSOIMO !== undefined;
  87617. };
  87618. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87619. if (!impostor.physicsBody.sleeping) {
  87620. //TODO check that
  87621. /*if (impostor.physicsBody.shapes.next) {
  87622. var parentShape = this._getLastShape(impostor.physicsBody);
  87623. impostor.object.position.copyFrom(parentShape.position);
  87624. console.log(parentShape.position);
  87625. } else {*/
  87626. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87627. //}
  87628. if (impostor.object.rotationQuaternion) {
  87629. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87630. }
  87631. }
  87632. };
  87633. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87634. var body = impostor.physicsBody;
  87635. body.position.copy(newPosition);
  87636. body.orientation.copy(newRotation);
  87637. body.syncShapes();
  87638. body.awake();
  87639. };
  87640. /*private _getLastShape(body: any): any {
  87641. var lastShape = body.shapes;
  87642. while (lastShape.next) {
  87643. lastShape = lastShape.next;
  87644. }
  87645. return lastShape;
  87646. }*/
  87647. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87648. impostor.physicsBody.linearVelocity.copy(velocity);
  87649. };
  87650. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87651. impostor.physicsBody.angularVelocity.copy(velocity);
  87652. };
  87653. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87654. var v = impostor.physicsBody.linearVelocity;
  87655. if (!v) {
  87656. return null;
  87657. }
  87658. return new BABYLON.Vector3(v.x, v.y, v.z);
  87659. };
  87660. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87661. var v = impostor.physicsBody.angularVelocity;
  87662. if (!v) {
  87663. return null;
  87664. }
  87665. return new BABYLON.Vector3(v.x, v.y, v.z);
  87666. };
  87667. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87668. var staticBody = mass === 0;
  87669. //this will actually set the body's density and not its mass.
  87670. //But this is how oimo treats the mass variable.
  87671. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87672. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87673. };
  87674. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87675. return impostor.physicsBody.shapes.density;
  87676. };
  87677. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87678. return impostor.physicsBody.shapes.friction;
  87679. };
  87680. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87681. impostor.physicsBody.shapes.friction = friction;
  87682. };
  87683. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87684. return impostor.physicsBody.shapes.restitution;
  87685. };
  87686. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87687. impostor.physicsBody.shapes.restitution = restitution;
  87688. };
  87689. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87690. impostor.physicsBody.sleep();
  87691. };
  87692. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87693. impostor.physicsBody.awake();
  87694. };
  87695. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87696. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87697. if (minDistance !== void 0) {
  87698. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87699. }
  87700. };
  87701. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87702. //TODO separate rotational and transational motors.
  87703. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87704. if (motor) {
  87705. motor.setMotor(speed, maxForce);
  87706. }
  87707. };
  87708. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87709. //TODO separate rotational and transational motors.
  87710. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87711. if (motor) {
  87712. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87713. }
  87714. };
  87715. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87716. var body = impostor.physicsBody;
  87717. mesh.position.x = body.position.x;
  87718. mesh.position.y = body.position.y;
  87719. mesh.position.z = body.position.z;
  87720. if (mesh.rotationQuaternion) {
  87721. mesh.rotationQuaternion.x = body.orientation.x;
  87722. mesh.rotationQuaternion.y = body.orientation.y;
  87723. mesh.rotationQuaternion.z = body.orientation.z;
  87724. mesh.rotationQuaternion.w = body.orientation.s;
  87725. }
  87726. };
  87727. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87728. return impostor.physicsBody.shapes.radius;
  87729. };
  87730. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87731. var shape = impostor.physicsBody.shapes;
  87732. result.x = shape.halfWidth * 2;
  87733. result.y = shape.halfHeight * 2;
  87734. result.z = shape.halfDepth * 2;
  87735. };
  87736. OimoJSPlugin.prototype.dispose = function () {
  87737. this.world.clear();
  87738. };
  87739. return OimoJSPlugin;
  87740. }());
  87741. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87742. })(BABYLON || (BABYLON = {}));
  87743. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87744. var BABYLON;
  87745. (function (BABYLON) {
  87746. /*
  87747. * Based on jsTGALoader - Javascript loader for TGA file
  87748. * By Vincent Thibault
  87749. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87750. */
  87751. var TGATools = /** @class */ (function () {
  87752. function TGATools() {
  87753. }
  87754. TGATools.GetTGAHeader = function (data) {
  87755. var offset = 0;
  87756. var header = {
  87757. id_length: data[offset++],
  87758. colormap_type: data[offset++],
  87759. image_type: data[offset++],
  87760. colormap_index: data[offset++] | data[offset++] << 8,
  87761. colormap_length: data[offset++] | data[offset++] << 8,
  87762. colormap_size: data[offset++],
  87763. origin: [
  87764. data[offset++] | data[offset++] << 8,
  87765. data[offset++] | data[offset++] << 8
  87766. ],
  87767. width: data[offset++] | data[offset++] << 8,
  87768. height: data[offset++] | data[offset++] << 8,
  87769. pixel_size: data[offset++],
  87770. flags: data[offset++]
  87771. };
  87772. return header;
  87773. };
  87774. /**
  87775. * Uploads TGA content to a Babylon Texture
  87776. * @hidden
  87777. */
  87778. TGATools.UploadContent = function (texture, data) {
  87779. // Not enough data to contain header ?
  87780. if (data.length < 19) {
  87781. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87782. return;
  87783. }
  87784. // Read Header
  87785. var offset = 18;
  87786. var header = TGATools.GetTGAHeader(data);
  87787. // Assume it's a valid Targa file.
  87788. if (header.id_length + offset > data.length) {
  87789. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87790. return;
  87791. }
  87792. // Skip not needed data
  87793. offset += header.id_length;
  87794. var use_rle = false;
  87795. var use_pal = false;
  87796. var use_grey = false;
  87797. // Get some informations.
  87798. switch (header.image_type) {
  87799. case TGATools._TYPE_RLE_INDEXED:
  87800. use_rle = true;
  87801. case TGATools._TYPE_INDEXED:
  87802. use_pal = true;
  87803. break;
  87804. case TGATools._TYPE_RLE_RGB:
  87805. use_rle = true;
  87806. case TGATools._TYPE_RGB:
  87807. // use_rgb = true;
  87808. break;
  87809. case TGATools._TYPE_RLE_GREY:
  87810. use_rle = true;
  87811. case TGATools._TYPE_GREY:
  87812. use_grey = true;
  87813. break;
  87814. }
  87815. var pixel_data;
  87816. // var numAlphaBits = header.flags & 0xf;
  87817. var pixel_size = header.pixel_size >> 3;
  87818. var pixel_total = header.width * header.height * pixel_size;
  87819. // Read palettes
  87820. var palettes;
  87821. if (use_pal) {
  87822. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87823. }
  87824. // Read LRE
  87825. if (use_rle) {
  87826. pixel_data = new Uint8Array(pixel_total);
  87827. var c, count, i;
  87828. var localOffset = 0;
  87829. var pixels = new Uint8Array(pixel_size);
  87830. while (offset < pixel_total && localOffset < pixel_total) {
  87831. c = data[offset++];
  87832. count = (c & 0x7f) + 1;
  87833. // RLE pixels
  87834. if (c & 0x80) {
  87835. // Bind pixel tmp array
  87836. for (i = 0; i < pixel_size; ++i) {
  87837. pixels[i] = data[offset++];
  87838. }
  87839. // Copy pixel array
  87840. for (i = 0; i < count; ++i) {
  87841. pixel_data.set(pixels, localOffset + i * pixel_size);
  87842. }
  87843. localOffset += pixel_size * count;
  87844. }
  87845. // Raw pixels
  87846. else {
  87847. count *= pixel_size;
  87848. for (i = 0; i < count; ++i) {
  87849. pixel_data[localOffset + i] = data[offset++];
  87850. }
  87851. localOffset += count;
  87852. }
  87853. }
  87854. }
  87855. // RAW Pixels
  87856. else {
  87857. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87858. }
  87859. // Load to texture
  87860. var x_start, y_start, x_step, y_step, y_end, x_end;
  87861. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87862. default:
  87863. case TGATools._ORIGIN_UL:
  87864. x_start = 0;
  87865. x_step = 1;
  87866. x_end = header.width;
  87867. y_start = 0;
  87868. y_step = 1;
  87869. y_end = header.height;
  87870. break;
  87871. case TGATools._ORIGIN_BL:
  87872. x_start = 0;
  87873. x_step = 1;
  87874. x_end = header.width;
  87875. y_start = header.height - 1;
  87876. y_step = -1;
  87877. y_end = -1;
  87878. break;
  87879. case TGATools._ORIGIN_UR:
  87880. x_start = header.width - 1;
  87881. x_step = -1;
  87882. x_end = -1;
  87883. y_start = 0;
  87884. y_step = 1;
  87885. y_end = header.height;
  87886. break;
  87887. case TGATools._ORIGIN_BR:
  87888. x_start = header.width - 1;
  87889. x_step = -1;
  87890. x_end = -1;
  87891. y_start = header.height - 1;
  87892. y_step = -1;
  87893. y_end = -1;
  87894. break;
  87895. }
  87896. // Load the specify method
  87897. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87898. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87899. var engine = texture.getEngine();
  87900. engine._uploadDataToTextureDirectly(texture, imageData);
  87901. };
  87902. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87903. var image = pixel_data, colormap = palettes;
  87904. var width = header.width, height = header.height;
  87905. var color, i = 0, x, y;
  87906. var imageData = new Uint8Array(width * height * 4);
  87907. for (y = y_start; y !== y_end; y += y_step) {
  87908. for (x = x_start; x !== x_end; x += x_step, i++) {
  87909. color = image[i];
  87910. imageData[(x + width * y) * 4 + 3] = 255;
  87911. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87912. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87913. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87914. }
  87915. }
  87916. return imageData;
  87917. };
  87918. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87919. var image = pixel_data;
  87920. var width = header.width, height = header.height;
  87921. var color, i = 0, x, y;
  87922. var imageData = new Uint8Array(width * height * 4);
  87923. for (y = y_start; y !== y_end; y += y_step) {
  87924. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87925. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87926. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87927. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87928. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87929. imageData[(x + width * y) * 4 + 0] = r;
  87930. imageData[(x + width * y) * 4 + 1] = g;
  87931. imageData[(x + width * y) * 4 + 2] = b;
  87932. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87933. }
  87934. }
  87935. return imageData;
  87936. };
  87937. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87938. var image = pixel_data;
  87939. var width = header.width, height = header.height;
  87940. var i = 0, x, y;
  87941. var imageData = new Uint8Array(width * height * 4);
  87942. for (y = y_start; y !== y_end; y += y_step) {
  87943. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87944. imageData[(x + width * y) * 4 + 3] = 255;
  87945. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87946. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87947. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87948. }
  87949. }
  87950. return imageData;
  87951. };
  87952. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87953. var image = pixel_data;
  87954. var width = header.width, height = header.height;
  87955. var i = 0, x, y;
  87956. var imageData = new Uint8Array(width * height * 4);
  87957. for (y = y_start; y !== y_end; y += y_step) {
  87958. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87959. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87960. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87961. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87962. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87963. }
  87964. }
  87965. return imageData;
  87966. };
  87967. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87968. var image = pixel_data;
  87969. var width = header.width, height = header.height;
  87970. var color, i = 0, x, y;
  87971. var imageData = new Uint8Array(width * height * 4);
  87972. for (y = y_start; y !== y_end; y += y_step) {
  87973. for (x = x_start; x !== x_end; x += x_step, i++) {
  87974. color = image[i];
  87975. imageData[(x + width * y) * 4 + 0] = color;
  87976. imageData[(x + width * y) * 4 + 1] = color;
  87977. imageData[(x + width * y) * 4 + 2] = color;
  87978. imageData[(x + width * y) * 4 + 3] = 255;
  87979. }
  87980. }
  87981. return imageData;
  87982. };
  87983. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87984. var image = pixel_data;
  87985. var width = header.width, height = header.height;
  87986. var i = 0, x, y;
  87987. var imageData = new Uint8Array(width * height * 4);
  87988. for (y = y_start; y !== y_end; y += y_step) {
  87989. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87990. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87991. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87992. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87993. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87994. }
  87995. }
  87996. return imageData;
  87997. };
  87998. //private static _TYPE_NO_DATA = 0;
  87999. TGATools._TYPE_INDEXED = 1;
  88000. TGATools._TYPE_RGB = 2;
  88001. TGATools._TYPE_GREY = 3;
  88002. TGATools._TYPE_RLE_INDEXED = 9;
  88003. TGATools._TYPE_RLE_RGB = 10;
  88004. TGATools._TYPE_RLE_GREY = 11;
  88005. TGATools._ORIGIN_MASK = 0x30;
  88006. TGATools._ORIGIN_SHIFT = 0x04;
  88007. TGATools._ORIGIN_BL = 0x00;
  88008. TGATools._ORIGIN_BR = 0x01;
  88009. TGATools._ORIGIN_UL = 0x02;
  88010. TGATools._ORIGIN_UR = 0x03;
  88011. return TGATools;
  88012. }());
  88013. BABYLON.TGATools = TGATools;
  88014. })(BABYLON || (BABYLON = {}));
  88015. //# sourceMappingURL=babylon.tga.js.map
  88016. var BABYLON;
  88017. (function (BABYLON) {
  88018. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  88019. // All values and structures referenced from:
  88020. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  88021. var DDS_MAGIC = 0x20534444;
  88022. var
  88023. //DDSD_CAPS = 0x1,
  88024. //DDSD_HEIGHT = 0x2,
  88025. //DDSD_WIDTH = 0x4,
  88026. //DDSD_PITCH = 0x8,
  88027. //DDSD_PIXELFORMAT = 0x1000,
  88028. DDSD_MIPMAPCOUNT = 0x20000;
  88029. //DDSD_LINEARSIZE = 0x80000,
  88030. //DDSD_DEPTH = 0x800000;
  88031. // var DDSCAPS_COMPLEX = 0x8,
  88032. // DDSCAPS_MIPMAP = 0x400000,
  88033. // DDSCAPS_TEXTURE = 0x1000;
  88034. var DDSCAPS2_CUBEMAP = 0x200;
  88035. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  88036. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  88037. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  88038. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  88039. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  88040. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  88041. // DDSCAPS2_VOLUME = 0x200000;
  88042. var
  88043. //DDPF_ALPHAPIXELS = 0x1,
  88044. //DDPF_ALPHA = 0x2,
  88045. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  88046. //DDPF_YUV = 0x200,
  88047. DDPF_LUMINANCE = 0x20000;
  88048. function FourCCToInt32(value) {
  88049. return value.charCodeAt(0) +
  88050. (value.charCodeAt(1) << 8) +
  88051. (value.charCodeAt(2) << 16) +
  88052. (value.charCodeAt(3) << 24);
  88053. }
  88054. function Int32ToFourCC(value) {
  88055. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  88056. }
  88057. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  88058. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  88059. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  88060. var FOURCC_DX10 = FourCCToInt32("DX10");
  88061. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  88062. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  88063. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  88064. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  88065. var headerLengthInt = 31; // The header length in 32 bit ints
  88066. // Offsets into the header array
  88067. var off_magic = 0;
  88068. var off_size = 1;
  88069. var off_flags = 2;
  88070. var off_height = 3;
  88071. var off_width = 4;
  88072. var off_mipmapCount = 7;
  88073. var off_pfFlags = 20;
  88074. var off_pfFourCC = 21;
  88075. var off_RGBbpp = 22;
  88076. var off_RMask = 23;
  88077. var off_GMask = 24;
  88078. var off_BMask = 25;
  88079. var off_AMask = 26;
  88080. // var off_caps1 = 27;
  88081. var off_caps2 = 28;
  88082. // var off_caps3 = 29;
  88083. // var off_caps4 = 30;
  88084. var off_dxgiFormat = 32;
  88085. ;
  88086. var DDSTools = /** @class */ (function () {
  88087. function DDSTools() {
  88088. }
  88089. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88090. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88091. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88092. var mipmapCount = 1;
  88093. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88094. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88095. }
  88096. var fourCC = header[off_pfFourCC];
  88097. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88098. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88099. switch (fourCC) {
  88100. case FOURCC_D3DFMT_R16G16B16A16F:
  88101. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88102. break;
  88103. case FOURCC_D3DFMT_R32G32B32A32F:
  88104. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88105. break;
  88106. case FOURCC_DX10:
  88107. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88108. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88109. break;
  88110. }
  88111. }
  88112. return {
  88113. width: header[off_width],
  88114. height: header[off_height],
  88115. mipmapCount: mipmapCount,
  88116. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88117. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88118. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88119. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88120. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88121. dxgiFormat: dxgiFormat,
  88122. textureType: textureType
  88123. };
  88124. };
  88125. DDSTools._ToHalfFloat = function (value) {
  88126. if (!DDSTools._FloatView) {
  88127. DDSTools._FloatView = new Float32Array(1);
  88128. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88129. }
  88130. DDSTools._FloatView[0] = value;
  88131. var x = DDSTools._Int32View[0];
  88132. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88133. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88134. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88135. /* If zero, or denormal, or exponent underflows too much for a denormal
  88136. * half, return signed zero. */
  88137. if (e < 103) {
  88138. return bits;
  88139. }
  88140. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88141. if (e > 142) {
  88142. bits |= 0x7c00;
  88143. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88144. * not Inf, so make sure we set one mantissa bit too. */
  88145. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88146. return bits;
  88147. }
  88148. /* If exponent underflows but not too much, return a denormal */
  88149. if (e < 113) {
  88150. m |= 0x0800;
  88151. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88152. * to 1, which is OK. */
  88153. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88154. return bits;
  88155. }
  88156. bits |= ((e - 112) << 10) | (m >> 1);
  88157. bits += m & 1;
  88158. return bits;
  88159. };
  88160. DDSTools._FromHalfFloat = function (value) {
  88161. var s = (value & 0x8000) >> 15;
  88162. var e = (value & 0x7C00) >> 10;
  88163. var f = value & 0x03FF;
  88164. if (e === 0) {
  88165. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88166. }
  88167. else if (e == 0x1F) {
  88168. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88169. }
  88170. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88171. };
  88172. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88173. var destArray = new Float32Array(dataLength);
  88174. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88175. var index = 0;
  88176. for (var y = 0; y < height; y++) {
  88177. for (var x = 0; x < width; x++) {
  88178. var srcPos = (x + y * width) * 4;
  88179. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  88180. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  88181. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  88182. if (DDSTools.StoreLODInAlphaChannel) {
  88183. destArray[index + 3] = lod;
  88184. }
  88185. else {
  88186. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  88187. }
  88188. index += 4;
  88189. }
  88190. }
  88191. return destArray;
  88192. };
  88193. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88194. if (DDSTools.StoreLODInAlphaChannel) {
  88195. var destArray = new Uint16Array(dataLength);
  88196. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88197. var index = 0;
  88198. for (var y = 0; y < height; y++) {
  88199. for (var x = 0; x < width; x++) {
  88200. var srcPos = (x + y * width) * 4;
  88201. destArray[index] = srcData[srcPos];
  88202. destArray[index + 1] = srcData[srcPos + 1];
  88203. destArray[index + 2] = srcData[srcPos + 2];
  88204. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  88205. index += 4;
  88206. }
  88207. }
  88208. return destArray;
  88209. }
  88210. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88211. };
  88212. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88213. if (DDSTools.StoreLODInAlphaChannel) {
  88214. var destArray = new Float32Array(dataLength);
  88215. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88216. var index = 0;
  88217. for (var y = 0; y < height; y++) {
  88218. for (var x = 0; x < width; x++) {
  88219. var srcPos = (x + y * width) * 4;
  88220. destArray[index] = srcData[srcPos];
  88221. destArray[index + 1] = srcData[srcPos + 1];
  88222. destArray[index + 2] = srcData[srcPos + 2];
  88223. destArray[index + 3] = lod;
  88224. index += 4;
  88225. }
  88226. }
  88227. return destArray;
  88228. }
  88229. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88230. };
  88231. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88232. var destArray = new Uint8Array(dataLength);
  88233. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88234. var index = 0;
  88235. for (var y = 0; y < height; y++) {
  88236. for (var x = 0; x < width; x++) {
  88237. var srcPos = (x + y * width) * 4;
  88238. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88239. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88240. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88241. if (DDSTools.StoreLODInAlphaChannel) {
  88242. destArray[index + 3] = lod;
  88243. }
  88244. else {
  88245. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88246. }
  88247. index += 4;
  88248. }
  88249. }
  88250. return destArray;
  88251. };
  88252. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88253. var destArray = new Uint8Array(dataLength);
  88254. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88255. var index = 0;
  88256. for (var y = 0; y < height; y++) {
  88257. for (var x = 0; x < width; x++) {
  88258. var srcPos = (x + y * width) * 4;
  88259. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88260. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88261. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88262. if (DDSTools.StoreLODInAlphaChannel) {
  88263. destArray[index + 3] = lod;
  88264. }
  88265. else {
  88266. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88267. }
  88268. index += 4;
  88269. }
  88270. }
  88271. return destArray;
  88272. };
  88273. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88274. var byteArray = new Uint8Array(dataLength);
  88275. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88276. var index = 0;
  88277. for (var y = 0; y < height; y++) {
  88278. for (var x = 0; x < width; x++) {
  88279. var srcPos = (x + y * width) * 4;
  88280. byteArray[index] = srcData[srcPos + rOffset];
  88281. byteArray[index + 1] = srcData[srcPos + gOffset];
  88282. byteArray[index + 2] = srcData[srcPos + bOffset];
  88283. byteArray[index + 3] = srcData[srcPos + aOffset];
  88284. index += 4;
  88285. }
  88286. }
  88287. return byteArray;
  88288. };
  88289. DDSTools._ExtractLongWordOrder = function (value) {
  88290. if (value === 0 || value === 255 || value === -16777216) {
  88291. return 0;
  88292. }
  88293. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88294. };
  88295. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88296. var byteArray = new Uint8Array(dataLength);
  88297. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88298. var index = 0;
  88299. for (var y = 0; y < height; y++) {
  88300. for (var x = 0; x < width; x++) {
  88301. var srcPos = (x + y * width) * 3;
  88302. byteArray[index] = srcData[srcPos + rOffset];
  88303. byteArray[index + 1] = srcData[srcPos + gOffset];
  88304. byteArray[index + 2] = srcData[srcPos + bOffset];
  88305. index += 3;
  88306. }
  88307. }
  88308. return byteArray;
  88309. };
  88310. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88311. var byteArray = new Uint8Array(dataLength);
  88312. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88313. var index = 0;
  88314. for (var y = 0; y < height; y++) {
  88315. for (var x = 0; x < width; x++) {
  88316. var srcPos = (x + y * width);
  88317. byteArray[index] = srcData[srcPos];
  88318. index++;
  88319. }
  88320. }
  88321. return byteArray;
  88322. };
  88323. /**
  88324. * Uploads DDS Levels to a Babylon Texture
  88325. * @hidden
  88326. */
  88327. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88328. if (lodIndex === void 0) { lodIndex = -1; }
  88329. var sphericalPolynomialFaces = null;
  88330. if (info.sphericalPolynomial) {
  88331. sphericalPolynomialFaces = new Array();
  88332. }
  88333. var ext = engine.getCaps().s3tc;
  88334. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88335. var fourCC, width, height, dataLength = 0, dataOffset;
  88336. var byteArray, mipmapCount, mip;
  88337. var internalCompressedFormat = 0;
  88338. var blockBytes = 1;
  88339. if (header[off_magic] !== DDS_MAGIC) {
  88340. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88341. return;
  88342. }
  88343. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88344. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88345. return;
  88346. }
  88347. if (info.isCompressed && !ext) {
  88348. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88349. return;
  88350. }
  88351. var bpp = header[off_RGBbpp];
  88352. dataOffset = header[off_size] + 4;
  88353. var computeFormats = false;
  88354. if (info.isFourCC) {
  88355. fourCC = header[off_pfFourCC];
  88356. switch (fourCC) {
  88357. case FOURCC_DXT1:
  88358. blockBytes = 8;
  88359. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88360. break;
  88361. case FOURCC_DXT3:
  88362. blockBytes = 16;
  88363. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88364. break;
  88365. case FOURCC_DXT5:
  88366. blockBytes = 16;
  88367. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88368. break;
  88369. case FOURCC_D3DFMT_R16G16B16A16F:
  88370. computeFormats = true;
  88371. break;
  88372. case FOURCC_D3DFMT_R32G32B32A32F:
  88373. computeFormats = true;
  88374. break;
  88375. case FOURCC_DX10:
  88376. // There is an additionnal header so dataOffset need to be changed
  88377. dataOffset += 5 * 4; // 5 uints
  88378. var supported = false;
  88379. switch (info.dxgiFormat) {
  88380. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88381. computeFormats = true;
  88382. supported = true;
  88383. break;
  88384. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88385. info.isRGB = true;
  88386. info.isFourCC = false;
  88387. bpp = 32;
  88388. supported = true;
  88389. break;
  88390. }
  88391. if (supported) {
  88392. break;
  88393. }
  88394. default:
  88395. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88396. return;
  88397. }
  88398. }
  88399. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88400. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88401. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88402. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88403. if (computeFormats) {
  88404. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88405. }
  88406. mipmapCount = 1;
  88407. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88408. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88409. }
  88410. for (var face = 0; face < faces; face++) {
  88411. width = header[off_width];
  88412. height = header[off_height];
  88413. for (mip = 0; mip < mipmapCount; ++mip) {
  88414. if (lodIndex === -1 || lodIndex === mip) {
  88415. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88416. var i = (lodIndex === -1) ? mip : 0;
  88417. if (!info.isCompressed && info.isFourCC) {
  88418. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88419. dataLength = width * height * 4;
  88420. var floatArray = null;
  88421. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88422. if (bpp === 128) {
  88423. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88424. if (sphericalPolynomialFaces && i == 0) {
  88425. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88426. }
  88427. }
  88428. else if (bpp === 64) {
  88429. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88430. if (sphericalPolynomialFaces && i == 0) {
  88431. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88432. }
  88433. }
  88434. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88435. }
  88436. else {
  88437. if (bpp === 128) {
  88438. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88439. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88440. if (sphericalPolynomialFaces && i == 0) {
  88441. sphericalPolynomialFaces.push(floatArray);
  88442. }
  88443. }
  88444. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88445. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88446. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88447. if (sphericalPolynomialFaces && i == 0) {
  88448. sphericalPolynomialFaces.push(floatArray);
  88449. }
  88450. }
  88451. else { // 64
  88452. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88453. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88454. if (sphericalPolynomialFaces && i == 0) {
  88455. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88456. }
  88457. }
  88458. }
  88459. if (floatArray) {
  88460. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88461. }
  88462. }
  88463. else if (info.isRGB) {
  88464. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88465. if (bpp === 24) {
  88466. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88467. dataLength = width * height * 3;
  88468. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88469. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88470. }
  88471. else { // 32
  88472. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88473. dataLength = width * height * 4;
  88474. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88475. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88476. }
  88477. }
  88478. else if (info.isLuminance) {
  88479. var unpackAlignment = engine._getUnpackAlignement();
  88480. var unpaddedRowSize = width;
  88481. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88482. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88483. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88484. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88485. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88486. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88487. }
  88488. else {
  88489. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88490. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88491. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88492. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88493. }
  88494. }
  88495. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88496. width *= 0.5;
  88497. height *= 0.5;
  88498. width = Math.max(1.0, width);
  88499. height = Math.max(1.0, height);
  88500. }
  88501. if (currentFace !== undefined) {
  88502. // Loading a single face
  88503. break;
  88504. }
  88505. }
  88506. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88507. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88508. size: header[off_width],
  88509. right: sphericalPolynomialFaces[0],
  88510. left: sphericalPolynomialFaces[1],
  88511. up: sphericalPolynomialFaces[2],
  88512. down: sphericalPolynomialFaces[3],
  88513. front: sphericalPolynomialFaces[4],
  88514. back: sphericalPolynomialFaces[5],
  88515. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88516. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88517. gammaSpace: false,
  88518. });
  88519. }
  88520. else {
  88521. info.sphericalPolynomial = undefined;
  88522. }
  88523. };
  88524. DDSTools.StoreLODInAlphaChannel = false;
  88525. return DDSTools;
  88526. }());
  88527. BABYLON.DDSTools = DDSTools;
  88528. })(BABYLON || (BABYLON = {}));
  88529. //# sourceMappingURL=babylon.dds.js.map
  88530. var BABYLON;
  88531. (function (BABYLON) {
  88532. /**
  88533. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88534. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88535. */
  88536. var KhronosTextureContainer = /** @class */ (function () {
  88537. /**
  88538. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88539. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88540. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88541. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88542. */
  88543. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88544. this.arrayBuffer = arrayBuffer;
  88545. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88546. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88547. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88548. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88549. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88550. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88551. BABYLON.Tools.Error("texture missing KTX identifier");
  88552. return;
  88553. }
  88554. // load the reset of the header in native 32 bit int
  88555. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88556. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88557. var oppositeEndianess = header[0] === 0x01020304;
  88558. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88559. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88560. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88561. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88562. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88563. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88564. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88565. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88566. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88567. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88568. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88569. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88570. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88571. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88572. if (this.glType !== 0) {
  88573. BABYLON.Tools.Error("only compressed formats currently supported");
  88574. return;
  88575. }
  88576. else {
  88577. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88578. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88579. }
  88580. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88581. BABYLON.Tools.Error("only 2D textures currently supported");
  88582. return;
  88583. }
  88584. if (this.numberOfArrayElements !== 0) {
  88585. BABYLON.Tools.Error("texture arrays not currently supported");
  88586. return;
  88587. }
  88588. if (this.numberOfFaces !== facesExpected) {
  88589. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88590. return;
  88591. }
  88592. // we now have a completely validated file, so could use existence of loadType as success
  88593. // would need to make this more elaborate & adjust checks above to support more than one load type
  88594. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88595. }
  88596. // not as fast hardware based, but will probably never need to use
  88597. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88598. return ((val & 0xFF) << 24)
  88599. | ((val & 0xFF00) << 8)
  88600. | ((val >> 8) & 0xFF00)
  88601. | ((val >> 24) & 0xFF);
  88602. };
  88603. /**
  88604. * Uploads KTX content to a Babylon Texture.
  88605. * It is assumed that the texture has already been created & is currently bound
  88606. * @hidden
  88607. */
  88608. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88609. switch (this.loadType) {
  88610. case KhronosTextureContainer.COMPRESSED_2D:
  88611. this._upload2DCompressedLevels(texture, loadMipmaps);
  88612. break;
  88613. case KhronosTextureContainer.TEX_2D:
  88614. case KhronosTextureContainer.COMPRESSED_3D:
  88615. case KhronosTextureContainer.TEX_3D:
  88616. }
  88617. };
  88618. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88619. // initialize width & height for level 1
  88620. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88621. var width = this.pixelWidth;
  88622. var height = this.pixelHeight;
  88623. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88624. for (var level = 0; level < mipmapCount; level++) {
  88625. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88626. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88627. for (var face = 0; face < this.numberOfFaces; face++) {
  88628. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88629. var engine = texture.getEngine();
  88630. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88631. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88632. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88633. }
  88634. width = Math.max(1.0, width * 0.5);
  88635. height = Math.max(1.0, height * 0.5);
  88636. }
  88637. };
  88638. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88639. // load types
  88640. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88641. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88642. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88643. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88644. return KhronosTextureContainer;
  88645. }());
  88646. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88647. })(BABYLON || (BABYLON = {}));
  88648. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88649. var BABYLON;
  88650. (function (BABYLON) {
  88651. /**
  88652. * Renders a layer on top of an existing scene
  88653. */
  88654. var UtilityLayerRenderer = /** @class */ (function () {
  88655. /**
  88656. * Instantiates a UtilityLayerRenderer
  88657. * @param originalScene the original scene that will be rendered on top of
  88658. */
  88659. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88660. var _this = this;
  88661. this.originalScene = originalScene;
  88662. this._pointerCaptures = {};
  88663. this._lastPointerEvents = {};
  88664. /**
  88665. * If the utility layer should automatically be rendered on top of existing scene
  88666. */
  88667. this.shouldRender = true;
  88668. /**
  88669. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88670. */
  88671. this.onlyCheckPointerDownEvents = true;
  88672. /**
  88673. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88674. */
  88675. this.processAllEvents = false;
  88676. /**
  88677. * Observable raised when the pointer move from the utility layer scene to the main scene
  88678. */
  88679. this.onPointerOutObservable = new BABYLON.Observable();
  88680. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88681. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88682. this.utilityLayerScene._allowPostProcessClear = false;
  88683. originalScene.getEngine().scenes.pop();
  88684. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88685. this.utilityLayerScene.detachControl();
  88686. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88687. if (!_this.processAllEvents) {
  88688. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88689. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88690. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88691. return;
  88692. }
  88693. }
  88694. var pointerEvent = (prePointerInfo.event);
  88695. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88696. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88697. return;
  88698. }
  88699. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88700. if (!prePointerInfo.ray && utilityScenePick) {
  88701. prePointerInfo.ray = utilityScenePick.ray;
  88702. }
  88703. // always fire the prepointer oversvable
  88704. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88705. // allow every non pointer down event to flow to the utility layer
  88706. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88707. if (!prePointerInfo.skipOnPointerObservable) {
  88708. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88709. }
  88710. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88711. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88712. }
  88713. return;
  88714. }
  88715. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88716. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88717. if (utilityScenePick && utilityScenePick.hit) {
  88718. if (!prePointerInfo.skipOnPointerObservable) {
  88719. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88720. }
  88721. prePointerInfo.skipOnPointerObservable = true;
  88722. }
  88723. }
  88724. else {
  88725. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88726. var pointerEvent_1 = (prePointerInfo.event);
  88727. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88728. if (originalScenePick && utilityScenePick) {
  88729. // No pick in utility scene
  88730. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88731. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88732. // We touched an utility mesh present in the main scene
  88733. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88734. prePointerInfo.skipOnPointerObservable = true;
  88735. }
  88736. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88737. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88738. }
  88739. }
  88740. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88741. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88742. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88743. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88744. }
  88745. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88746. // We have a pick in both scenes but main is closer than utility
  88747. // We touched an utility mesh present in the main scene
  88748. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88749. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88750. prePointerInfo.skipOnPointerObservable = true;
  88751. }
  88752. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88753. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88754. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88755. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88756. }
  88757. }
  88758. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88759. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88760. }
  88761. }
  88762. }
  88763. });
  88764. // Render directly on top of existing scene without clearing
  88765. this.utilityLayerScene.autoClear = false;
  88766. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88767. if (_this.shouldRender) {
  88768. _this.render();
  88769. }
  88770. });
  88771. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88772. _this.dispose();
  88773. });
  88774. this._updateCamera();
  88775. }
  88776. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88777. get: function () {
  88778. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88779. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88780. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88781. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88782. });
  88783. }
  88784. return UtilityLayerRenderer._DefaultUtilityLayer;
  88785. },
  88786. enumerable: true,
  88787. configurable: true
  88788. });
  88789. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88790. if (!prePointerInfo.skipOnPointerObservable) {
  88791. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88792. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88793. }
  88794. };
  88795. /**
  88796. * Renders the utility layers scene on top of the original scene
  88797. */
  88798. UtilityLayerRenderer.prototype.render = function () {
  88799. this._updateCamera();
  88800. if (this.utilityLayerScene.activeCamera) {
  88801. // Set the camera's scene to utility layers scene
  88802. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  88803. var camera = this.utilityLayerScene.activeCamera;
  88804. camera._scene = this.utilityLayerScene;
  88805. if (camera.leftCamera) {
  88806. camera.leftCamera._scene = this.utilityLayerScene;
  88807. }
  88808. if (camera.rightCamera) {
  88809. camera.rightCamera._scene = this.utilityLayerScene;
  88810. }
  88811. this.utilityLayerScene.render(false);
  88812. // Reset camera's scene back to original
  88813. camera._scene = oldScene;
  88814. if (camera.leftCamera) {
  88815. camera.leftCamera._scene = oldScene;
  88816. }
  88817. if (camera.rightCamera) {
  88818. camera.rightCamera._scene = oldScene;
  88819. }
  88820. }
  88821. };
  88822. /**
  88823. * Disposes of the renderer
  88824. */
  88825. UtilityLayerRenderer.prototype.dispose = function () {
  88826. this.onPointerOutObservable.clear();
  88827. if (this._afterRenderObserver) {
  88828. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88829. }
  88830. if (this._sceneDisposeObserver) {
  88831. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88832. }
  88833. if (this._originalPointerObserver) {
  88834. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88835. }
  88836. this.utilityLayerScene.dispose();
  88837. };
  88838. UtilityLayerRenderer.prototype._updateCamera = function () {
  88839. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88840. };
  88841. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88842. return UtilityLayerRenderer;
  88843. }());
  88844. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88845. })(BABYLON || (BABYLON = {}));
  88846. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88847. //# sourceMappingURL=babylon.behavior.js.map
  88848. var BABYLON;
  88849. (function (BABYLON) {
  88850. /**
  88851. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88852. */
  88853. var PointerDragBehavior = /** @class */ (function () {
  88854. /**
  88855. * Creates a pointer drag behavior that can be attached to a mesh
  88856. * @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)
  88857. */
  88858. function PointerDragBehavior(options) {
  88859. /**
  88860. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  88861. */
  88862. this.maxDragAngle = 0;
  88863. /**
  88864. * @hidden
  88865. */
  88866. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88867. /**
  88868. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88869. */
  88870. this.currentDraggingPointerID = -1;
  88871. /**
  88872. * If the behavior is currently in a dragging state
  88873. */
  88874. this.dragging = false;
  88875. /**
  88876. * 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)
  88877. */
  88878. this.dragDeltaRatio = 0.2;
  88879. /**
  88880. * If the drag plane orientation should be updated during the dragging (Default: true)
  88881. */
  88882. this.updateDragPlane = true;
  88883. // Debug mode will display drag planes to help visualize behavior
  88884. this._debugMode = false;
  88885. this._moving = false;
  88886. /**
  88887. * Fires each time the attached mesh is dragged with the pointer
  88888. * * delta between last drag position and current drag position in world space
  88889. * * dragDistance along the drag axis
  88890. * * dragPlaneNormal normal of the current drag plane used during the drag
  88891. * * dragPlanePoint in world space where the drag intersects the drag plane
  88892. */
  88893. this.onDragObservable = new BABYLON.Observable();
  88894. /**
  88895. * Fires each time a drag begins (eg. mouse down on mesh)
  88896. */
  88897. this.onDragStartObservable = new BABYLON.Observable();
  88898. /**
  88899. * Fires each time a drag ends (eg. mouse release after drag)
  88900. */
  88901. this.onDragEndObservable = new BABYLON.Observable();
  88902. /**
  88903. * If the attached mesh should be moved when dragged
  88904. */
  88905. this.moveAttached = true;
  88906. /**
  88907. * If the drag behavior will react to drag events (Default: true)
  88908. */
  88909. this.enabled = true;
  88910. /**
  88911. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88912. */
  88913. this.useObjectOrienationForDragging = true;
  88914. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88915. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88916. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88917. // Variables to avoid instantiation in the below method
  88918. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88919. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88920. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88921. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88922. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88923. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88924. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88925. this._options = options ? options : {};
  88926. var optionCount = 0;
  88927. if (this._options.dragAxis) {
  88928. optionCount++;
  88929. }
  88930. if (this._options.dragPlaneNormal) {
  88931. optionCount++;
  88932. }
  88933. if (optionCount > 1) {
  88934. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88935. }
  88936. }
  88937. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88938. /**
  88939. * The name of the behavior
  88940. */
  88941. get: function () {
  88942. return "PointerDrag";
  88943. },
  88944. enumerable: true,
  88945. configurable: true
  88946. });
  88947. /**
  88948. * Initializes the behavior
  88949. */
  88950. PointerDragBehavior.prototype.init = function () { };
  88951. /**
  88952. * Attaches the drag behavior the passed in mesh
  88953. * @param ownerNode The mesh that will be dragged around once attached
  88954. */
  88955. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88956. var _this = this;
  88957. this._scene = ownerNode.getScene();
  88958. this._attachedNode = ownerNode;
  88959. // Initialize drag plane to not interfere with existing scene
  88960. if (!PointerDragBehavior._planeScene) {
  88961. if (this._debugMode) {
  88962. PointerDragBehavior._planeScene = this._scene;
  88963. }
  88964. else {
  88965. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88966. PointerDragBehavior._planeScene.detachControl();
  88967. this._scene.getEngine().scenes.pop();
  88968. }
  88969. }
  88970. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88971. // State of the drag
  88972. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88973. var delta = new BABYLON.Vector3(0, 0, 0);
  88974. var dragLength = 0;
  88975. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88976. var pickPredicate = function (m) {
  88977. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88978. };
  88979. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88980. if (!_this.enabled) {
  88981. return;
  88982. }
  88983. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88984. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88985. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88986. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88987. if (pickedPoint) {
  88988. _this.dragging = true;
  88989. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88990. _this.lastDragPosition.copyFrom(pickedPoint);
  88991. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88992. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88993. }
  88994. }
  88995. }
  88996. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88997. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88998. _this.releaseDrag();
  88999. }
  89000. }
  89001. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89002. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89003. _this._moving = true;
  89004. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89005. if (pickedPoint) {
  89006. if (_this.updateDragPlane) {
  89007. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89008. }
  89009. // depending on the drag mode option drag accordingly
  89010. if (_this._options.dragAxis) {
  89011. // Convert local drag axis to world
  89012. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89013. // Project delta drag from the drag plane onto the drag axis
  89014. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89015. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89016. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89017. }
  89018. else {
  89019. dragLength = delta.length();
  89020. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89021. }
  89022. targetPosition.addInPlace(delta);
  89023. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89024. _this.lastDragPosition.copyFrom(pickedPoint);
  89025. }
  89026. }
  89027. }
  89028. });
  89029. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89030. if (_this._moving && _this.moveAttached) {
  89031. // Slowly move mesh to avoid jitter
  89032. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89033. _this._tmpVector.scaleInPlace(0.2);
  89034. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89035. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89036. }
  89037. });
  89038. };
  89039. PointerDragBehavior.prototype.releaseDrag = function () {
  89040. this.dragging = false;
  89041. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89042. this.currentDraggingPointerID = -1;
  89043. this._moving = false;
  89044. };
  89045. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89046. var _this = this;
  89047. if (!ray) {
  89048. return null;
  89049. }
  89050. // Calculate angle between plane normal and ray
  89051. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89052. // Correct if ray is casted from oposite side
  89053. if (angle > Math.PI / 2) {
  89054. angle = Math.PI - angle;
  89055. }
  89056. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89057. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89058. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89059. // Invert ray direction along the towards object axis
  89060. this._tmpVector.copyFrom(ray.direction);
  89061. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89062. this._alternatePickedPoint.normalize();
  89063. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89064. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89065. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89066. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89067. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89068. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89069. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89070. return this._alternatePickedPoint;
  89071. }
  89072. else {
  89073. return null;
  89074. }
  89075. }
  89076. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89077. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89078. return pickResult.pickedPoint;
  89079. }
  89080. else {
  89081. return null;
  89082. }
  89083. };
  89084. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89085. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89086. this._pointA.copyFrom(dragPlanePosition);
  89087. if (this._options.dragAxis) {
  89088. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89089. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89090. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89091. ray.origin.subtractToRef(this._pointA, this._pointC);
  89092. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89093. // Get perpendicular line from direction to camera and drag axis
  89094. this._pointB.subtractToRef(this._pointA, this._lineA);
  89095. this._pointC.subtractToRef(this._pointA, this._lineB);
  89096. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89097. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89098. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89099. this._lookAt.normalize();
  89100. this._dragPlane.position.copyFrom(this._pointA);
  89101. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89102. this._dragPlane.lookAt(this._lookAt);
  89103. }
  89104. else if (this._options.dragPlaneNormal) {
  89105. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89106. this._dragPlane.position.copyFrom(this._pointA);
  89107. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89108. this._dragPlane.lookAt(this._lookAt);
  89109. }
  89110. else {
  89111. this._dragPlane.position.copyFrom(this._pointA);
  89112. this._dragPlane.lookAt(ray.origin);
  89113. }
  89114. this._dragPlane.computeWorldMatrix(true);
  89115. };
  89116. /**
  89117. * Detaches the behavior from the mesh
  89118. */
  89119. PointerDragBehavior.prototype.detach = function () {
  89120. if (this._pointerObserver) {
  89121. this._scene.onPointerObservable.remove(this._pointerObserver);
  89122. }
  89123. if (this._beforeRenderObserver) {
  89124. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89125. }
  89126. };
  89127. return PointerDragBehavior;
  89128. }());
  89129. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89130. })(BABYLON || (BABYLON = {}));
  89131. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89132. var BABYLON;
  89133. (function (BABYLON) {
  89134. /**
  89135. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89136. */
  89137. var MultiPointerScaleBehavior = /** @class */ (function () {
  89138. function MultiPointerScaleBehavior() {
  89139. this._startDistance = 0;
  89140. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89141. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89142. this._sceneRenderObserver = null;
  89143. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89144. this._dragBehaviorA.moveAttached = false;
  89145. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89146. this._dragBehaviorB.moveAttached = false;
  89147. }
  89148. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89149. /**
  89150. * The name of the behavior
  89151. */
  89152. get: function () {
  89153. return "MultiPointerScale";
  89154. },
  89155. enumerable: true,
  89156. configurable: true
  89157. });
  89158. /**
  89159. * Initializes the behavior
  89160. */
  89161. MultiPointerScaleBehavior.prototype.init = function () { };
  89162. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89163. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89164. };
  89165. /**
  89166. * Attaches the scale behavior the passed in mesh
  89167. * @param ownerNode The mesh that will be scaled around once attached
  89168. */
  89169. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89170. var _this = this;
  89171. this._ownerNode = ownerNode;
  89172. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89173. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89174. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89175. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89176. _this._dragBehaviorA.releaseDrag();
  89177. }
  89178. else {
  89179. _this._initialScale.copyFrom(ownerNode.scaling);
  89180. _this._startDistance = _this._getCurrentDistance();
  89181. }
  89182. }
  89183. });
  89184. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89185. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89186. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89187. _this._dragBehaviorB.releaseDrag();
  89188. }
  89189. else {
  89190. _this._initialScale.copyFrom(ownerNode.scaling);
  89191. _this._startDistance = _this._getCurrentDistance();
  89192. }
  89193. }
  89194. });
  89195. // Once both drag behaviors are active scale based on the distance between the two pointers
  89196. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89197. behavior.onDragObservable.add(function () {
  89198. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89199. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89200. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89201. }
  89202. });
  89203. });
  89204. ownerNode.addBehavior(this._dragBehaviorA);
  89205. ownerNode.addBehavior(this._dragBehaviorB);
  89206. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89207. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89208. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89209. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89210. if (change.length() > 0.01) {
  89211. ownerNode.scaling.addInPlace(change);
  89212. }
  89213. }
  89214. });
  89215. };
  89216. /**
  89217. * Detaches the behavior from the mesh
  89218. */
  89219. MultiPointerScaleBehavior.prototype.detach = function () {
  89220. var _this = this;
  89221. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89222. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89223. behavior.onDragStartObservable.clear();
  89224. behavior.onDragObservable.clear();
  89225. _this._ownerNode.removeBehavior(behavior);
  89226. });
  89227. };
  89228. return MultiPointerScaleBehavior;
  89229. }());
  89230. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89231. })(BABYLON || (BABYLON = {}));
  89232. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89233. var BABYLON;
  89234. (function (BABYLON) {
  89235. /**
  89236. * 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
  89237. */
  89238. var SixDofDragBehavior = /** @class */ (function () {
  89239. function SixDofDragBehavior() {
  89240. this._sceneRenderObserver = null;
  89241. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89242. this._moving = false;
  89243. this._startingOrientation = new BABYLON.Quaternion();
  89244. /**
  89245. * 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: 3)
  89246. */
  89247. this.zDragFactor = 3;
  89248. /**
  89249. * If the behavior is currently in a dragging state
  89250. */
  89251. this.dragging = false;
  89252. /**
  89253. * 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)
  89254. */
  89255. this.dragDeltaRatio = 0.2;
  89256. /**
  89257. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89258. */
  89259. this.currentDraggingPointerID = -1;
  89260. }
  89261. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89262. /**
  89263. * The name of the behavior
  89264. */
  89265. get: function () {
  89266. return "SixDofDrag";
  89267. },
  89268. enumerable: true,
  89269. configurable: true
  89270. });
  89271. /**
  89272. * Initializes the behavior
  89273. */
  89274. SixDofDragBehavior.prototype.init = function () { };
  89275. /**
  89276. * Attaches the scale behavior the passed in mesh
  89277. * @param ownerNode The mesh that will be scaled around once attached
  89278. */
  89279. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89280. var _this = this;
  89281. this._ownerNode = ownerNode;
  89282. this._scene = this._ownerNode.getScene();
  89283. if (!SixDofDragBehavior._virtualScene) {
  89284. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89285. this._scene.getEngine().scenes.pop();
  89286. }
  89287. var pickedMesh = null;
  89288. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89289. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89290. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89291. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89292. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89293. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89294. var pickPredicate = function (m) {
  89295. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89296. };
  89297. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89298. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89299. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89300. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89301. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89302. }
  89303. pickedMesh = _this._ownerNode;
  89304. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89305. // Set position and orientation of the controller
  89306. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89307. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89308. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89309. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89310. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89311. if (!pickedMesh.rotationQuaternion) {
  89312. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89313. }
  89314. var oldParent = pickedMesh.parent;
  89315. pickedMesh.setParent(null);
  89316. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89317. pickedMesh.setParent(oldParent);
  89318. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89319. // Update state
  89320. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89321. _this.dragging = true;
  89322. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89323. }
  89324. }
  89325. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89326. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89327. _this.dragging = false;
  89328. _this._moving = false;
  89329. _this.currentDraggingPointerID = -1;
  89330. pickedMesh = null;
  89331. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89332. }
  89333. }
  89334. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89335. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89336. var zDragFactor = _this.zDragFactor;
  89337. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89338. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89339. zDragFactor = 0;
  89340. }
  89341. // Calculate controller drag distance in controller space
  89342. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89343. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89344. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89345. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89346. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89347. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89348. if (_this._virtualDragMesh.position.z < 0) {
  89349. _this._virtualDragMesh.position.z = 0;
  89350. }
  89351. // Update the controller position
  89352. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89353. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89354. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89355. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89356. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89357. if (pickedMesh.parent) {
  89358. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89359. }
  89360. if (!_this._moving) {
  89361. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89362. }
  89363. _this._moving = true;
  89364. }
  89365. }
  89366. });
  89367. var tmpQuaternion = new BABYLON.Quaternion();
  89368. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89369. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89370. if (_this.dragging && _this._moving && pickedMesh) {
  89371. // Slowly move mesh to avoid jitter
  89372. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89373. // Get change in rotation
  89374. tmpQuaternion.copyFrom(_this._startingOrientation);
  89375. tmpQuaternion.x = -tmpQuaternion.x;
  89376. tmpQuaternion.y = -tmpQuaternion.y;
  89377. tmpQuaternion.z = -tmpQuaternion.z;
  89378. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89379. // Convert change in rotation to only y axis rotation
  89380. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89381. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89382. // Slowly move mesh to avoid jitter
  89383. var oldParent = pickedMesh.parent;
  89384. pickedMesh.setParent(null);
  89385. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89386. pickedMesh.setParent(oldParent);
  89387. }
  89388. });
  89389. };
  89390. /**
  89391. * Detaches the behavior from the mesh
  89392. */
  89393. SixDofDragBehavior.prototype.detach = function () {
  89394. if (this._scene) {
  89395. this._scene.onPointerObservable.remove(this._pointerObserver);
  89396. }
  89397. if (this._ownerNode) {
  89398. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89399. }
  89400. if (this._virtualOriginMesh) {
  89401. this._virtualOriginMesh.dispose();
  89402. }
  89403. if (this._virtualDragMesh) {
  89404. this._virtualDragMesh.dispose();
  89405. }
  89406. };
  89407. return SixDofDragBehavior;
  89408. }());
  89409. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89410. })(BABYLON || (BABYLON = {}));
  89411. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89412. var BABYLON;
  89413. (function (BABYLON) {
  89414. /**
  89415. * @hidden
  89416. */
  89417. var FaceDirectionInfo = /** @class */ (function () {
  89418. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89419. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89420. if (diff === void 0) { diff = 0; }
  89421. if (ignore === void 0) { ignore = false; }
  89422. this.direction = direction;
  89423. this.rotatedDirection = rotatedDirection;
  89424. this.diff = diff;
  89425. this.ignore = ignore;
  89426. }
  89427. return FaceDirectionInfo;
  89428. }());
  89429. /**
  89430. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89431. */
  89432. var AttachToBoxBehavior = /** @class */ (function () {
  89433. /**
  89434. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89435. * @param ui The transform node that should be attched to the mesh
  89436. */
  89437. function AttachToBoxBehavior(ui) {
  89438. this.ui = ui;
  89439. /**
  89440. * The name of the behavior
  89441. */
  89442. this.name = "AttachToBoxBehavior";
  89443. /**
  89444. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89445. */
  89446. this.distanceAwayFromFace = 0.15;
  89447. /**
  89448. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89449. */
  89450. this.distanceAwayFromBottomOfFace = 0.15;
  89451. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  89452. this._tmpMatrix = new BABYLON.Matrix();
  89453. this._tmpVector = new BABYLON.Vector3();
  89454. this._zeroVector = BABYLON.Vector3.Zero();
  89455. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89456. /* Does nothing */
  89457. }
  89458. /**
  89459. * Initializes the behavior
  89460. */
  89461. AttachToBoxBehavior.prototype.init = function () {
  89462. /* Does nothing */
  89463. };
  89464. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89465. var _this = this;
  89466. // Go over each face and calculate the angle between the face's normal and targetDirection
  89467. this._faceVectors.forEach(function (v) {
  89468. if (!_this._target.rotationQuaternion) {
  89469. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89470. }
  89471. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89472. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89473. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89474. });
  89475. // Return the face information of the one with the normal closeset to target direction
  89476. return this._faceVectors.reduce(function (min, p) {
  89477. if (min.ignore) {
  89478. return p;
  89479. }
  89480. else if (p.ignore) {
  89481. return min;
  89482. }
  89483. else {
  89484. return min.diff < p.diff ? min : p;
  89485. }
  89486. }, this._faceVectors[0]);
  89487. };
  89488. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89489. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89490. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89491. this._lookAtTmpMatrix.invert();
  89492. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89493. };
  89494. /**
  89495. * Attaches the AttachToBoxBehavior to the passed in mesh
  89496. * @param target The mesh that the specified node will be attached to
  89497. */
  89498. AttachToBoxBehavior.prototype.attach = function (target) {
  89499. var _this = this;
  89500. this._target = target;
  89501. this._scene = this._target.getScene();
  89502. // Every frame, update the app bars position
  89503. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89504. if (!_this._scene.activeCamera) {
  89505. return;
  89506. }
  89507. // Find the face closest to the cameras position
  89508. var cameraPos = _this._scene.activeCamera.position;
  89509. if (_this._scene.activeCamera.devicePosition) {
  89510. cameraPos = _this._scene.activeCamera.devicePosition;
  89511. }
  89512. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89513. if (_this._scene.activeCamera.leftCamera) {
  89514. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89515. }
  89516. else {
  89517. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89518. }
  89519. // Get camera up direction
  89520. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89521. // Ignore faces to not select a parrelel face for the up vector of the UI
  89522. _this._faceVectors.forEach(function (v) {
  89523. if (facing.direction.x && v.direction.x) {
  89524. v.ignore = true;
  89525. }
  89526. if (facing.direction.y && v.direction.y) {
  89527. v.ignore = true;
  89528. }
  89529. if (facing.direction.z && v.direction.z) {
  89530. v.ignore = true;
  89531. }
  89532. });
  89533. var facingUp = _this._closestFace(_this._tmpVector);
  89534. // Unignore faces
  89535. _this._faceVectors.forEach(function (v) {
  89536. v.ignore = false;
  89537. });
  89538. // Position the app bar on that face
  89539. _this.ui.position.copyFrom(target.position);
  89540. if (facing.direction.x) {
  89541. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89542. _this.ui.position.addInPlace(_this._tmpVector);
  89543. }
  89544. if (facing.direction.y) {
  89545. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89546. _this.ui.position.addInPlace(_this._tmpVector);
  89547. }
  89548. if (facing.direction.z) {
  89549. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89550. _this.ui.position.addInPlace(_this._tmpVector);
  89551. }
  89552. // Rotate to be oriented properly to the camera
  89553. if (!_this.ui.rotationQuaternion) {
  89554. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89555. }
  89556. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89557. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89558. // Place ui the correct distance from the bottom of the mesh
  89559. if (facingUp.direction.x) {
  89560. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89561. }
  89562. if (facingUp.direction.y) {
  89563. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89564. }
  89565. if (facingUp.direction.z) {
  89566. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89567. }
  89568. _this.ui.position.addInPlace(_this._tmpVector);
  89569. });
  89570. };
  89571. /**
  89572. * Detaches the behavior from the mesh
  89573. */
  89574. AttachToBoxBehavior.prototype.detach = function () {
  89575. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89576. };
  89577. return AttachToBoxBehavior;
  89578. }());
  89579. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89580. })(BABYLON || (BABYLON = {}));
  89581. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89582. var BABYLON;
  89583. (function (BABYLON) {
  89584. /**
  89585. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89586. */
  89587. var Gizmo = /** @class */ (function () {
  89588. /**
  89589. * Creates a gizmo
  89590. * @param gizmoLayer The utility layer the gizmo will be added to
  89591. */
  89592. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89593. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89594. var _this = this;
  89595. this.gizmoLayer = gizmoLayer;
  89596. this._scaleFactor = 3;
  89597. this._tmpMatrix = new BABYLON.Matrix();
  89598. /**
  89599. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89600. */
  89601. this.updateGizmoRotationToMatchAttachedMesh = true;
  89602. /**
  89603. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89604. */
  89605. this.updateGizmoPositionToMatchAttachedMesh = true;
  89606. /**
  89607. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89608. */
  89609. this._updateScale = true;
  89610. this._interactionsEnabled = true;
  89611. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89612. var tempVector = new BABYLON.Vector3();
  89613. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89614. if (_this.attachedMesh) {
  89615. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89616. if (!_this._rootMesh.rotationQuaternion) {
  89617. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89618. }
  89619. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89620. tempVector.copyFrom(_this.attachedMesh.scaling);
  89621. if (_this.attachedMesh.scaling.x < 0) {
  89622. _this.attachedMesh.scaling.x *= -1;
  89623. }
  89624. if (_this.attachedMesh.scaling.y < 0) {
  89625. _this.attachedMesh.scaling.y *= -1;
  89626. }
  89627. if (_this.attachedMesh.scaling.z < 0) {
  89628. _this.attachedMesh.scaling.z *= -1;
  89629. }
  89630. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89631. _this.attachedMesh.scaling.copyFrom(tempVector);
  89632. _this.attachedMesh.computeWorldMatrix();
  89633. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89634. }
  89635. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89636. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89637. }
  89638. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89639. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89640. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89641. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89642. }
  89643. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89644. var dist = tempVector.length() / _this._scaleFactor;
  89645. _this._rootMesh.scaling.set(dist, dist, dist);
  89646. }
  89647. }
  89648. });
  89649. this.attachedMesh = null;
  89650. }
  89651. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89652. /**
  89653. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89654. * * When set, interactions will be enabled
  89655. */
  89656. get: function () {
  89657. return this._attachedMesh;
  89658. },
  89659. set: function (value) {
  89660. this._attachedMesh = value;
  89661. this._rootMesh.setEnabled(value ? true : false);
  89662. this._attachedMeshChanged(value);
  89663. },
  89664. enumerable: true,
  89665. configurable: true
  89666. });
  89667. Gizmo.prototype._attachedMeshChanged = function (value) {
  89668. };
  89669. /**
  89670. * Disposes of the gizmo
  89671. */
  89672. Gizmo.prototype.dispose = function () {
  89673. this._rootMesh.dispose();
  89674. if (this._beforeRenderObserver) {
  89675. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89676. }
  89677. };
  89678. return Gizmo;
  89679. }());
  89680. BABYLON.Gizmo = Gizmo;
  89681. })(BABYLON || (BABYLON = {}));
  89682. //# sourceMappingURL=babylon.gizmo.js.map
  89683. var BABYLON;
  89684. (function (BABYLON) {
  89685. /**
  89686. * Single axis drag gizmo
  89687. */
  89688. var AxisDragGizmo = /** @class */ (function (_super) {
  89689. __extends(AxisDragGizmo, _super);
  89690. /**
  89691. * Creates an AxisDragGizmo
  89692. * @param gizmoLayer The utility layer the gizmo will be added to
  89693. * @param dragAxis The axis which the gizmo will be able to drag on
  89694. * @param color The color of the gizmo
  89695. */
  89696. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89697. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89698. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89699. var _this = _super.call(this, gizmoLayer) || this;
  89700. _this._pointerObserver = null;
  89701. /**
  89702. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89703. */
  89704. _this.snapDistance = 0;
  89705. /**
  89706. * Event that fires each time the gizmo snaps to a new location.
  89707. * * snapDistance is the the change in distance
  89708. */
  89709. _this.onSnapObservable = new BABYLON.Observable();
  89710. // Create Material
  89711. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89712. coloredMaterial.disableLighting = true;
  89713. coloredMaterial.emissiveColor = color;
  89714. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89715. hoverMaterial.disableLighting = true;
  89716. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89717. // Build mesh on root node
  89718. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89719. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89720. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89721. arrow.addChild(arrowMesh);
  89722. arrow.addChild(arrowTail);
  89723. // Position arrow pointing in its drag axis
  89724. arrowMesh.scaling.scaleInPlace(0.05);
  89725. arrowMesh.material = coloredMaterial;
  89726. arrowMesh.rotation.x = Math.PI / 2;
  89727. arrowMesh.position.z += 0.3;
  89728. arrowTail.rotation.x = Math.PI / 2;
  89729. arrowTail.material = coloredMaterial;
  89730. arrowTail.position.z += 0.15;
  89731. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89732. _this._rootMesh.addChild(arrow);
  89733. var currentSnapDragDistance = 0;
  89734. var tmpVector = new BABYLON.Vector3();
  89735. var tmpSnapEvent = { snapDistance: 0 };
  89736. // Add drag behavior to handle events when the gizmo is dragged
  89737. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89738. _this.dragBehavior.moveAttached = false;
  89739. _this._rootMesh.addBehavior(_this.dragBehavior);
  89740. _this.dragBehavior.onDragObservable.add(function (event) {
  89741. if (_this.attachedMesh) {
  89742. // Snapping logic
  89743. if (_this.snapDistance == 0) {
  89744. _this.attachedMesh.position.addInPlace(event.delta);
  89745. }
  89746. else {
  89747. currentSnapDragDistance += event.dragDistance;
  89748. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89749. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89750. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89751. event.delta.normalizeToRef(tmpVector);
  89752. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89753. _this.attachedMesh.position.addInPlace(tmpVector);
  89754. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89755. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89756. }
  89757. }
  89758. }
  89759. });
  89760. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89761. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89762. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89763. m.material = hoverMaterial;
  89764. });
  89765. }
  89766. else {
  89767. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89768. m.material = coloredMaterial;
  89769. });
  89770. }
  89771. });
  89772. return _this;
  89773. }
  89774. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89775. if (this.dragBehavior) {
  89776. this.dragBehavior.enabled = value ? true : false;
  89777. }
  89778. };
  89779. /**
  89780. * Disposes of the gizmo
  89781. */
  89782. AxisDragGizmo.prototype.dispose = function () {
  89783. this.onSnapObservable.clear();
  89784. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89785. this.dragBehavior.detach();
  89786. _super.prototype.dispose.call(this);
  89787. };
  89788. return AxisDragGizmo;
  89789. }(BABYLON.Gizmo));
  89790. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89791. })(BABYLON || (BABYLON = {}));
  89792. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89793. var BABYLON;
  89794. (function (BABYLON) {
  89795. /**
  89796. * Single axis scale gizmo
  89797. */
  89798. var AxisScaleGizmo = /** @class */ (function (_super) {
  89799. __extends(AxisScaleGizmo, _super);
  89800. /**
  89801. * Creates an AxisScaleGizmo
  89802. * @param gizmoLayer The utility layer the gizmo will be added to
  89803. * @param dragAxis The axis which the gizmo will be able to scale on
  89804. * @param color The color of the gizmo
  89805. */
  89806. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89807. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89808. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89809. var _this = _super.call(this, gizmoLayer) || this;
  89810. _this._pointerObserver = null;
  89811. /**
  89812. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89813. */
  89814. _this.snapDistance = 0;
  89815. /**
  89816. * Event that fires each time the gizmo snaps to a new location.
  89817. * * snapDistance is the the change in distance
  89818. */
  89819. _this.onSnapObservable = new BABYLON.Observable();
  89820. // Create Material
  89821. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89822. coloredMaterial.disableLighting = true;
  89823. coloredMaterial.emissiveColor = color;
  89824. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89825. hoverMaterial.disableLighting = true;
  89826. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89827. // Build mesh on root node
  89828. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89829. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89830. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89831. arrow.addChild(arrowMesh);
  89832. arrow.addChild(arrowTail);
  89833. // Position arrow pointing in its drag axis
  89834. arrowMesh.scaling.scaleInPlace(0.1);
  89835. arrowMesh.material = coloredMaterial;
  89836. arrowMesh.rotation.x = Math.PI / 2;
  89837. arrowMesh.position.z += 0.3;
  89838. arrowTail.rotation.x = Math.PI / 2;
  89839. arrowTail.material = coloredMaterial;
  89840. arrowTail.position.z += 0.15;
  89841. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89842. _this._rootMesh.addChild(arrow);
  89843. // Add drag behavior to handle events when the gizmo is dragged
  89844. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89845. _this.dragBehavior.moveAttached = false;
  89846. _this._rootMesh.addBehavior(_this.dragBehavior);
  89847. var currentSnapDragDistance = 0;
  89848. var tmpVector = new BABYLON.Vector3();
  89849. var tmpSnapEvent = { snapDistance: 0 };
  89850. _this.dragBehavior.onDragObservable.add(function (event) {
  89851. if (_this.attachedMesh) {
  89852. // Snapping logic
  89853. var snapped = false;
  89854. var dragSteps = 0;
  89855. if (_this.snapDistance == 0) {
  89856. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89857. }
  89858. else {
  89859. currentSnapDragDistance += event.dragDistance;
  89860. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89861. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89862. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89863. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89864. snapped = true;
  89865. }
  89866. else {
  89867. tmpVector.scaleInPlace(0);
  89868. }
  89869. }
  89870. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89871. if (snapped) {
  89872. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89873. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89874. }
  89875. }
  89876. });
  89877. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89878. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89879. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89880. m.material = hoverMaterial;
  89881. });
  89882. }
  89883. else {
  89884. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89885. m.material = coloredMaterial;
  89886. });
  89887. }
  89888. });
  89889. return _this;
  89890. }
  89891. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89892. if (this.dragBehavior) {
  89893. this.dragBehavior.enabled = value ? true : false;
  89894. }
  89895. };
  89896. /**
  89897. * Disposes of the gizmo
  89898. */
  89899. AxisScaleGizmo.prototype.dispose = function () {
  89900. this.onSnapObservable.clear();
  89901. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89902. this.dragBehavior.detach();
  89903. _super.prototype.dispose.call(this);
  89904. };
  89905. return AxisScaleGizmo;
  89906. }(BABYLON.Gizmo));
  89907. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89908. })(BABYLON || (BABYLON = {}));
  89909. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89910. var BABYLON;
  89911. (function (BABYLON) {
  89912. /**
  89913. * Single plane rotation gizmo
  89914. */
  89915. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89916. __extends(PlaneRotationGizmo, _super);
  89917. /**
  89918. * Creates a PlaneRotationGizmo
  89919. * @param gizmoLayer The utility layer the gizmo will be added to
  89920. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89921. * @param color The color of the gizmo
  89922. */
  89923. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89924. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89925. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89926. var _this = _super.call(this, gizmoLayer) || this;
  89927. _this._pointerObserver = null;
  89928. /**
  89929. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89930. */
  89931. _this.snapDistance = 0;
  89932. /**
  89933. * Event that fires each time the gizmo snaps to a new location.
  89934. * * snapDistance is the the change in distance
  89935. */
  89936. _this.onSnapObservable = new BABYLON.Observable();
  89937. // Create Material
  89938. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89939. coloredMaterial.disableLighting = true;
  89940. coloredMaterial.emissiveColor = color;
  89941. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89942. hoverMaterial.disableLighting = true;
  89943. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89944. // Build mesh on root node
  89945. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89946. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89947. // Position arrow pointing in its drag axis
  89948. rotationMesh.scaling.scaleInPlace(0.1);
  89949. rotationMesh.material = coloredMaterial;
  89950. rotationMesh.rotation.x = Math.PI / 2;
  89951. parentMesh.addChild(rotationMesh);
  89952. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89953. _this._rootMesh.addChild(parentMesh);
  89954. // Add drag behavior to handle events when the gizmo is dragged
  89955. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89956. _this.dragBehavior.moveAttached = false;
  89957. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89958. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89959. _this._rootMesh.addBehavior(_this.dragBehavior);
  89960. var lastDragPosition = new BABYLON.Vector3();
  89961. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89962. if (_this.attachedMesh) {
  89963. lastDragPosition.copyFrom(e.dragPlanePoint);
  89964. }
  89965. });
  89966. var rotationMatrix = new BABYLON.Matrix();
  89967. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89968. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89969. var tmpSnapEvent = { snapDistance: 0 };
  89970. var currentSnapDragDistance = 0;
  89971. _this.dragBehavior.onDragObservable.add(function (event) {
  89972. if (_this.attachedMesh) {
  89973. if (!_this.attachedMesh.rotationQuaternion) {
  89974. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89975. }
  89976. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89977. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89978. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89979. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89980. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89981. var angle = Math.atan2(cross.length(), dot);
  89982. planeNormalTowardsCamera.copyFrom(planeNormal);
  89983. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89984. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89985. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89986. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89987. }
  89988. // Flip up vector depending on which side the camera is on
  89989. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89990. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89991. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89992. planeNormalTowardsCamera.scaleInPlace(-1);
  89993. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89994. }
  89995. }
  89996. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89997. if (halfCircleSide)
  89998. angle = -angle;
  89999. // Snapping logic
  90000. var snapped = false;
  90001. if (_this.snapDistance != 0) {
  90002. currentSnapDragDistance += angle;
  90003. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90004. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90005. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90006. angle = _this.snapDistance * dragSteps;
  90007. snapped = true;
  90008. }
  90009. else {
  90010. angle = 0;
  90011. }
  90012. }
  90013. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90014. var quaternionCoefficient = Math.sin(angle / 2);
  90015. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90016. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90017. // Rotate selected mesh quaternion over fixed axis
  90018. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90019. }
  90020. else {
  90021. // Rotate selected mesh quaternion over rotated axis
  90022. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90023. }
  90024. lastDragPosition.copyFrom(event.dragPlanePoint);
  90025. if (snapped) {
  90026. tmpSnapEvent.snapDistance = angle;
  90027. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90028. }
  90029. }
  90030. });
  90031. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90032. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90033. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90034. m.material = hoverMaterial;
  90035. });
  90036. }
  90037. else {
  90038. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90039. m.material = coloredMaterial;
  90040. });
  90041. }
  90042. });
  90043. return _this;
  90044. }
  90045. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90046. if (this.dragBehavior) {
  90047. this.dragBehavior.enabled = value ? true : false;
  90048. }
  90049. };
  90050. /**
  90051. * Disposes of the gizmo
  90052. */
  90053. PlaneRotationGizmo.prototype.dispose = function () {
  90054. this.onSnapObservable.clear();
  90055. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90056. this.dragBehavior.detach();
  90057. _super.prototype.dispose.call(this);
  90058. };
  90059. return PlaneRotationGizmo;
  90060. }(BABYLON.Gizmo));
  90061. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90062. })(BABYLON || (BABYLON = {}));
  90063. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90064. var BABYLON;
  90065. (function (BABYLON) {
  90066. /**
  90067. * Gizmo that enables dragging a mesh along 3 axis
  90068. */
  90069. var PositionGizmo = /** @class */ (function (_super) {
  90070. __extends(PositionGizmo, _super);
  90071. /**
  90072. * Creates a PositionGizmo
  90073. * @param gizmoLayer The utility layer the gizmo will be added to
  90074. */
  90075. function PositionGizmo(gizmoLayer) {
  90076. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90077. var _this = _super.call(this, gizmoLayer) || this;
  90078. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90079. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90080. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90081. _this.attachedMesh = null;
  90082. return _this;
  90083. }
  90084. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90085. set: function (mesh) {
  90086. if (this.xGizmo) {
  90087. this.xGizmo.attachedMesh = mesh;
  90088. this.yGizmo.attachedMesh = mesh;
  90089. this.zGizmo.attachedMesh = mesh;
  90090. }
  90091. },
  90092. enumerable: true,
  90093. configurable: true
  90094. });
  90095. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90096. get: function () {
  90097. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90098. },
  90099. set: function (value) {
  90100. if (this.xGizmo) {
  90101. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90102. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90103. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90104. }
  90105. },
  90106. enumerable: true,
  90107. configurable: true
  90108. });
  90109. /**
  90110. * Disposes of the gizmo
  90111. */
  90112. PositionGizmo.prototype.dispose = function () {
  90113. this.xGizmo.dispose();
  90114. this.yGizmo.dispose();
  90115. this.zGizmo.dispose();
  90116. };
  90117. return PositionGizmo;
  90118. }(BABYLON.Gizmo));
  90119. BABYLON.PositionGizmo = PositionGizmo;
  90120. })(BABYLON || (BABYLON = {}));
  90121. //# sourceMappingURL=babylon.positionGizmo.js.map
  90122. var BABYLON;
  90123. (function (BABYLON) {
  90124. /**
  90125. * Gizmo that enables rotating a mesh along 3 axis
  90126. */
  90127. var RotationGizmo = /** @class */ (function (_super) {
  90128. __extends(RotationGizmo, _super);
  90129. /**
  90130. * Creates a RotationGizmo
  90131. * @param gizmoLayer The utility layer the gizmo will be added to
  90132. */
  90133. function RotationGizmo(gizmoLayer) {
  90134. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90135. var _this = _super.call(this, gizmoLayer) || this;
  90136. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90137. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90138. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90139. _this.attachedMesh = null;
  90140. return _this;
  90141. }
  90142. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90143. set: function (mesh) {
  90144. if (this.xGizmo) {
  90145. this.xGizmo.attachedMesh = mesh;
  90146. this.yGizmo.attachedMesh = mesh;
  90147. this.zGizmo.attachedMesh = mesh;
  90148. }
  90149. },
  90150. enumerable: true,
  90151. configurable: true
  90152. });
  90153. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90154. get: function () {
  90155. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90156. },
  90157. set: function (value) {
  90158. if (this.xGizmo) {
  90159. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90160. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90161. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90162. }
  90163. },
  90164. enumerable: true,
  90165. configurable: true
  90166. });
  90167. /**
  90168. * Disposes of the gizmo
  90169. */
  90170. RotationGizmo.prototype.dispose = function () {
  90171. this.xGizmo.dispose();
  90172. this.yGizmo.dispose();
  90173. this.zGizmo.dispose();
  90174. };
  90175. return RotationGizmo;
  90176. }(BABYLON.Gizmo));
  90177. BABYLON.RotationGizmo = RotationGizmo;
  90178. })(BABYLON || (BABYLON = {}));
  90179. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90180. var BABYLON;
  90181. (function (BABYLON) {
  90182. /**
  90183. * Gizmo that enables scaling a mesh along 3 axis
  90184. */
  90185. var ScaleGizmo = /** @class */ (function (_super) {
  90186. __extends(ScaleGizmo, _super);
  90187. /**
  90188. * Creates a ScaleGizmo
  90189. * @param gizmoLayer The utility layer the gizmo will be added to
  90190. */
  90191. function ScaleGizmo(gizmoLayer) {
  90192. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90193. var _this = _super.call(this, gizmoLayer) || this;
  90194. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90195. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90196. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90197. _this.attachedMesh = null;
  90198. return _this;
  90199. }
  90200. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90201. set: function (mesh) {
  90202. if (this.xGizmo) {
  90203. this.xGizmo.attachedMesh = mesh;
  90204. this.yGizmo.attachedMesh = mesh;
  90205. this.zGizmo.attachedMesh = mesh;
  90206. }
  90207. },
  90208. enumerable: true,
  90209. configurable: true
  90210. });
  90211. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90212. get: function () {
  90213. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90214. },
  90215. set: function (value) {
  90216. if (this.xGizmo) {
  90217. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90218. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90219. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90220. }
  90221. },
  90222. enumerable: true,
  90223. configurable: true
  90224. });
  90225. /**
  90226. * Disposes of the gizmo
  90227. */
  90228. ScaleGizmo.prototype.dispose = function () {
  90229. this.xGizmo.dispose();
  90230. this.yGizmo.dispose();
  90231. this.zGizmo.dispose();
  90232. };
  90233. return ScaleGizmo;
  90234. }(BABYLON.Gizmo));
  90235. BABYLON.ScaleGizmo = ScaleGizmo;
  90236. })(BABYLON || (BABYLON = {}));
  90237. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90238. var BABYLON;
  90239. (function (BABYLON) {
  90240. /**
  90241. * Bounding box gizmo
  90242. */
  90243. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90244. __extends(BoundingBoxGizmo, _super);
  90245. /**
  90246. * Creates an BoundingBoxGizmo
  90247. * @param gizmoLayer The utility layer the gizmo will be added to
  90248. * @param color The color of the gizmo
  90249. */
  90250. function BoundingBoxGizmo(color, gizmoLayer) {
  90251. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90252. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90253. var _this = _super.call(this, gizmoLayer) || this;
  90254. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90255. _this._renderObserver = null;
  90256. _this._pointerObserver = null;
  90257. _this._scaleDragSpeed = 0.2;
  90258. _this._tmpQuaternion = new BABYLON.Quaternion();
  90259. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90260. /**
  90261. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90262. */
  90263. _this.rotationSphereSize = 0.1;
  90264. /**
  90265. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90266. */
  90267. _this.scaleBoxSize = 0.1;
  90268. /**
  90269. * 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)
  90270. */
  90271. _this.fixedDragMeshScreenSize = false;
  90272. /**
  90273. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90274. */
  90275. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90276. /**
  90277. * Fired when a rotation sphere or scale box is dragged
  90278. */
  90279. _this.onDragStartObservable = new BABYLON.Observable();
  90280. /**
  90281. * Fired when a rotation sphere or scale box drag is started
  90282. */
  90283. _this.onDragObservable = new BABYLON.Observable();
  90284. /**
  90285. * Fired when a rotation sphere or scale box drag is needed
  90286. */
  90287. _this.onDragEndObservable = new BABYLON.Observable();
  90288. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90289. _this._updateScale = false;
  90290. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90291. // Create Materials
  90292. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90293. coloredMaterial.disableLighting = true;
  90294. coloredMaterial.emissiveColor = color;
  90295. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90296. hoverColoredMaterial.disableLighting = true;
  90297. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90298. // Build bounding box out of lines
  90299. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90300. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90301. var lines = [];
  90302. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90303. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90304. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90305. 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));
  90306. 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));
  90307. 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));
  90308. 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));
  90309. 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));
  90310. 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));
  90311. 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));
  90312. 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));
  90313. 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));
  90314. lines.forEach(function (l) {
  90315. l.color = color;
  90316. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90317. l.isPickable = false;
  90318. _this._lineBoundingBox.addChild(l);
  90319. });
  90320. _this._rootMesh.addChild(_this._lineBoundingBox);
  90321. // Create rotation spheres
  90322. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90323. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90324. var _loop_1 = function (i_1) {
  90325. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90326. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90327. sphere.material = coloredMaterial;
  90328. // Drag behavior
  90329. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90330. _dragBehavior.moveAttached = false;
  90331. _dragBehavior.updateDragPlane = false;
  90332. sphere.addBehavior(_dragBehavior);
  90333. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90334. var totalTurnAmountOfDrag = 0;
  90335. _dragBehavior.onDragStartObservable.add(function (event) {
  90336. startingTurnDirection.copyFrom(sphere.forward);
  90337. totalTurnAmountOfDrag = 0;
  90338. });
  90339. _dragBehavior.onDragObservable.add(function (event) {
  90340. _this.onDragObservable.notifyObservers({});
  90341. if (_this.attachedMesh) {
  90342. var worldDragDirection = startingTurnDirection;
  90343. // Project the world right on to the drag plane
  90344. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90345. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90346. // project drag delta on to the resulting drag axis and rotate based on that
  90347. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90348. // Rotate based on axis
  90349. if (!_this.attachedMesh.rotationQuaternion) {
  90350. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90351. }
  90352. if (!_this._anchorMesh.rotationQuaternion) {
  90353. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90354. }
  90355. // Do not allow the object to turn more than a full circle
  90356. totalTurnAmountOfDrag += projectDist;
  90357. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90358. if (i_1 >= 8) {
  90359. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90360. }
  90361. else if (i_1 >= 4) {
  90362. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90363. }
  90364. else {
  90365. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90366. }
  90367. // Rotate around center of bounding box
  90368. _this._anchorMesh.addChild(_this.attachedMesh);
  90369. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90370. _this._anchorMesh.removeChild(_this.attachedMesh);
  90371. }
  90372. }
  90373. });
  90374. // Selection/deselection
  90375. _dragBehavior.onDragStartObservable.add(function () {
  90376. _this.onDragStartObservable.notifyObservers({});
  90377. _this._selectNode(sphere);
  90378. });
  90379. _dragBehavior.onDragEndObservable.add(function () {
  90380. _this.onDragEndObservable.notifyObservers({});
  90381. _this._selectNode(null);
  90382. });
  90383. this_1._rotateSpheresParent.addChild(sphere);
  90384. };
  90385. var this_1 = this, _dragBehavior;
  90386. for (var i_1 = 0; i_1 < 12; i_1++) {
  90387. _loop_1(i_1);
  90388. }
  90389. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90390. // Create scale cubes
  90391. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90392. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90393. for (var i = 0; i < 2; i++) {
  90394. for (var j = 0; j < 2; j++) {
  90395. var _loop_2 = function () {
  90396. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90397. box.material = coloredMaterial;
  90398. // Dragging logic
  90399. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90400. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90401. _dragBehavior.moveAttached = false;
  90402. box.addBehavior(_dragBehavior);
  90403. _dragBehavior.onDragObservable.add(function (event) {
  90404. _this.onDragObservable.notifyObservers({});
  90405. if (_this.attachedMesh) {
  90406. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90407. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90408. _this._updateBoundingBox();
  90409. // Scale from the position of the opposite corner
  90410. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90411. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90412. _this._anchorMesh.addChild(_this.attachedMesh);
  90413. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90414. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90415. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90416. }
  90417. _this._anchorMesh.removeChild(_this.attachedMesh);
  90418. }
  90419. });
  90420. // Selection/deselection
  90421. _dragBehavior.onDragStartObservable.add(function () {
  90422. _this.onDragStartObservable.notifyObservers({});
  90423. _this._selectNode(box);
  90424. });
  90425. _dragBehavior.onDragEndObservable.add(function () {
  90426. _this.onDragEndObservable.notifyObservers({});
  90427. _this._selectNode(null);
  90428. });
  90429. this_2._scaleBoxesParent.addChild(box);
  90430. };
  90431. var this_2 = this, _dragBehavior;
  90432. for (var k = 0; k < 2; k++) {
  90433. _loop_2();
  90434. }
  90435. }
  90436. }
  90437. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90438. // Hover color change
  90439. var pointerIds = new Array();
  90440. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90441. if (!pointerIds[pointerInfo.event.pointerId]) {
  90442. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90443. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90444. pointerIds[pointerInfo.event.pointerId] = mesh;
  90445. mesh.material = hoverColoredMaterial;
  90446. }
  90447. });
  90448. }
  90449. else {
  90450. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90451. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90452. delete pointerIds[pointerInfo.event.pointerId];
  90453. }
  90454. }
  90455. });
  90456. // Update bounding box positions
  90457. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90458. _this._updateBoundingBox();
  90459. });
  90460. _this._updateBoundingBox();
  90461. return _this;
  90462. }
  90463. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90464. if (value) {
  90465. // Reset anchor mesh to match attached mesh's scale
  90466. // This is needed to avoid invalid box/sphere position on first drag
  90467. this._anchorMesh.addChild(value);
  90468. this._anchorMesh.removeChild(value);
  90469. this._updateBoundingBox();
  90470. }
  90471. };
  90472. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90473. this._rotateSpheresParent.getChildMeshes()
  90474. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90475. m.isVisible = (!selectedMesh || m == selectedMesh);
  90476. });
  90477. };
  90478. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90479. var _this = this;
  90480. mesh.computeWorldMatrix(true);
  90481. mesh.getChildMeshes().forEach(function (m) {
  90482. _this._recurseComputeWorld(m);
  90483. });
  90484. };
  90485. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90486. if (this.attachedMesh) {
  90487. // Rotate based on axis
  90488. if (!this.attachedMesh.rotationQuaternion) {
  90489. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90490. }
  90491. if (!this._anchorMesh.rotationQuaternion) {
  90492. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90493. }
  90494. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90495. // Store original position and reset mesh to origin before computing the bounding box
  90496. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90497. this._tmpVector.copyFrom(this.attachedMesh.position);
  90498. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90499. this.attachedMesh.position.set(0, 0, 0);
  90500. // Update bounding dimensions/positions
  90501. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90502. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90503. // Update gizmo to match bounding box scaling and rotation
  90504. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90505. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90506. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90507. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90508. this._lineBoundingBox.computeWorldMatrix();
  90509. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90510. // restore position/rotation values
  90511. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90512. this.attachedMesh.position.copyFrom(this._tmpVector);
  90513. this._recurseComputeWorld(this.attachedMesh);
  90514. }
  90515. // Update rotation sphere locations
  90516. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90517. for (var i = 0; i < 3; i++) {
  90518. for (var j = 0; j < 2; j++) {
  90519. for (var k = 0; k < 2; k++) {
  90520. var index = ((i * 4) + (j * 2)) + k;
  90521. if (i == 0) {
  90522. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90523. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90524. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90525. }
  90526. if (i == 1) {
  90527. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90528. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90529. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90530. }
  90531. if (i == 2) {
  90532. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90533. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90534. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90535. }
  90536. if (this.fixedDragMeshScreenSize) {
  90537. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90538. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90539. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90540. }
  90541. else {
  90542. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90543. }
  90544. }
  90545. }
  90546. }
  90547. // Update scale box locations
  90548. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90549. for (var i = 0; i < 2; i++) {
  90550. for (var j = 0; j < 2; j++) {
  90551. for (var k = 0; k < 2; k++) {
  90552. var index = ((i * 4) + (j * 2)) + k;
  90553. if (scaleBoxes[index]) {
  90554. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90555. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90556. if (this.fixedDragMeshScreenSize) {
  90557. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90558. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90559. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90560. }
  90561. else {
  90562. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90563. }
  90564. }
  90565. }
  90566. }
  90567. }
  90568. };
  90569. /**
  90570. * Enables rotation on the specified axis and disables rotation on the others
  90571. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90572. */
  90573. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90574. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90575. if (i < 4) {
  90576. m.setEnabled(axis.indexOf("x") != -1);
  90577. }
  90578. else if (i < 8) {
  90579. m.setEnabled(axis.indexOf("y") != -1);
  90580. }
  90581. else {
  90582. m.setEnabled(axis.indexOf("z") != -1);
  90583. }
  90584. });
  90585. };
  90586. /**
  90587. * Disposes of the gizmo
  90588. */
  90589. BoundingBoxGizmo.prototype.dispose = function () {
  90590. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90591. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90592. this._lineBoundingBox.dispose();
  90593. this._rotateSpheresParent.dispose();
  90594. this._scaleBoxesParent.dispose();
  90595. _super.prototype.dispose.call(this);
  90596. };
  90597. /**
  90598. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  90599. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90600. * @returns the bounding box mesh with the passed in mesh as a child
  90601. */
  90602. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90603. var makeNotPickable = function (root) {
  90604. root.isPickable = false;
  90605. root.getChildMeshes().forEach(function (c) {
  90606. makeNotPickable(c);
  90607. });
  90608. };
  90609. makeNotPickable(mesh);
  90610. // Reset position to get boudning box from origin with no rotation
  90611. if (!mesh.rotationQuaternion) {
  90612. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  90613. }
  90614. var oldPos = mesh.position.clone();
  90615. var oldRot = mesh.rotationQuaternion.clone();
  90616. mesh.rotationQuaternion.set(0, 0, 0, 1);
  90617. mesh.position.set(0, 0, 0);
  90618. // Update bounding dimensions/positions
  90619. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  90620. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  90621. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  90622. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90623. // Restore original positions
  90624. mesh.addChild(box);
  90625. mesh.rotationQuaternion.copyFrom(oldRot);
  90626. mesh.position.copyFrom(oldPos);
  90627. // Reverse parenting
  90628. mesh.removeChild(box);
  90629. box.addChild(mesh);
  90630. box.visibility = 0;
  90631. return box;
  90632. };
  90633. return BoundingBoxGizmo;
  90634. }(BABYLON.Gizmo));
  90635. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90636. })(BABYLON || (BABYLON = {}));
  90637. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90638. var BABYLON;
  90639. (function (BABYLON) {
  90640. /**
  90641. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90642. */
  90643. var GizmoManager = /** @class */ (function () {
  90644. /**
  90645. * Instatiates a gizmo manager
  90646. * @param scene the scene to overlay the gizmos on top of
  90647. */
  90648. function GizmoManager(scene) {
  90649. var _this = this;
  90650. this.scene = scene;
  90651. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  90652. this._pointerObserver = null;
  90653. this._attachedMesh = null;
  90654. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  90655. this._boundingBoxUtilLayer = null;
  90656. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  90657. /**
  90658. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  90659. */
  90660. this.attachableMeshes = null;
  90661. /**
  90662. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  90663. */
  90664. this.usePointerToAttachGizmos = true;
  90665. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  90666. // Instatiate/dispose gizmos based on pointer actions
  90667. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90668. if (!_this.usePointerToAttachGizmos) {
  90669. return;
  90670. }
  90671. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90672. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90673. var node = pointerInfo.pickInfo.pickedMesh;
  90674. if (_this.attachableMeshes == null) {
  90675. // Attach to the most parent node
  90676. while (node && node.parent != null) {
  90677. node = node.parent;
  90678. }
  90679. }
  90680. else {
  90681. // Attach to the parent node that is an attachableMesh
  90682. var found = false;
  90683. _this.attachableMeshes.forEach(function (mesh) {
  90684. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  90685. node = mesh;
  90686. found = true;
  90687. }
  90688. });
  90689. if (!found) {
  90690. node = null;
  90691. }
  90692. }
  90693. if (node instanceof BABYLON.AbstractMesh) {
  90694. _this.attachToMesh(node);
  90695. }
  90696. }
  90697. else {
  90698. _this.attachToMesh(null);
  90699. }
  90700. }
  90701. });
  90702. }
  90703. /**
  90704. * Attaches a set of gizmos to the specified mesh
  90705. * @param mesh The mesh the gizmo's should be attached to
  90706. */
  90707. GizmoManager.prototype.attachToMesh = function (mesh) {
  90708. if (this._attachedMesh) {
  90709. this._attachedMesh.removeBehavior(this._dragBehavior);
  90710. }
  90711. this._attachedMesh = mesh;
  90712. for (var key in this.gizmos) {
  90713. var gizmo = (this.gizmos[key]);
  90714. if (gizmo && this._gizmosEnabled[key]) {
  90715. gizmo.attachedMesh = mesh;
  90716. }
  90717. }
  90718. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  90719. this._attachedMesh.addBehavior(this._dragBehavior);
  90720. }
  90721. };
  90722. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  90723. get: function () {
  90724. return this._gizmosEnabled.positionGizmo;
  90725. },
  90726. /**
  90727. * If the position gizmo is enabled
  90728. */
  90729. set: function (value) {
  90730. if (value) {
  90731. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  90732. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90733. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  90734. }
  90735. else if (this.gizmos.positionGizmo) {
  90736. this.gizmos.positionGizmo.attachedMesh = null;
  90737. }
  90738. this._gizmosEnabled.positionGizmo = value;
  90739. },
  90740. enumerable: true,
  90741. configurable: true
  90742. });
  90743. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  90744. get: function () {
  90745. return this._gizmosEnabled.rotationGizmo;
  90746. },
  90747. /**
  90748. * If the rotation gizmo is enabled
  90749. */
  90750. set: function (value) {
  90751. if (value) {
  90752. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  90753. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90754. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  90755. }
  90756. else if (this.gizmos.rotationGizmo) {
  90757. this.gizmos.rotationGizmo.attachedMesh = null;
  90758. }
  90759. this._gizmosEnabled.rotationGizmo = value;
  90760. },
  90761. enumerable: true,
  90762. configurable: true
  90763. });
  90764. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  90765. get: function () {
  90766. return this._gizmosEnabled.scaleGizmo;
  90767. },
  90768. /**
  90769. * If the scale gizmo is enabled
  90770. */
  90771. set: function (value) {
  90772. if (value) {
  90773. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  90774. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  90775. }
  90776. else if (this.gizmos.scaleGizmo) {
  90777. this.gizmos.scaleGizmo.attachedMesh = null;
  90778. }
  90779. this._gizmosEnabled.scaleGizmo = value;
  90780. },
  90781. enumerable: true,
  90782. configurable: true
  90783. });
  90784. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  90785. get: function () {
  90786. return this._gizmosEnabled.boundingBoxGizmo;
  90787. },
  90788. /**
  90789. * If the boundingBox gizmo is enabled
  90790. */
  90791. set: function (value) {
  90792. if (value) {
  90793. if (!this._boundingBoxUtilLayer) {
  90794. this._boundingBoxUtilLayer = new BABYLON.UtilityLayerRenderer(this.scene);
  90795. this._boundingBoxUtilLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90796. }
  90797. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._boundingBoxUtilLayer);
  90798. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  90799. if (this._attachedMesh) {
  90800. this._attachedMesh.removeBehavior(this._dragBehavior);
  90801. this._attachedMesh.addBehavior(this._dragBehavior);
  90802. }
  90803. }
  90804. else if (this.gizmos.boundingBoxGizmo) {
  90805. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  90806. }
  90807. this._gizmosEnabled.boundingBoxGizmo = value;
  90808. },
  90809. enumerable: true,
  90810. configurable: true
  90811. });
  90812. /**
  90813. * Disposes of the gizmo manager
  90814. */
  90815. GizmoManager.prototype.dispose = function () {
  90816. this.scene.onPointerObservable.remove(this._pointerObserver);
  90817. for (var key in this.gizmos) {
  90818. var gizmo = (this.gizmos[key]);
  90819. if (gizmo) {
  90820. gizmo.dispose();
  90821. }
  90822. }
  90823. this._gizmoLayer.dispose();
  90824. };
  90825. return GizmoManager;
  90826. }());
  90827. BABYLON.GizmoManager = GizmoManager;
  90828. })(BABYLON || (BABYLON = {}));
  90829. //# sourceMappingURL=babylon.gizmoManager.js.map
  90830. var BABYLON;
  90831. (function (BABYLON) {
  90832. /**
  90833. * Defines a target to use with MorphTargetManager
  90834. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90835. */
  90836. var MorphTarget = /** @class */ (function () {
  90837. /**
  90838. * Creates a new MorphTarget
  90839. * @param name defines the name of the target
  90840. * @param influence defines the influence to use
  90841. */
  90842. function MorphTarget(
  90843. /** defines the name of the target */
  90844. name, influence, scene) {
  90845. if (influence === void 0) { influence = 0; }
  90846. if (scene === void 0) { scene = null; }
  90847. this.name = name;
  90848. /**
  90849. * Gets or sets the list of animations
  90850. */
  90851. this.animations = new Array();
  90852. this._positions = null;
  90853. this._normals = null;
  90854. this._tangents = null;
  90855. /**
  90856. * Observable raised when the influence changes
  90857. */
  90858. this.onInfluenceChanged = new BABYLON.Observable();
  90859. this._animationPropertiesOverride = null;
  90860. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90861. this.influence = influence;
  90862. }
  90863. Object.defineProperty(MorphTarget.prototype, "influence", {
  90864. /**
  90865. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90866. */
  90867. get: function () {
  90868. return this._influence;
  90869. },
  90870. set: function (influence) {
  90871. if (this._influence === influence) {
  90872. return;
  90873. }
  90874. var previous = this._influence;
  90875. this._influence = influence;
  90876. if (this.onInfluenceChanged.hasObservers) {
  90877. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90878. }
  90879. },
  90880. enumerable: true,
  90881. configurable: true
  90882. });
  90883. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90884. /**
  90885. * Gets or sets the animation properties override
  90886. */
  90887. get: function () {
  90888. if (!this._animationPropertiesOverride && this._scene) {
  90889. return this._scene.animationPropertiesOverride;
  90890. }
  90891. return this._animationPropertiesOverride;
  90892. },
  90893. set: function (value) {
  90894. this._animationPropertiesOverride = value;
  90895. },
  90896. enumerable: true,
  90897. configurable: true
  90898. });
  90899. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90900. /**
  90901. * Gets a boolean defining if the target contains position data
  90902. */
  90903. get: function () {
  90904. return !!this._positions;
  90905. },
  90906. enumerable: true,
  90907. configurable: true
  90908. });
  90909. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90910. /**
  90911. * Gets a boolean defining if the target contains normal data
  90912. */
  90913. get: function () {
  90914. return !!this._normals;
  90915. },
  90916. enumerable: true,
  90917. configurable: true
  90918. });
  90919. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90920. /**
  90921. * Gets a boolean defining if the target contains tangent data
  90922. */
  90923. get: function () {
  90924. return !!this._tangents;
  90925. },
  90926. enumerable: true,
  90927. configurable: true
  90928. });
  90929. /**
  90930. * Affects position data to this target
  90931. * @param data defines the position data to use
  90932. */
  90933. MorphTarget.prototype.setPositions = function (data) {
  90934. this._positions = data;
  90935. };
  90936. /**
  90937. * Gets the position data stored in this target
  90938. * @returns a FloatArray containing the position data (or null if not present)
  90939. */
  90940. MorphTarget.prototype.getPositions = function () {
  90941. return this._positions;
  90942. };
  90943. /**
  90944. * Affects normal data to this target
  90945. * @param data defines the normal data to use
  90946. */
  90947. MorphTarget.prototype.setNormals = function (data) {
  90948. this._normals = data;
  90949. };
  90950. /**
  90951. * Gets the normal data stored in this target
  90952. * @returns a FloatArray containing the normal data (or null if not present)
  90953. */
  90954. MorphTarget.prototype.getNormals = function () {
  90955. return this._normals;
  90956. };
  90957. /**
  90958. * Affects tangent data to this target
  90959. * @param data defines the tangent data to use
  90960. */
  90961. MorphTarget.prototype.setTangents = function (data) {
  90962. this._tangents = data;
  90963. };
  90964. /**
  90965. * Gets the tangent data stored in this target
  90966. * @returns a FloatArray containing the tangent data (or null if not present)
  90967. */
  90968. MorphTarget.prototype.getTangents = function () {
  90969. return this._tangents;
  90970. };
  90971. /**
  90972. * Serializes the current target into a Serialization object
  90973. * @returns the serialized object
  90974. */
  90975. MorphTarget.prototype.serialize = function () {
  90976. var serializationObject = {};
  90977. serializationObject.name = this.name;
  90978. serializationObject.influence = this.influence;
  90979. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90980. if (this.hasNormals) {
  90981. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90982. }
  90983. if (this.hasTangents) {
  90984. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90985. }
  90986. // Animations
  90987. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90988. return serializationObject;
  90989. };
  90990. // Statics
  90991. /**
  90992. * Creates a new target from serialized data
  90993. * @param serializationObject defines the serialized data to use
  90994. * @returns a new MorphTarget
  90995. */
  90996. MorphTarget.Parse = function (serializationObject) {
  90997. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90998. result.setPositions(serializationObject.positions);
  90999. if (serializationObject.normals) {
  91000. result.setNormals(serializationObject.normals);
  91001. }
  91002. if (serializationObject.tangents) {
  91003. result.setTangents(serializationObject.tangents);
  91004. }
  91005. // Animations
  91006. if (serializationObject.animations) {
  91007. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91008. var parsedAnimation = serializationObject.animations[animationIndex];
  91009. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91010. }
  91011. }
  91012. return result;
  91013. };
  91014. /**
  91015. * Creates a MorphTarget from mesh data
  91016. * @param mesh defines the source mesh
  91017. * @param name defines the name to use for the new target
  91018. * @param influence defines the influence to attach to the target
  91019. * @returns a new MorphTarget
  91020. */
  91021. MorphTarget.FromMesh = function (mesh, name, influence) {
  91022. if (!name) {
  91023. name = mesh.name;
  91024. }
  91025. var result = new MorphTarget(name, influence, mesh.getScene());
  91026. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91028. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91029. }
  91030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91031. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91032. }
  91033. return result;
  91034. };
  91035. return MorphTarget;
  91036. }());
  91037. BABYLON.MorphTarget = MorphTarget;
  91038. })(BABYLON || (BABYLON = {}));
  91039. //# sourceMappingURL=babylon.morphTarget.js.map
  91040. var BABYLON;
  91041. (function (BABYLON) {
  91042. /**
  91043. * This class is used to deform meshes using morphing between different targets
  91044. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91045. */
  91046. var MorphTargetManager = /** @class */ (function () {
  91047. /**
  91048. * Creates a new MorphTargetManager
  91049. * @param scene defines the current scene
  91050. */
  91051. function MorphTargetManager(scene) {
  91052. if (scene === void 0) { scene = null; }
  91053. this._targets = new Array();
  91054. this._targetObservable = new Array();
  91055. this._activeTargets = new BABYLON.SmartArray(16);
  91056. this._supportsNormals = false;
  91057. this._supportsTangents = false;
  91058. this._vertexCount = 0;
  91059. this._uniqueId = 0;
  91060. this._tempInfluences = new Array();
  91061. if (!scene) {
  91062. scene = BABYLON.Engine.LastCreatedScene;
  91063. }
  91064. this._scene = scene;
  91065. if (this._scene) {
  91066. this._scene.morphTargetManagers.push(this);
  91067. this._uniqueId = this._scene.getUniqueId();
  91068. }
  91069. }
  91070. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91071. /**
  91072. * Gets the unique ID of this manager
  91073. */
  91074. get: function () {
  91075. return this._uniqueId;
  91076. },
  91077. enumerable: true,
  91078. configurable: true
  91079. });
  91080. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91081. /**
  91082. * Gets the number of vertices handled by this manager
  91083. */
  91084. get: function () {
  91085. return this._vertexCount;
  91086. },
  91087. enumerable: true,
  91088. configurable: true
  91089. });
  91090. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91091. /**
  91092. * Gets a boolean indicating if this manager supports morphing of normals
  91093. */
  91094. get: function () {
  91095. return this._supportsNormals;
  91096. },
  91097. enumerable: true,
  91098. configurable: true
  91099. });
  91100. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91101. /**
  91102. * Gets a boolean indicating if this manager supports morphing of tangents
  91103. */
  91104. get: function () {
  91105. return this._supportsTangents;
  91106. },
  91107. enumerable: true,
  91108. configurable: true
  91109. });
  91110. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91111. /**
  91112. * Gets the number of targets stored in this manager
  91113. */
  91114. get: function () {
  91115. return this._targets.length;
  91116. },
  91117. enumerable: true,
  91118. configurable: true
  91119. });
  91120. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91121. /**
  91122. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91123. */
  91124. get: function () {
  91125. return this._activeTargets.length;
  91126. },
  91127. enumerable: true,
  91128. configurable: true
  91129. });
  91130. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91131. /**
  91132. * Gets the list of influences (one per target)
  91133. */
  91134. get: function () {
  91135. return this._influences;
  91136. },
  91137. enumerable: true,
  91138. configurable: true
  91139. });
  91140. /**
  91141. * Gets the active target at specified index. An active target is a target with an influence > 0
  91142. * @param index defines the index to check
  91143. * @returns the requested target
  91144. */
  91145. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91146. return this._activeTargets.data[index];
  91147. };
  91148. /**
  91149. * Gets the target at specified index
  91150. * @param index defines the index to check
  91151. * @returns the requested target
  91152. */
  91153. MorphTargetManager.prototype.getTarget = function (index) {
  91154. return this._targets[index];
  91155. };
  91156. /**
  91157. * Add a new target to this manager
  91158. * @param target defines the target to add
  91159. */
  91160. MorphTargetManager.prototype.addTarget = function (target) {
  91161. var _this = this;
  91162. this._targets.push(target);
  91163. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91164. _this._syncActiveTargets(needUpdate);
  91165. }));
  91166. this._syncActiveTargets(true);
  91167. };
  91168. /**
  91169. * Removes a target from the manager
  91170. * @param target defines the target to remove
  91171. */
  91172. MorphTargetManager.prototype.removeTarget = function (target) {
  91173. var index = this._targets.indexOf(target);
  91174. if (index >= 0) {
  91175. this._targets.splice(index, 1);
  91176. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91177. this._syncActiveTargets(true);
  91178. }
  91179. };
  91180. /**
  91181. * Serializes the current manager into a Serialization object
  91182. * @returns the serialized object
  91183. */
  91184. MorphTargetManager.prototype.serialize = function () {
  91185. var serializationObject = {};
  91186. serializationObject.id = this.uniqueId;
  91187. serializationObject.targets = [];
  91188. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91189. var target = _a[_i];
  91190. serializationObject.targets.push(target.serialize());
  91191. }
  91192. return serializationObject;
  91193. };
  91194. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91195. var influenceCount = 0;
  91196. this._activeTargets.reset();
  91197. this._supportsNormals = true;
  91198. this._supportsTangents = true;
  91199. this._vertexCount = 0;
  91200. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91201. var target = _a[_i];
  91202. this._activeTargets.push(target);
  91203. this._tempInfluences[influenceCount++] = target.influence;
  91204. var positions = target.getPositions();
  91205. if (positions) {
  91206. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91207. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91208. var vertexCount = positions.length / 3;
  91209. if (this._vertexCount === 0) {
  91210. this._vertexCount = vertexCount;
  91211. }
  91212. else if (this._vertexCount !== vertexCount) {
  91213. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91214. return;
  91215. }
  91216. }
  91217. }
  91218. if (!this._influences || this._influences.length !== influenceCount) {
  91219. this._influences = new Float32Array(influenceCount);
  91220. }
  91221. for (var index = 0; index < influenceCount; index++) {
  91222. this._influences[index] = this._tempInfluences[index];
  91223. }
  91224. if (needUpdate) {
  91225. this.synchronize();
  91226. }
  91227. };
  91228. /**
  91229. * Syncrhonize the targets with all the meshes using this morph target manager
  91230. */
  91231. MorphTargetManager.prototype.synchronize = function () {
  91232. if (!this._scene) {
  91233. return;
  91234. }
  91235. // Flag meshes as dirty to resync with the active targets
  91236. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91237. var mesh = _a[_i];
  91238. if (mesh.morphTargetManager === this) {
  91239. mesh._syncGeometryWithMorphTargetManager();
  91240. }
  91241. }
  91242. };
  91243. // Statics
  91244. /**
  91245. * Creates a new MorphTargetManager from serialized data
  91246. * @param serializationObject defines the serialized data
  91247. * @param scene defines the hosting scene
  91248. * @returns the new MorphTargetManager
  91249. */
  91250. MorphTargetManager.Parse = function (serializationObject, scene) {
  91251. var result = new MorphTargetManager(scene);
  91252. result._uniqueId = serializationObject.id;
  91253. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91254. var targetData = _a[_i];
  91255. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91256. }
  91257. return result;
  91258. };
  91259. return MorphTargetManager;
  91260. }());
  91261. BABYLON.MorphTargetManager = MorphTargetManager;
  91262. })(BABYLON || (BABYLON = {}));
  91263. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91264. var BABYLON;
  91265. (function (BABYLON) {
  91266. var Octree = /** @class */ (function () {
  91267. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91268. if (maxDepth === void 0) { maxDepth = 2; }
  91269. this.maxDepth = maxDepth;
  91270. this.dynamicContent = new Array();
  91271. this._maxBlockCapacity = maxBlockCapacity || 64;
  91272. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91273. this._creationFunc = creationFunc;
  91274. }
  91275. // Methods
  91276. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91277. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91278. };
  91279. Octree.prototype.addMesh = function (entry) {
  91280. for (var index = 0; index < this.blocks.length; index++) {
  91281. var block = this.blocks[index];
  91282. block.addEntry(entry);
  91283. }
  91284. };
  91285. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91286. this._selectionContent.reset();
  91287. for (var index = 0; index < this.blocks.length; index++) {
  91288. var block = this.blocks[index];
  91289. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91290. }
  91291. if (allowDuplicate) {
  91292. this._selectionContent.concat(this.dynamicContent);
  91293. }
  91294. else {
  91295. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91296. }
  91297. return this._selectionContent;
  91298. };
  91299. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91300. this._selectionContent.reset();
  91301. for (var index = 0; index < this.blocks.length; index++) {
  91302. var block = this.blocks[index];
  91303. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91304. }
  91305. if (allowDuplicate) {
  91306. this._selectionContent.concat(this.dynamicContent);
  91307. }
  91308. else {
  91309. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91310. }
  91311. return this._selectionContent;
  91312. };
  91313. Octree.prototype.intersectsRay = function (ray) {
  91314. this._selectionContent.reset();
  91315. for (var index = 0; index < this.blocks.length; index++) {
  91316. var block = this.blocks[index];
  91317. block.intersectsRay(ray, this._selectionContent);
  91318. }
  91319. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91320. return this._selectionContent;
  91321. };
  91322. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91323. target.blocks = new Array();
  91324. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91325. // Segmenting space
  91326. for (var x = 0; x < 2; x++) {
  91327. for (var y = 0; y < 2; y++) {
  91328. for (var z = 0; z < 2; z++) {
  91329. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91330. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91331. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91332. block.addEntries(entries);
  91333. target.blocks.push(block);
  91334. }
  91335. }
  91336. }
  91337. };
  91338. Octree.CreationFuncForMeshes = function (entry, block) {
  91339. var boundingInfo = entry.getBoundingInfo();
  91340. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91341. block.entries.push(entry);
  91342. }
  91343. };
  91344. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91345. var boundingInfo = entry.getBoundingInfo();
  91346. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91347. block.entries.push(entry);
  91348. }
  91349. };
  91350. return Octree;
  91351. }());
  91352. BABYLON.Octree = Octree;
  91353. })(BABYLON || (BABYLON = {}));
  91354. //# sourceMappingURL=babylon.octree.js.map
  91355. var BABYLON;
  91356. (function (BABYLON) {
  91357. var OctreeBlock = /** @class */ (function () {
  91358. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91359. this.entries = new Array();
  91360. this._boundingVectors = new Array();
  91361. this._capacity = capacity;
  91362. this._depth = depth;
  91363. this._maxDepth = maxDepth;
  91364. this._creationFunc = creationFunc;
  91365. this._minPoint = minPoint;
  91366. this._maxPoint = maxPoint;
  91367. this._boundingVectors.push(minPoint.clone());
  91368. this._boundingVectors.push(maxPoint.clone());
  91369. this._boundingVectors.push(minPoint.clone());
  91370. this._boundingVectors[2].x = maxPoint.x;
  91371. this._boundingVectors.push(minPoint.clone());
  91372. this._boundingVectors[3].y = maxPoint.y;
  91373. this._boundingVectors.push(minPoint.clone());
  91374. this._boundingVectors[4].z = maxPoint.z;
  91375. this._boundingVectors.push(maxPoint.clone());
  91376. this._boundingVectors[5].z = minPoint.z;
  91377. this._boundingVectors.push(maxPoint.clone());
  91378. this._boundingVectors[6].x = minPoint.x;
  91379. this._boundingVectors.push(maxPoint.clone());
  91380. this._boundingVectors[7].y = minPoint.y;
  91381. }
  91382. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91383. // Property
  91384. get: function () {
  91385. return this._capacity;
  91386. },
  91387. enumerable: true,
  91388. configurable: true
  91389. });
  91390. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91391. get: function () {
  91392. return this._minPoint;
  91393. },
  91394. enumerable: true,
  91395. configurable: true
  91396. });
  91397. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91398. get: function () {
  91399. return this._maxPoint;
  91400. },
  91401. enumerable: true,
  91402. configurable: true
  91403. });
  91404. // Methods
  91405. OctreeBlock.prototype.addEntry = function (entry) {
  91406. if (this.blocks) {
  91407. for (var index = 0; index < this.blocks.length; index++) {
  91408. var block = this.blocks[index];
  91409. block.addEntry(entry);
  91410. }
  91411. return;
  91412. }
  91413. this._creationFunc(entry, this);
  91414. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91415. this.createInnerBlocks();
  91416. }
  91417. };
  91418. OctreeBlock.prototype.addEntries = function (entries) {
  91419. for (var index = 0; index < entries.length; index++) {
  91420. var mesh = entries[index];
  91421. this.addEntry(mesh);
  91422. }
  91423. };
  91424. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91425. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91426. if (this.blocks) {
  91427. for (var index = 0; index < this.blocks.length; index++) {
  91428. var block = this.blocks[index];
  91429. block.select(frustumPlanes, selection, allowDuplicate);
  91430. }
  91431. return;
  91432. }
  91433. if (allowDuplicate) {
  91434. selection.concat(this.entries);
  91435. }
  91436. else {
  91437. selection.concatWithNoDuplicate(this.entries);
  91438. }
  91439. }
  91440. };
  91441. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91442. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91443. if (this.blocks) {
  91444. for (var index = 0; index < this.blocks.length; index++) {
  91445. var block = this.blocks[index];
  91446. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91447. }
  91448. return;
  91449. }
  91450. if (allowDuplicate) {
  91451. selection.concat(this.entries);
  91452. }
  91453. else {
  91454. selection.concatWithNoDuplicate(this.entries);
  91455. }
  91456. }
  91457. };
  91458. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91459. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91460. if (this.blocks) {
  91461. for (var index = 0; index < this.blocks.length; index++) {
  91462. var block = this.blocks[index];
  91463. block.intersectsRay(ray, selection);
  91464. }
  91465. return;
  91466. }
  91467. selection.concatWithNoDuplicate(this.entries);
  91468. }
  91469. };
  91470. OctreeBlock.prototype.createInnerBlocks = function () {
  91471. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91472. };
  91473. return OctreeBlock;
  91474. }());
  91475. BABYLON.OctreeBlock = OctreeBlock;
  91476. })(BABYLON || (BABYLON = {}));
  91477. //# sourceMappingURL=babylon.octreeBlock.js.map
  91478. var BABYLON;
  91479. (function (BABYLON) {
  91480. /**
  91481. * Postprocess used to generate anaglyphic rendering
  91482. */
  91483. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91484. __extends(AnaglyphPostProcess, _super);
  91485. /**
  91486. * Creates a new AnaglyphPostProcess
  91487. * @param name defines postprocess name
  91488. * @param options defines creation options or target ratio scale
  91489. * @param rigCameras defines cameras using this postprocess
  91490. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91491. * @param engine defines hosting engine
  91492. * @param reusable defines if the postprocess will be reused multiple times per frame
  91493. */
  91494. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91495. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91496. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91497. _this.onApplyObservable.add(function (effect) {
  91498. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91499. });
  91500. return _this;
  91501. }
  91502. return AnaglyphPostProcess;
  91503. }(BABYLON.PostProcess));
  91504. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91505. })(BABYLON || (BABYLON = {}));
  91506. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91507. var BABYLON;
  91508. (function (BABYLON) {
  91509. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91510. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91511. });
  91512. /**
  91513. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91514. */
  91515. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91516. __extends(AnaglyphArcRotateCamera, _super);
  91517. /**
  91518. * Creates a new AnaglyphArcRotateCamera
  91519. * @param name defines camera name
  91520. * @param alpha defines alpha angle (in radians)
  91521. * @param beta defines beta angle (in radians)
  91522. * @param radius defines radius
  91523. * @param target defines camera target
  91524. * @param interaxialDistance defines distance between each color axis
  91525. * @param scene defines the hosting scene
  91526. */
  91527. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91528. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91529. _this.interaxialDistance = interaxialDistance;
  91530. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91531. return _this;
  91532. }
  91533. /**
  91534. * Gets camera class name
  91535. * @returns AnaglyphArcRotateCamera
  91536. */
  91537. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91538. return "AnaglyphArcRotateCamera";
  91539. };
  91540. return AnaglyphArcRotateCamera;
  91541. }(BABYLON.ArcRotateCamera));
  91542. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91543. })(BABYLON || (BABYLON = {}));
  91544. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91545. var BABYLON;
  91546. (function (BABYLON) {
  91547. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91548. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91549. });
  91550. /**
  91551. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91552. */
  91553. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91554. __extends(AnaglyphFreeCamera, _super);
  91555. /**
  91556. * Creates a new AnaglyphFreeCamera
  91557. * @param name defines camera name
  91558. * @param position defines initial position
  91559. * @param interaxialDistance defines distance between each color axis
  91560. * @param scene defines the hosting scene
  91561. */
  91562. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91563. var _this = _super.call(this, name, position, scene) || this;
  91564. _this.interaxialDistance = interaxialDistance;
  91565. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91566. return _this;
  91567. }
  91568. /**
  91569. * Gets camera class name
  91570. * @returns AnaglyphFreeCamera
  91571. */
  91572. AnaglyphFreeCamera.prototype.getClassName = function () {
  91573. return "AnaglyphFreeCamera";
  91574. };
  91575. return AnaglyphFreeCamera;
  91576. }(BABYLON.FreeCamera));
  91577. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91578. })(BABYLON || (BABYLON = {}));
  91579. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91580. var BABYLON;
  91581. (function (BABYLON) {
  91582. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91583. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91584. });
  91585. /**
  91586. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91587. */
  91588. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91589. __extends(AnaglyphGamepadCamera, _super);
  91590. /**
  91591. * Creates a new AnaglyphGamepadCamera
  91592. * @param name defines camera name
  91593. * @param position defines initial position
  91594. * @param interaxialDistance defines distance between each color axis
  91595. * @param scene defines the hosting scene
  91596. */
  91597. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91598. var _this = _super.call(this, name, position, scene) || this;
  91599. _this.interaxialDistance = interaxialDistance;
  91600. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91601. return _this;
  91602. }
  91603. /**
  91604. * Gets camera class name
  91605. * @returns AnaglyphGamepadCamera
  91606. */
  91607. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91608. return "AnaglyphGamepadCamera";
  91609. };
  91610. return AnaglyphGamepadCamera;
  91611. }(BABYLON.GamepadCamera));
  91612. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91613. })(BABYLON || (BABYLON = {}));
  91614. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91615. var BABYLON;
  91616. (function (BABYLON) {
  91617. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91618. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91619. });
  91620. /**
  91621. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91622. */
  91623. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91624. __extends(AnaglyphUniversalCamera, _super);
  91625. /**
  91626. * Creates a new AnaglyphUniversalCamera
  91627. * @param name defines camera name
  91628. * @param position defines initial position
  91629. * @param interaxialDistance defines distance between each color axis
  91630. * @param scene defines the hosting scene
  91631. */
  91632. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91633. var _this = _super.call(this, name, position, scene) || this;
  91634. _this.interaxialDistance = interaxialDistance;
  91635. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91636. return _this;
  91637. }
  91638. /**
  91639. * Gets camera class name
  91640. * @returns AnaglyphUniversalCamera
  91641. */
  91642. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91643. return "AnaglyphUniversalCamera";
  91644. };
  91645. return AnaglyphUniversalCamera;
  91646. }(BABYLON.UniversalCamera));
  91647. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91648. })(BABYLON || (BABYLON = {}));
  91649. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91650. var BABYLON;
  91651. (function (BABYLON) {
  91652. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91653. __extends(StereoscopicInterlacePostProcess, _super);
  91654. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91655. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91656. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91657. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91658. _this.onSizeChangedObservable.add(function () {
  91659. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91660. });
  91661. _this.onApplyObservable.add(function (effect) {
  91662. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91663. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91664. });
  91665. return _this;
  91666. }
  91667. return StereoscopicInterlacePostProcess;
  91668. }(BABYLON.PostProcess));
  91669. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91670. })(BABYLON || (BABYLON = {}));
  91671. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91672. var BABYLON;
  91673. (function (BABYLON) {
  91674. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  91675. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91676. });
  91677. /**
  91678. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91679. */
  91680. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91681. __extends(StereoscopicArcRotateCamera, _super);
  91682. /**
  91683. * Creates a new StereoscopicArcRotateCamera
  91684. * @param name defines camera name
  91685. * @param alpha defines alpha angle (in radians)
  91686. * @param beta defines beta angle (in radians)
  91687. * @param radius defines radius
  91688. * @param target defines camera target
  91689. * @param interaxialDistance defines distance between each color axis
  91690. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91691. * @param scene defines the hosting scene
  91692. */
  91693. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91694. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91695. _this.interaxialDistance = interaxialDistance;
  91696. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91697. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91698. return _this;
  91699. }
  91700. /**
  91701. * Gets camera class name
  91702. * @returns StereoscopicArcRotateCamera
  91703. */
  91704. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91705. return "StereoscopicArcRotateCamera";
  91706. };
  91707. return StereoscopicArcRotateCamera;
  91708. }(BABYLON.ArcRotateCamera));
  91709. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91710. })(BABYLON || (BABYLON = {}));
  91711. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  91712. var BABYLON;
  91713. (function (BABYLON) {
  91714. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91715. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91716. });
  91717. /**
  91718. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91719. */
  91720. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91721. __extends(StereoscopicFreeCamera, _super);
  91722. /**
  91723. * Creates a new StereoscopicFreeCamera
  91724. * @param name defines camera name
  91725. * @param position defines initial position
  91726. * @param interaxialDistance defines distance between each color axis
  91727. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91728. * @param scene defines the hosting scene
  91729. */
  91730. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91731. var _this = _super.call(this, name, position, scene) || this;
  91732. _this.interaxialDistance = interaxialDistance;
  91733. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91734. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91735. return _this;
  91736. }
  91737. /**
  91738. * Gets camera class name
  91739. * @returns StereoscopicFreeCamera
  91740. */
  91741. StereoscopicFreeCamera.prototype.getClassName = function () {
  91742. return "StereoscopicFreeCamera";
  91743. };
  91744. return StereoscopicFreeCamera;
  91745. }(BABYLON.FreeCamera));
  91746. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91747. })(BABYLON || (BABYLON = {}));
  91748. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  91749. var BABYLON;
  91750. (function (BABYLON) {
  91751. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  91752. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91753. });
  91754. /**
  91755. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91756. */
  91757. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91758. __extends(StereoscopicGamepadCamera, _super);
  91759. /**
  91760. * Creates a new StereoscopicGamepadCamera
  91761. * @param name defines camera name
  91762. * @param position defines initial position
  91763. * @param interaxialDistance defines distance between each color axis
  91764. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91765. * @param scene defines the hosting scene
  91766. */
  91767. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91768. var _this = _super.call(this, name, position, scene) || this;
  91769. _this.interaxialDistance = interaxialDistance;
  91770. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91771. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91772. return _this;
  91773. }
  91774. /**
  91775. * Gets camera class name
  91776. * @returns StereoscopicGamepadCamera
  91777. */
  91778. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91779. return "StereoscopicGamepadCamera";
  91780. };
  91781. return StereoscopicGamepadCamera;
  91782. }(BABYLON.GamepadCamera));
  91783. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91784. })(BABYLON || (BABYLON = {}));
  91785. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  91786. var BABYLON;
  91787. (function (BABYLON) {
  91788. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91789. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91790. });
  91791. /**
  91792. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91793. */
  91794. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91795. __extends(StereoscopicUniversalCamera, _super);
  91796. /**
  91797. * Creates a new StereoscopicUniversalCamera
  91798. * @param name defines camera name
  91799. * @param position defines initial position
  91800. * @param interaxialDistance defines distance between each color axis
  91801. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91802. * @param scene defines the hosting scene
  91803. */
  91804. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91805. var _this = _super.call(this, name, position, scene) || this;
  91806. _this.interaxialDistance = interaxialDistance;
  91807. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91808. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91809. return _this;
  91810. }
  91811. /**
  91812. * Gets camera class name
  91813. * @returns StereoscopicUniversalCamera
  91814. */
  91815. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91816. return "StereoscopicUniversalCamera";
  91817. };
  91818. return StereoscopicUniversalCamera;
  91819. }(BABYLON.UniversalCamera));
  91820. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91821. })(BABYLON || (BABYLON = {}));
  91822. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  91823. var BABYLON;
  91824. (function (BABYLON) {
  91825. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91826. __extends(VRDistortionCorrectionPostProcess, _super);
  91827. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91828. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91829. 'LensCenter',
  91830. 'Scale',
  91831. 'ScaleIn',
  91832. 'HmdWarpParam'
  91833. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91834. _this._isRightEye = isRightEye;
  91835. _this._distortionFactors = vrMetrics.distortionK;
  91836. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91837. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91838. _this.adaptScaleToCurrentViewport = true;
  91839. _this.onSizeChangedObservable.add(function () {
  91840. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91841. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91842. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91843. });
  91844. _this.onApplyObservable.add(function (effect) {
  91845. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91846. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91847. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91848. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91849. });
  91850. return _this;
  91851. }
  91852. return VRDistortionCorrectionPostProcess;
  91853. }(BABYLON.PostProcess));
  91854. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91855. })(BABYLON || (BABYLON = {}));
  91856. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91857. var BABYLON;
  91858. (function (BABYLON) {
  91859. /**
  91860. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91861. * Screen rotation is taken into account.
  91862. */
  91863. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91864. function FreeCameraDeviceOrientationInput() {
  91865. var _this = this;
  91866. this._screenOrientationAngle = 0;
  91867. this._screenQuaternion = new BABYLON.Quaternion();
  91868. this._alpha = 0;
  91869. this._beta = 0;
  91870. this._gamma = 0;
  91871. this._orientationChanged = function () {
  91872. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91873. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91874. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91875. };
  91876. this._deviceOrientation = function (evt) {
  91877. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91878. _this._beta = evt.beta !== null ? evt.beta : 0;
  91879. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91880. };
  91881. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91882. this._orientationChanged();
  91883. }
  91884. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91885. get: function () {
  91886. return this._camera;
  91887. },
  91888. set: function (camera) {
  91889. this._camera = camera;
  91890. if (this._camera != null && !this._camera.rotationQuaternion) {
  91891. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91892. }
  91893. },
  91894. enumerable: true,
  91895. configurable: true
  91896. });
  91897. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91898. window.addEventListener("orientationchange", this._orientationChanged);
  91899. window.addEventListener("deviceorientation", this._deviceOrientation);
  91900. //In certain cases, the attach control is called AFTER orientation was changed,
  91901. //So this is needed.
  91902. this._orientationChanged();
  91903. };
  91904. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91905. window.removeEventListener("orientationchange", this._orientationChanged);
  91906. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91907. };
  91908. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91909. //if no device orientation provided, don't update the rotation.
  91910. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91911. if (!this._alpha)
  91912. return;
  91913. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91914. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91915. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91916. //Mirror on XY Plane
  91917. this._camera.rotationQuaternion.z *= -1;
  91918. this._camera.rotationQuaternion.w *= -1;
  91919. };
  91920. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91921. return "FreeCameraDeviceOrientationInput";
  91922. };
  91923. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91924. return "deviceOrientation";
  91925. };
  91926. return FreeCameraDeviceOrientationInput;
  91927. }());
  91928. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91929. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91930. })(BABYLON || (BABYLON = {}));
  91931. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91932. var BABYLON;
  91933. (function (BABYLON) {
  91934. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91935. function ArcRotateCameraVRDeviceOrientationInput() {
  91936. this.alphaCorrection = 1;
  91937. this.betaCorrection = 1;
  91938. this.gammaCorrection = 1;
  91939. this._alpha = 0;
  91940. this._gamma = 0;
  91941. this._dirty = false;
  91942. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91943. }
  91944. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91945. this.camera.attachControl(element, noPreventDefault);
  91946. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91947. };
  91948. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91949. if (evt.alpha !== null) {
  91950. this._alpha = +evt.alpha | 0;
  91951. }
  91952. if (evt.gamma !== null) {
  91953. this._gamma = +evt.gamma | 0;
  91954. }
  91955. this._dirty = true;
  91956. };
  91957. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91958. if (this._dirty) {
  91959. this._dirty = false;
  91960. if (this._gamma < 0) {
  91961. this._gamma = 180 + this._gamma;
  91962. }
  91963. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91964. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91965. }
  91966. };
  91967. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91968. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91969. };
  91970. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91971. return "ArcRotateCameraVRDeviceOrientationInput";
  91972. };
  91973. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91974. return "VRDeviceOrientation";
  91975. };
  91976. return ArcRotateCameraVRDeviceOrientationInput;
  91977. }());
  91978. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91979. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91980. })(BABYLON || (BABYLON = {}));
  91981. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91982. var BABYLON;
  91983. (function (BABYLON) {
  91984. var VRCameraMetrics = /** @class */ (function () {
  91985. function VRCameraMetrics() {
  91986. this.compensateDistortion = true;
  91987. }
  91988. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91989. get: function () {
  91990. return this.hResolution / (2 * this.vResolution);
  91991. },
  91992. enumerable: true,
  91993. configurable: true
  91994. });
  91995. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91996. get: function () {
  91997. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91998. },
  91999. enumerable: true,
  92000. configurable: true
  92001. });
  92002. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92003. get: function () {
  92004. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92005. var h = (4 * meters) / this.hScreenSize;
  92006. return BABYLON.Matrix.Translation(h, 0, 0);
  92007. },
  92008. enumerable: true,
  92009. configurable: true
  92010. });
  92011. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92012. get: function () {
  92013. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92014. var h = (4 * meters) / this.hScreenSize;
  92015. return BABYLON.Matrix.Translation(-h, 0, 0);
  92016. },
  92017. enumerable: true,
  92018. configurable: true
  92019. });
  92020. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92021. get: function () {
  92022. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92023. },
  92024. enumerable: true,
  92025. configurable: true
  92026. });
  92027. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92028. get: function () {
  92029. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92030. },
  92031. enumerable: true,
  92032. configurable: true
  92033. });
  92034. VRCameraMetrics.GetDefault = function () {
  92035. var result = new VRCameraMetrics();
  92036. result.hResolution = 1280;
  92037. result.vResolution = 800;
  92038. result.hScreenSize = 0.149759993;
  92039. result.vScreenSize = 0.0935999975;
  92040. result.vScreenCenter = 0.0467999987;
  92041. result.eyeToScreenDistance = 0.0410000011;
  92042. result.lensSeparationDistance = 0.0635000020;
  92043. result.interpupillaryDistance = 0.0640000030;
  92044. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92045. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92046. result.postProcessScaleFactor = 1.714605507808412;
  92047. result.lensCenterOffset = 0.151976421;
  92048. return result;
  92049. };
  92050. return VRCameraMetrics;
  92051. }());
  92052. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92053. })(BABYLON || (BABYLON = {}));
  92054. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92055. var BABYLON;
  92056. (function (BABYLON) {
  92057. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92058. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92059. });
  92060. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92061. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92062. });
  92063. /**
  92064. * This represents a WebVR camera.
  92065. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92066. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92067. */
  92068. var WebVRFreeCamera = /** @class */ (function (_super) {
  92069. __extends(WebVRFreeCamera, _super);
  92070. /**
  92071. * Instantiates a WebVRFreeCamera.
  92072. * @param name The name of the WebVRFreeCamera
  92073. * @param position The starting anchor position for the camera
  92074. * @param scene The scene the camera belongs to
  92075. * @param webVROptions a set of customizable options for the webVRCamera
  92076. */
  92077. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92078. if (webVROptions === void 0) { webVROptions = {}; }
  92079. var _this = _super.call(this, name, position, scene) || this;
  92080. _this.webVROptions = webVROptions;
  92081. /**
  92082. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92083. */
  92084. _this._vrDevice = null;
  92085. /**
  92086. * The rawPose of the vrDevice.
  92087. */
  92088. _this.rawPose = null;
  92089. _this._specsVersion = "1.1";
  92090. _this._attached = false;
  92091. _this._descendants = [];
  92092. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92093. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92094. /** @hidden */
  92095. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92096. _this._standingMatrix = null;
  92097. /**
  92098. * Represents device position in babylon space.
  92099. */
  92100. _this.devicePosition = BABYLON.Vector3.Zero();
  92101. /**
  92102. * Represents device rotation in babylon space.
  92103. */
  92104. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92105. /**
  92106. * The scale of the device to be used when translating from device space to babylon space.
  92107. */
  92108. _this.deviceScaleFactor = 1;
  92109. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92110. _this._worldToDevice = BABYLON.Matrix.Identity();
  92111. /**
  92112. * References to the webVR controllers for the vrDevice.
  92113. */
  92114. _this.controllers = [];
  92115. /**
  92116. * Emits an event when a controller is attached.
  92117. */
  92118. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92119. /**
  92120. * Emits an event when a controller's mesh has been loaded;
  92121. */
  92122. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92123. /**
  92124. * Emits an event when the HMD's pose has been updated.
  92125. */
  92126. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92127. _this._poseSet = false;
  92128. /**
  92129. * If the rig cameras be used as parent instead of this camera.
  92130. */
  92131. _this.rigParenting = true;
  92132. _this._defaultHeight = undefined;
  92133. _this._workingVector = BABYLON.Vector3.Zero();
  92134. _this._oneVector = BABYLON.Vector3.One();
  92135. _this._workingMatrix = BABYLON.Matrix.Identity();
  92136. _this._cache.position = BABYLON.Vector3.Zero();
  92137. if (webVROptions.defaultHeight) {
  92138. _this._defaultHeight = webVROptions.defaultHeight;
  92139. _this.position.y = _this._defaultHeight;
  92140. }
  92141. _this.minZ = 0.1;
  92142. //legacy support - the compensation boolean was removed.
  92143. if (arguments.length === 5) {
  92144. _this.webVROptions = arguments[4];
  92145. }
  92146. // default webVR options
  92147. if (_this.webVROptions.trackPosition == undefined) {
  92148. _this.webVROptions.trackPosition = true;
  92149. }
  92150. if (_this.webVROptions.controllerMeshes == undefined) {
  92151. _this.webVROptions.controllerMeshes = true;
  92152. }
  92153. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92154. _this.webVROptions.defaultLightingOnControllers = true;
  92155. }
  92156. _this.rotationQuaternion = new BABYLON.Quaternion();
  92157. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92158. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92159. }
  92160. //enable VR
  92161. var engine = _this.getEngine();
  92162. _this._onVREnabled = function (success) { if (success) {
  92163. _this.initControllers();
  92164. } };
  92165. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92166. engine.initWebVR().add(function (event) {
  92167. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92168. return;
  92169. }
  92170. _this._vrDevice = event.vrDisplay;
  92171. //reset the rig parameters.
  92172. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92173. if (_this._attached) {
  92174. _this.getEngine().enableVR();
  92175. }
  92176. });
  92177. if (typeof (VRFrameData) !== "undefined")
  92178. _this._frameData = new VRFrameData();
  92179. /**
  92180. * The idea behind the following lines:
  92181. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92182. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92183. * the second will not show it correctly.
  92184. *
  92185. * To solve this - each object that has the camera as parent will be added to a protected array.
  92186. * When the rig camera renders, it will take this array and set all of those to be its children.
  92187. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92188. * Amazing!
  92189. */
  92190. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92191. if (camera.parent === _this && _this.rigParenting) {
  92192. _this._descendants = _this.getDescendants(true, function (n) {
  92193. // don't take the cameras or the controllers!
  92194. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92195. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92196. return !isController && !isRigCamera;
  92197. });
  92198. _this._descendants.forEach(function (node) {
  92199. node.parent = camera;
  92200. });
  92201. }
  92202. });
  92203. scene.onAfterCameraRenderObservable.add(function (camera) {
  92204. if (camera.parent === _this && _this.rigParenting) {
  92205. _this._descendants.forEach(function (node) {
  92206. node.parent = _this;
  92207. });
  92208. }
  92209. });
  92210. return _this;
  92211. }
  92212. /**
  92213. * Gets the device distance from the ground in meters.
  92214. * @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.
  92215. */
  92216. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92217. if (this._standingMatrix) {
  92218. // Add standing matrix offset to get real offset from ground in room
  92219. this._standingMatrix.getTranslationToRef(this._workingVector);
  92220. return this._deviceRoomPosition.y + this._workingVector.y;
  92221. }
  92222. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92223. return this._defaultHeight || 0;
  92224. };
  92225. /**
  92226. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92227. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92228. */
  92229. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92230. var _this = this;
  92231. if (callback === void 0) { callback = function (bool) { }; }
  92232. // Use standing matrix if available
  92233. this.getEngine().initWebVRAsync().then(function (result) {
  92234. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92235. callback(false);
  92236. }
  92237. else {
  92238. _this._standingMatrix = new BABYLON.Matrix();
  92239. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92240. if (!_this.getScene().useRightHandedSystem) {
  92241. [2, 6, 8, 9, 14].forEach(function (num) {
  92242. if (_this._standingMatrix) {
  92243. _this._standingMatrix.m[num] *= -1;
  92244. }
  92245. });
  92246. }
  92247. callback(true);
  92248. }
  92249. });
  92250. };
  92251. /**
  92252. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92253. * @returns A promise with a boolean set to if the standing matrix is supported.
  92254. */
  92255. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92256. var _this = this;
  92257. return new Promise(function (res, rej) {
  92258. _this.useStandingMatrix(function (supported) {
  92259. res(supported);
  92260. });
  92261. });
  92262. };
  92263. /**
  92264. * Disposes the camera
  92265. */
  92266. WebVRFreeCamera.prototype.dispose = function () {
  92267. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92268. _super.prototype.dispose.call(this);
  92269. };
  92270. /**
  92271. * Gets a vrController by name.
  92272. * @param name The name of the controller to retreive
  92273. * @returns the controller matching the name specified or null if not found
  92274. */
  92275. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92276. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92277. var gp = _a[_i];
  92278. if (gp.hand === name) {
  92279. return gp;
  92280. }
  92281. }
  92282. return null;
  92283. };
  92284. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92285. /**
  92286. * The controller corrisponding to the users left hand.
  92287. */
  92288. get: function () {
  92289. if (!this._leftController) {
  92290. this._leftController = this.getControllerByName("left");
  92291. }
  92292. return this._leftController;
  92293. },
  92294. enumerable: true,
  92295. configurable: true
  92296. });
  92297. ;
  92298. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92299. /**
  92300. * The controller corrisponding to the users right hand.
  92301. */
  92302. get: function () {
  92303. if (!this._rightController) {
  92304. this._rightController = this.getControllerByName("right");
  92305. }
  92306. return this._rightController;
  92307. },
  92308. enumerable: true,
  92309. configurable: true
  92310. });
  92311. ;
  92312. /**
  92313. * Casts a ray forward from the vrCamera's gaze.
  92314. * @param length Length of the ray (default: 100)
  92315. * @returns the ray corrisponding to the gaze
  92316. */
  92317. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92318. if (length === void 0) { length = 100; }
  92319. if (this.leftCamera) {
  92320. // Use left eye to avoid computation to compute center on every call
  92321. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92322. }
  92323. else {
  92324. return _super.prototype.getForwardRay.call(this, length);
  92325. }
  92326. };
  92327. /**
  92328. * Updates the camera based on device's frame data
  92329. */
  92330. WebVRFreeCamera.prototype._checkInputs = function () {
  92331. if (this._vrDevice && this._vrDevice.isPresenting) {
  92332. this._vrDevice.getFrameData(this._frameData);
  92333. this.updateFromDevice(this._frameData.pose);
  92334. }
  92335. _super.prototype._checkInputs.call(this);
  92336. };
  92337. /**
  92338. * Updates the poseControlled values based on the input device pose.
  92339. * @param poseData Pose coming from the device
  92340. */
  92341. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92342. if (poseData && poseData.orientation) {
  92343. this.rawPose = poseData;
  92344. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92345. if (this.getScene().useRightHandedSystem) {
  92346. this._deviceRoomRotationQuaternion.z *= -1;
  92347. this._deviceRoomRotationQuaternion.w *= -1;
  92348. }
  92349. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92350. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92351. if (this.getScene().useRightHandedSystem) {
  92352. this._deviceRoomPosition.z *= -1;
  92353. }
  92354. }
  92355. this._poseSet = true;
  92356. }
  92357. };
  92358. /**
  92359. * WebVR's attach control will start broadcasting frames to the device.
  92360. * Note that in certain browsers (chrome for example) this function must be called
  92361. * within a user-interaction callback. Example:
  92362. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92363. *
  92364. * @param element html element to attach the vrDevice to
  92365. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92366. */
  92367. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92368. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92369. this._attached = true;
  92370. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92371. if (this._vrDevice) {
  92372. this.getEngine().enableVR();
  92373. }
  92374. };
  92375. /**
  92376. * Detaches the camera from the html element and disables VR
  92377. *
  92378. * @param element html element to detach from
  92379. */
  92380. WebVRFreeCamera.prototype.detachControl = function (element) {
  92381. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92382. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92383. _super.prototype.detachControl.call(this, element);
  92384. this._attached = false;
  92385. this.getEngine().disableVR();
  92386. };
  92387. /**
  92388. * @returns the name of this class
  92389. */
  92390. WebVRFreeCamera.prototype.getClassName = function () {
  92391. return "WebVRFreeCamera";
  92392. };
  92393. /**
  92394. * Calls resetPose on the vrDisplay
  92395. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92396. */
  92397. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92398. //uses the vrDisplay's "resetPose()".
  92399. //pitch and roll won't be affected.
  92400. this._vrDevice.resetPose();
  92401. };
  92402. /**
  92403. * Updates the rig cameras (left and right eye)
  92404. */
  92405. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92406. var camLeft = this._rigCameras[0];
  92407. var camRight = this._rigCameras[1];
  92408. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92409. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92410. camLeft.position.copyFrom(this._deviceRoomPosition);
  92411. camRight.position.copyFrom(this._deviceRoomPosition);
  92412. };
  92413. /**
  92414. * Updates the cached values of the camera
  92415. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92416. */
  92417. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92418. var _this = this;
  92419. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92420. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92421. if (!this.updateCacheCalled) {
  92422. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92423. this.updateCacheCalled = true;
  92424. this.update();
  92425. }
  92426. // Set working vector to the device position in room space rotated by the new rotation
  92427. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92428. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92429. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92430. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92431. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92432. // Add translation from anchor position
  92433. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92434. this._workingVector.addInPlace(this.position);
  92435. this._workingVector.subtractInPlace(this._cache.position);
  92436. this._deviceToWorld.setTranslation(this._workingVector);
  92437. // Set an inverted matrix to be used when updating the camera
  92438. this._deviceToWorld.invertToRef(this._worldToDevice);
  92439. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92440. this.controllers.forEach(function (controller) {
  92441. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92442. controller.update();
  92443. });
  92444. }
  92445. if (!ignoreParentClass) {
  92446. _super.prototype._updateCache.call(this);
  92447. }
  92448. this.updateCacheCalled = false;
  92449. };
  92450. /**
  92451. * Updates the current device position and rotation in the babylon world
  92452. */
  92453. WebVRFreeCamera.prototype.update = function () {
  92454. // Get current device position in babylon world
  92455. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92456. // Get current device rotation in babylon world
  92457. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92458. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92459. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92460. if (this._poseSet) {
  92461. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92462. }
  92463. _super.prototype.update.call(this);
  92464. };
  92465. /**
  92466. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92467. * @returns an identity matrix
  92468. */
  92469. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92470. return BABYLON.Matrix.Identity();
  92471. };
  92472. /**
  92473. * This function is called by the two RIG cameras.
  92474. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92475. */
  92476. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92477. var _this = this;
  92478. // Update the parent camera prior to using a child camera to avoid desynchronization
  92479. var parentCamera = this._cameraRigParams["parentCamera"];
  92480. parentCamera._updateCache();
  92481. //WebVR 1.1
  92482. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92483. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92484. if (!this.getScene().useRightHandedSystem) {
  92485. [2, 6, 8, 9, 14].forEach(function (num) {
  92486. _this._webvrViewMatrix.m[num] *= -1;
  92487. });
  92488. }
  92489. // update the camera rotation matrix
  92490. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92491. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92492. // Computing target and final matrix
  92493. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92494. // should the view matrix be updated with scale and position offset?
  92495. if (parentCamera.deviceScaleFactor !== 1) {
  92496. this._webvrViewMatrix.invert();
  92497. // scale the position, if set
  92498. if (parentCamera.deviceScaleFactor) {
  92499. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92500. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92501. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92502. }
  92503. this._webvrViewMatrix.invert();
  92504. }
  92505. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92506. // Compute global position
  92507. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92508. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92509. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92510. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92511. this._markSyncedWithParent();
  92512. return this._webvrViewMatrix;
  92513. };
  92514. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92515. var _this = this;
  92516. var parentCamera = this.parent;
  92517. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92518. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92519. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92520. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92521. //babylon compatible matrix
  92522. if (!this.getScene().useRightHandedSystem) {
  92523. [8, 9, 10, 11].forEach(function (num) {
  92524. _this._projectionMatrix.m[num] *= -1;
  92525. });
  92526. }
  92527. return this._projectionMatrix;
  92528. };
  92529. /**
  92530. * Initializes the controllers and their meshes
  92531. */
  92532. WebVRFreeCamera.prototype.initControllers = function () {
  92533. var _this = this;
  92534. this.controllers = [];
  92535. var manager = this.getScene().gamepadManager;
  92536. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92537. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92538. var webVrController = gamepad;
  92539. if (webVrController.defaultModel) {
  92540. webVrController.defaultModel.setEnabled(false);
  92541. }
  92542. if (webVrController.hand === "right") {
  92543. _this._rightController = null;
  92544. }
  92545. if (webVrController.hand === "left") {
  92546. _this._leftController = null;
  92547. }
  92548. var controllerIndex = _this.controllers.indexOf(webVrController);
  92549. if (controllerIndex !== -1) {
  92550. _this.controllers.splice(controllerIndex, 1);
  92551. }
  92552. }
  92553. });
  92554. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92555. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92556. var webVrController_1 = gamepad;
  92557. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92558. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92559. if (_this.webVROptions.controllerMeshes) {
  92560. if (webVrController_1.defaultModel) {
  92561. webVrController_1.defaultModel.setEnabled(true);
  92562. }
  92563. else {
  92564. // Load the meshes
  92565. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92566. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92567. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92568. if (_this.webVROptions.defaultLightingOnControllers) {
  92569. if (!_this._lightOnControllers) {
  92570. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92571. }
  92572. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92573. var children = mesh.getChildren();
  92574. if (children.length !== 0) {
  92575. children.forEach(function (mesh) {
  92576. light.includedOnlyMeshes.push(mesh);
  92577. activateLightOnSubMeshes_1(mesh, light);
  92578. });
  92579. }
  92580. };
  92581. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92582. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92583. }
  92584. });
  92585. }
  92586. }
  92587. webVrController_1.attachToPoseControlledCamera(_this);
  92588. // since this is async - sanity check. Is the controller already stored?
  92589. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92590. //add to the controllers array
  92591. _this.controllers.push(webVrController_1);
  92592. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92593. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92594. // So we're overriding setting left & right manually to be sure
  92595. var firstViveWandDetected = false;
  92596. for (var i = 0; i < _this.controllers.length; i++) {
  92597. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92598. if (!firstViveWandDetected) {
  92599. firstViveWandDetected = true;
  92600. _this.controllers[i].hand = "left";
  92601. }
  92602. else {
  92603. _this.controllers[i].hand = "right";
  92604. }
  92605. }
  92606. }
  92607. //did we find enough controllers? Great! let the developer know.
  92608. if (_this.controllers.length >= 2) {
  92609. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92610. }
  92611. }
  92612. }
  92613. });
  92614. };
  92615. return WebVRFreeCamera;
  92616. }(BABYLON.FreeCamera));
  92617. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92618. })(BABYLON || (BABYLON = {}));
  92619. //# sourceMappingURL=babylon.webVRCamera.js.map
  92620. var BABYLON;
  92621. (function (BABYLON) {
  92622. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92623. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92624. });
  92625. // We're mainly based on the logic defined into the FreeCamera code
  92626. /**
  92627. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92628. * being tilted forward or back and left or right.
  92629. */
  92630. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92631. __extends(DeviceOrientationCamera, _super);
  92632. /**
  92633. * Creates a new device orientation camera
  92634. * @param name The name of the camera
  92635. * @param position The start position camera
  92636. * @param scene The scene the camera belongs to
  92637. */
  92638. function DeviceOrientationCamera(name, position, scene) {
  92639. var _this = _super.call(this, name, position, scene) || this;
  92640. _this._quaternionCache = new BABYLON.Quaternion();
  92641. _this.inputs.addDeviceOrientation();
  92642. return _this;
  92643. }
  92644. /**
  92645. * Gets the current instance class name ("DeviceOrientationCamera").
  92646. * This helps avoiding instanceof at run time.
  92647. * @returns the class name
  92648. */
  92649. DeviceOrientationCamera.prototype.getClassName = function () {
  92650. return "DeviceOrientationCamera";
  92651. };
  92652. /**
  92653. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92654. */
  92655. DeviceOrientationCamera.prototype._checkInputs = function () {
  92656. _super.prototype._checkInputs.call(this);
  92657. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92658. if (this._initialQuaternion) {
  92659. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92660. }
  92661. };
  92662. /**
  92663. * Reset the camera to its default orientation on the specified axis only.
  92664. * @param axis The axis to reset
  92665. */
  92666. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92667. var _this = this;
  92668. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92669. //can only work if this camera has a rotation quaternion already.
  92670. if (!this.rotationQuaternion)
  92671. return;
  92672. if (!this._initialQuaternion) {
  92673. this._initialQuaternion = new BABYLON.Quaternion();
  92674. }
  92675. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92676. ['x', 'y', 'z'].forEach(function (axisName) {
  92677. if (!axis[axisName]) {
  92678. _this._initialQuaternion[axisName] = 0;
  92679. }
  92680. else {
  92681. _this._initialQuaternion[axisName] *= -1;
  92682. }
  92683. });
  92684. this._initialQuaternion.normalize();
  92685. //force rotation update
  92686. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92687. };
  92688. return DeviceOrientationCamera;
  92689. }(BABYLON.FreeCamera));
  92690. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92691. })(BABYLON || (BABYLON = {}));
  92692. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92693. var BABYLON;
  92694. (function (BABYLON) {
  92695. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92696. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92697. });
  92698. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92699. __extends(VRDeviceOrientationFreeCamera, _super);
  92700. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92701. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92702. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92703. var _this = _super.call(this, name, position, scene) || this;
  92704. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92705. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92706. return _this;
  92707. }
  92708. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92709. return "VRDeviceOrientationFreeCamera";
  92710. };
  92711. return VRDeviceOrientationFreeCamera;
  92712. }(BABYLON.DeviceOrientationCamera));
  92713. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92714. })(BABYLON || (BABYLON = {}));
  92715. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92716. var BABYLON;
  92717. (function (BABYLON) {
  92718. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92719. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92720. });
  92721. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92722. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92723. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92724. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92725. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92726. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92727. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92728. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92729. _this.inputs.addVRDeviceOrientation();
  92730. return _this;
  92731. }
  92732. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92733. return "VRDeviceOrientationArcRotateCamera";
  92734. };
  92735. return VRDeviceOrientationArcRotateCamera;
  92736. }(BABYLON.ArcRotateCamera));
  92737. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92738. })(BABYLON || (BABYLON = {}));
  92739. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92740. var BABYLON;
  92741. (function (BABYLON) {
  92742. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92743. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92744. });
  92745. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92746. __extends(VRDeviceOrientationGamepadCamera, _super);
  92747. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92748. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92749. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92750. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92751. _this.inputs.addGamepad();
  92752. return _this;
  92753. }
  92754. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92755. return "VRDeviceOrientationGamepadCamera";
  92756. };
  92757. return VRDeviceOrientationGamepadCamera;
  92758. }(BABYLON.VRDeviceOrientationFreeCamera));
  92759. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92760. })(BABYLON || (BABYLON = {}));
  92761. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92762. var BABYLON;
  92763. (function (BABYLON) {
  92764. var VRExperienceHelperGazer = /** @class */ (function () {
  92765. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92766. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92767. this.scene = scene;
  92768. this._pointerDownOnMeshAsked = false;
  92769. this._isActionableMesh = false;
  92770. this._teleportationRequestInitiated = false;
  92771. this._teleportationBackRequestInitiated = false;
  92772. this._rotationRightAsked = false;
  92773. this._rotationLeftAsked = false;
  92774. this._dpadPressed = true;
  92775. this._activePointer = false;
  92776. this._id = VRExperienceHelperGazer._idCounter++;
  92777. // Gaze tracker
  92778. if (!gazeTrackerToClone) {
  92779. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92780. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92781. this._gazeTracker.isPickable = false;
  92782. this._gazeTracker.isVisible = false;
  92783. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92784. targetMat.specularColor = BABYLON.Color3.Black();
  92785. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92786. targetMat.backFaceCulling = false;
  92787. this._gazeTracker.material = targetMat;
  92788. }
  92789. else {
  92790. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92791. }
  92792. }
  92793. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92794. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92795. };
  92796. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92797. this._pointerDownOnMeshAsked = true;
  92798. if (this._currentHit) {
  92799. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92800. }
  92801. };
  92802. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92803. if (this._currentHit) {
  92804. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92805. }
  92806. this._pointerDownOnMeshAsked = false;
  92807. };
  92808. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92809. this._activePointer = true;
  92810. };
  92811. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92812. this._activePointer = false;
  92813. };
  92814. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92815. if (distance === void 0) { distance = 100; }
  92816. };
  92817. VRExperienceHelperGazer.prototype.dispose = function () {
  92818. this._interactionsEnabled = false;
  92819. this._teleportationEnabled = false;
  92820. if (this._gazeTracker) {
  92821. this._gazeTracker.dispose();
  92822. }
  92823. };
  92824. VRExperienceHelperGazer._idCounter = 0;
  92825. return VRExperienceHelperGazer;
  92826. }());
  92827. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92828. __extends(VRExperienceHelperControllerGazer, _super);
  92829. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92830. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92831. _this.webVRController = webVRController;
  92832. // Laser pointer
  92833. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92834. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92835. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92836. laserPointerMaterial.alpha = 0.6;
  92837. _this._laserPointer.material = laserPointerMaterial;
  92838. _this._laserPointer.rotation.x = Math.PI / 2;
  92839. _this._laserPointer.position.z = -0.5;
  92840. _this._laserPointer.isVisible = false;
  92841. _this._laserPointer.isPickable = false;
  92842. if (!webVRController.mesh) {
  92843. // Create an empty mesh that is used prior to loading the high quality model
  92844. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92845. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92846. preloadPointerPose.rotation.x = -0.7;
  92847. preloadMesh.addChild(preloadPointerPose);
  92848. webVRController.attachToMesh(preloadMesh);
  92849. }
  92850. _this._setLaserPointerParent(webVRController.mesh);
  92851. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92852. _this._setLaserPointerParent(mesh);
  92853. });
  92854. return _this;
  92855. }
  92856. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92857. return this.webVRController.getForwardRay(length);
  92858. };
  92859. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92860. _super.prototype._activatePointer.call(this);
  92861. this._laserPointer.isVisible = true;
  92862. };
  92863. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92864. _super.prototype._deactivatePointer.call(this);
  92865. this._laserPointer.isVisible = false;
  92866. };
  92867. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92868. this._laserPointer.material.emissiveColor = color;
  92869. };
  92870. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92871. var makeNotPick = function (root) {
  92872. root.isPickable = false;
  92873. root.getChildMeshes().forEach(function (c) {
  92874. makeNotPick(c);
  92875. });
  92876. };
  92877. makeNotPick(mesh);
  92878. var childMeshes = mesh.getChildMeshes();
  92879. this.webVRController._pointingPoseNode = null;
  92880. for (var i = 0; i < childMeshes.length; i++) {
  92881. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92882. mesh = childMeshes[i];
  92883. this.webVRController._pointingPoseNode = mesh;
  92884. break;
  92885. }
  92886. }
  92887. this._laserPointer.parent = mesh;
  92888. };
  92889. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92890. if (distance === void 0) { distance = 100; }
  92891. this._laserPointer.scaling.y = distance;
  92892. this._laserPointer.position.z = -distance / 2;
  92893. };
  92894. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92895. _super.prototype.dispose.call(this);
  92896. this._laserPointer.dispose();
  92897. if (this._meshAttachedObserver) {
  92898. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92899. }
  92900. };
  92901. return VRExperienceHelperControllerGazer;
  92902. }(VRExperienceHelperGazer));
  92903. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92904. __extends(VRExperienceHelperCameraGazer, _super);
  92905. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92906. var _this = _super.call(this, scene) || this;
  92907. _this.getCamera = getCamera;
  92908. return _this;
  92909. }
  92910. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92911. var camera = this.getCamera();
  92912. if (camera) {
  92913. return camera.getForwardRay(length);
  92914. }
  92915. else {
  92916. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92917. }
  92918. };
  92919. return VRExperienceHelperCameraGazer;
  92920. }(VRExperienceHelperGazer));
  92921. /**
  92922. * Helps to quickly add VR support to an existing scene.
  92923. * See http://doc.babylonjs.com/how_to/webvr_helper
  92924. */
  92925. var VRExperienceHelper = /** @class */ (function () {
  92926. /**
  92927. * Instantiates a VRExperienceHelper.
  92928. * Helps to quickly add VR support to an existing scene.
  92929. * @param scene The scene the VRExperienceHelper belongs to.
  92930. * @param webVROptions Options to modify the vr experience helper's behavior.
  92931. */
  92932. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92933. if (webVROptions === void 0) { webVROptions = {}; }
  92934. var _this = this;
  92935. this.webVROptions = webVROptions;
  92936. // Can the system support WebVR, even if a headset isn't plugged in?
  92937. this._webVRsupported = false;
  92938. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92939. this._webVRready = false;
  92940. // Are we waiting for the requestPresent callback to complete?
  92941. this._webVRrequesting = false;
  92942. // Are we presenting to the headset right now?
  92943. this._webVRpresenting = false;
  92944. // Are we presenting in the fullscreen fallback?
  92945. this._fullscreenVRpresenting = false;
  92946. /**
  92947. * Observable raised when entering VR.
  92948. */
  92949. this.onEnteringVRObservable = new BABYLON.Observable();
  92950. /**
  92951. * Observable raised when exiting VR.
  92952. */
  92953. this.onExitingVRObservable = new BABYLON.Observable();
  92954. /**
  92955. * Observable raised when controller mesh is loaded.
  92956. */
  92957. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92958. this._useCustomVRButton = false;
  92959. this._teleportationRequested = false;
  92960. this._teleportActive = false;
  92961. this._floorMeshesCollection = [];
  92962. this._rotationAllowed = true;
  92963. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92964. this._isDefaultTeleportationTarget = true;
  92965. this._teleportationFillColor = "#444444";
  92966. this._teleportationBorderColor = "#FFFFFF";
  92967. this._rotationAngle = 0;
  92968. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92969. this._padSensibilityUp = 0.65;
  92970. this._padSensibilityDown = 0.35;
  92971. this.leftController = null;
  92972. this.rightController = null;
  92973. /**
  92974. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92975. */
  92976. this.onNewMeshSelected = new BABYLON.Observable();
  92977. /**
  92978. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92979. */
  92980. this.onNewMeshPicked = new BABYLON.Observable();
  92981. /**
  92982. * Observable raised before camera teleportation
  92983. */
  92984. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92985. /**
  92986. * Observable raised after camera teleportation
  92987. */
  92988. this.onAfterCameraTeleport = new BABYLON.Observable();
  92989. /**
  92990. * Observable raised when current selected mesh gets unselected
  92991. */
  92992. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92993. /**
  92994. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92995. */
  92996. this.teleportationEnabled = true;
  92997. this._teleportationInitialized = false;
  92998. this._interactionsEnabled = false;
  92999. this._interactionsRequested = false;
  93000. this._displayGaze = true;
  93001. this._displayLaserPointer = true;
  93002. this._onResize = function () {
  93003. _this.moveButtonToBottomRight();
  93004. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93005. _this.exitVR();
  93006. }
  93007. };
  93008. this._onFullscreenChange = function () {
  93009. if (document.fullscreen !== undefined) {
  93010. _this._fullscreenVRpresenting = document.fullscreen;
  93011. }
  93012. else if (document.mozFullScreen !== undefined) {
  93013. _this._fullscreenVRpresenting = document.mozFullScreen;
  93014. }
  93015. else if (document.webkitIsFullScreen !== undefined) {
  93016. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93017. }
  93018. else if (document.msIsFullScreen !== undefined) {
  93019. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93020. }
  93021. else if (document.msFullscreenElement !== undefined) {
  93022. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93023. }
  93024. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93025. _this.exitVR();
  93026. if (!_this._useCustomVRButton) {
  93027. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93028. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93029. }
  93030. }
  93031. };
  93032. this.beforeRender = function () {
  93033. if (_this.leftController && _this.leftController._activePointer) {
  93034. _this._castRayAndSelectObject(_this.leftController);
  93035. }
  93036. if (_this.rightController && _this.rightController._activePointer) {
  93037. _this._castRayAndSelectObject(_this.rightController);
  93038. }
  93039. if (_this._noControllerIsActive) {
  93040. _this._castRayAndSelectObject(_this._cameraGazer);
  93041. }
  93042. else {
  93043. _this._cameraGazer._gazeTracker.isVisible = false;
  93044. }
  93045. };
  93046. this._onNewGamepadConnected = function (gamepad) {
  93047. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93048. if (gamepad.leftStick) {
  93049. gamepad.onleftstickchanged(function (stickValues) {
  93050. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93051. // Listening to classic/xbox gamepad only if no VR controller is active
  93052. if ((!_this.leftController && !_this.rightController) ||
  93053. ((_this.leftController && !_this.leftController._activePointer) &&
  93054. (_this.rightController && !_this.rightController._activePointer))) {
  93055. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93056. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93057. }
  93058. }
  93059. });
  93060. }
  93061. if (gamepad.rightStick) {
  93062. gamepad.onrightstickchanged(function (stickValues) {
  93063. if (_this._teleportationInitialized) {
  93064. _this._checkRotate(stickValues, _this._cameraGazer);
  93065. }
  93066. });
  93067. }
  93068. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93069. gamepad.onbuttondown(function (buttonPressed) {
  93070. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93071. _this._cameraGazer._selectionPointerDown();
  93072. }
  93073. });
  93074. gamepad.onbuttonup(function (buttonPressed) {
  93075. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93076. _this._cameraGazer._selectionPointerUp();
  93077. }
  93078. });
  93079. }
  93080. }
  93081. else {
  93082. var webVRController = gamepad;
  93083. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93084. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93085. _this.rightController = controller;
  93086. }
  93087. else {
  93088. _this.leftController = controller;
  93089. }
  93090. _this._tryEnableInteractionOnController(controller);
  93091. }
  93092. };
  93093. // 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
  93094. this._tryEnableInteractionOnController = function (controller) {
  93095. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93096. _this._enableInteractionOnController(controller);
  93097. }
  93098. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93099. _this._enableTeleportationOnController(controller);
  93100. }
  93101. };
  93102. this._onNewGamepadDisconnected = function (gamepad) {
  93103. if (gamepad instanceof BABYLON.WebVRController) {
  93104. if (gamepad.hand === "left" && _this.leftController != null) {
  93105. _this.leftController.dispose();
  93106. _this.leftController = null;
  93107. }
  93108. if (gamepad.hand === "right" && _this.rightController != null) {
  93109. _this.rightController.dispose();
  93110. _this.rightController = null;
  93111. }
  93112. }
  93113. };
  93114. this._workingVector = BABYLON.Vector3.Zero();
  93115. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93116. this._workingMatrix = BABYLON.Matrix.Identity();
  93117. this._scene = scene;
  93118. this._canvas = scene.getEngine().getRenderingCanvas();
  93119. // Parse options
  93120. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93121. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93122. }
  93123. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93124. webVROptions.createDeviceOrientationCamera = true;
  93125. }
  93126. if (webVROptions.laserToggle === undefined) {
  93127. webVROptions.laserToggle = true;
  93128. }
  93129. if (webVROptions.defaultHeight === undefined) {
  93130. webVROptions.defaultHeight = 1.7;
  93131. }
  93132. if (webVROptions.useCustomVRButton) {
  93133. this._useCustomVRButton = true;
  93134. if (webVROptions.customVRButton) {
  93135. this._btnVR = webVROptions.customVRButton;
  93136. }
  93137. }
  93138. if (webVROptions.rayLength) {
  93139. this._rayLength = webVROptions.rayLength;
  93140. }
  93141. this._defaultHeight = webVROptions.defaultHeight;
  93142. if (webVROptions.positionScale) {
  93143. this._rayLength *= webVROptions.positionScale;
  93144. this._defaultHeight *= webVROptions.positionScale;
  93145. }
  93146. // Set position
  93147. if (this._scene.activeCamera) {
  93148. this._position = this._scene.activeCamera.position.clone();
  93149. }
  93150. else {
  93151. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93152. }
  93153. // Set non-vr camera
  93154. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93155. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93156. // Copy data from existing camera
  93157. if (this._scene.activeCamera) {
  93158. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93159. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93160. // Set rotation from previous camera
  93161. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93162. var targetCamera = this._scene.activeCamera;
  93163. if (targetCamera.rotationQuaternion) {
  93164. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93165. }
  93166. else {
  93167. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93168. }
  93169. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93170. }
  93171. }
  93172. this._scene.activeCamera = this._deviceOrientationCamera;
  93173. if (this._canvas) {
  93174. this._scene.activeCamera.attachControl(this._canvas);
  93175. }
  93176. }
  93177. else {
  93178. this._existingCamera = this._scene.activeCamera;
  93179. }
  93180. // Create VR cameras
  93181. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93182. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93183. }
  93184. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93185. this._webVRCamera.useStandingMatrix();
  93186. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93187. // Create default button
  93188. if (!this._useCustomVRButton) {
  93189. this._btnVR = document.createElement("BUTTON");
  93190. this._btnVR.className = "babylonVRicon";
  93191. this._btnVR.id = "babylonVRiconbtn";
  93192. this._btnVR.title = "Click to switch to VR";
  93193. 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) }";
  93194. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93195. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93196. // css += ".babylonVRicon.vrdisplaysupported { }";
  93197. // css += ".babylonVRicon.vrdisplayready { }";
  93198. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93199. var style = document.createElement('style');
  93200. style.appendChild(document.createTextNode(css));
  93201. document.getElementsByTagName('head')[0].appendChild(style);
  93202. this.moveButtonToBottomRight();
  93203. }
  93204. // VR button click event
  93205. if (this._btnVR) {
  93206. this._btnVR.addEventListener("click", function () {
  93207. if (!_this.isInVRMode) {
  93208. _this.enterVR();
  93209. }
  93210. else {
  93211. _this.exitVR();
  93212. }
  93213. });
  93214. }
  93215. // Window events
  93216. window.addEventListener("resize", this._onResize);
  93217. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93218. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93219. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93220. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93221. document.onmsfullscreenchange = this._onFullscreenChange;
  93222. // Display vr button when headset is connected
  93223. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93224. this.displayVRButton();
  93225. }
  93226. else {
  93227. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93228. if (e.vrDisplay) {
  93229. _this.displayVRButton();
  93230. }
  93231. });
  93232. }
  93233. // Exiting VR mode using 'ESC' key on desktop
  93234. this._onKeyDown = function (event) {
  93235. if (event.keyCode === 27 && _this.isInVRMode) {
  93236. _this.exitVR();
  93237. }
  93238. };
  93239. document.addEventListener("keydown", this._onKeyDown);
  93240. // Exiting VR mode double tapping the touch screen
  93241. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93242. if (_this.isInVRMode) {
  93243. _this.exitVR();
  93244. if (_this._fullscreenVRpresenting) {
  93245. _this._scene.getEngine().switchFullscreen(true);
  93246. }
  93247. }
  93248. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93249. // Listen for WebVR display changes
  93250. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93251. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93252. this._onVRRequestPresentStart = function () {
  93253. _this._webVRrequesting = true;
  93254. _this.updateButtonVisibility();
  93255. };
  93256. this._onVRRequestPresentComplete = function (success) {
  93257. _this._webVRrequesting = false;
  93258. _this.updateButtonVisibility();
  93259. };
  93260. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93261. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93262. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93263. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93264. scene.onDisposeObservable.add(function () {
  93265. _this.dispose();
  93266. });
  93267. // Gamepad connection events
  93268. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93269. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93270. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93271. this.updateButtonVisibility();
  93272. //create easing functions
  93273. this._circleEase = new BABYLON.CircleEase();
  93274. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93275. if (this.webVROptions.floorMeshes) {
  93276. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93277. }
  93278. }
  93279. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93280. /** Return this.onEnteringVRObservable
  93281. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93282. */
  93283. get: function () {
  93284. return this.onEnteringVRObservable;
  93285. },
  93286. enumerable: true,
  93287. configurable: true
  93288. });
  93289. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93290. /** Return this.onExitingVRObservable
  93291. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93292. */
  93293. get: function () {
  93294. return this.onExitingVRObservable;
  93295. },
  93296. enumerable: true,
  93297. configurable: true
  93298. });
  93299. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93300. /** Return this.onControllerMeshLoadedObservable
  93301. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93302. */
  93303. get: function () {
  93304. return this.onControllerMeshLoadedObservable;
  93305. },
  93306. enumerable: true,
  93307. configurable: true
  93308. });
  93309. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93310. /**
  93311. * The mesh used to display where the user is going to teleport.
  93312. */
  93313. get: function () {
  93314. return this._teleportationTarget;
  93315. },
  93316. /**
  93317. * Sets the mesh to be used to display where the user is going to teleport.
  93318. */
  93319. set: function (value) {
  93320. if (value) {
  93321. value.name = "teleportationTarget";
  93322. this._isDefaultTeleportationTarget = false;
  93323. this._teleportationTarget = value;
  93324. }
  93325. },
  93326. enumerable: true,
  93327. configurable: true
  93328. });
  93329. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93330. /**
  93331. * The mesh used to display where the user is selecting,
  93332. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93333. * See http://doc.babylonjs.com/resources/baking_transformations
  93334. */
  93335. get: function () {
  93336. return this._cameraGazer._gazeTracker;
  93337. },
  93338. set: function (value) {
  93339. if (value) {
  93340. this._cameraGazer._gazeTracker = value;
  93341. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93342. this._cameraGazer._gazeTracker.isPickable = false;
  93343. this._cameraGazer._gazeTracker.isVisible = false;
  93344. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93345. if (this.leftController) {
  93346. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93347. }
  93348. if (this.rightController) {
  93349. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93350. }
  93351. }
  93352. },
  93353. enumerable: true,
  93354. configurable: true
  93355. });
  93356. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93357. /**
  93358. * If the ray of the gaze should be displayed.
  93359. */
  93360. get: function () {
  93361. return this._displayGaze;
  93362. },
  93363. /**
  93364. * Sets if the ray of the gaze should be displayed.
  93365. */
  93366. set: function (value) {
  93367. this._displayGaze = value;
  93368. if (!value) {
  93369. this._cameraGazer._gazeTracker.isVisible = false;
  93370. if (this.leftController) {
  93371. this.leftController._gazeTracker.isVisible = false;
  93372. }
  93373. if (this.rightController) {
  93374. this.rightController._gazeTracker.isVisible = false;
  93375. }
  93376. }
  93377. },
  93378. enumerable: true,
  93379. configurable: true
  93380. });
  93381. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93382. /**
  93383. * If the ray of the LaserPointer should be displayed.
  93384. */
  93385. get: function () {
  93386. return this._displayLaserPointer;
  93387. },
  93388. /**
  93389. * Sets if the ray of the LaserPointer should be displayed.
  93390. */
  93391. set: function (value) {
  93392. this._displayLaserPointer = value;
  93393. if (!value) {
  93394. if (this.rightController) {
  93395. this.rightController._deactivatePointer();
  93396. this.rightController._gazeTracker.isVisible = false;
  93397. }
  93398. if (this.leftController) {
  93399. this.leftController._deactivatePointer();
  93400. this.leftController._gazeTracker.isVisible = false;
  93401. }
  93402. }
  93403. else {
  93404. if (this.rightController) {
  93405. this.rightController._activatePointer();
  93406. }
  93407. if (this.leftController) {
  93408. this.leftController._activatePointer();
  93409. }
  93410. }
  93411. },
  93412. enumerable: true,
  93413. configurable: true
  93414. });
  93415. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93416. /**
  93417. * The deviceOrientationCamera used as the camera when not in VR.
  93418. */
  93419. get: function () {
  93420. return this._deviceOrientationCamera;
  93421. },
  93422. enumerable: true,
  93423. configurable: true
  93424. });
  93425. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93426. /**
  93427. * Based on the current WebVR support, returns the current VR camera used.
  93428. */
  93429. get: function () {
  93430. if (this._webVRready) {
  93431. return this._webVRCamera;
  93432. }
  93433. else {
  93434. return this._scene.activeCamera;
  93435. }
  93436. },
  93437. enumerable: true,
  93438. configurable: true
  93439. });
  93440. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93441. /**
  93442. * The webVRCamera which is used when in VR.
  93443. */
  93444. get: function () {
  93445. return this._webVRCamera;
  93446. },
  93447. enumerable: true,
  93448. configurable: true
  93449. });
  93450. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93451. /**
  93452. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93453. */
  93454. get: function () {
  93455. return this._vrDeviceOrientationCamera;
  93456. },
  93457. enumerable: true,
  93458. configurable: true
  93459. });
  93460. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93461. get: function () {
  93462. var result = this._cameraGazer._teleportationRequestInitiated
  93463. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93464. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93465. return result;
  93466. },
  93467. enumerable: true,
  93468. configurable: true
  93469. });
  93470. // Raised when one of the controller has loaded successfully its associated default mesh
  93471. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93472. if (this.leftController && this.leftController.webVRController == webVRController) {
  93473. if (webVRController.mesh) {
  93474. this.leftController._setLaserPointerParent(webVRController.mesh);
  93475. }
  93476. }
  93477. if (this.rightController && this.rightController.webVRController == webVRController) {
  93478. if (webVRController.mesh) {
  93479. this.rightController._setLaserPointerParent(webVRController.mesh);
  93480. }
  93481. }
  93482. try {
  93483. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93484. }
  93485. catch (err) {
  93486. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93487. }
  93488. };
  93489. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93490. /**
  93491. * Gets a value indicating if we are currently in VR mode.
  93492. */
  93493. get: function () {
  93494. return this._webVRpresenting || this._fullscreenVRpresenting;
  93495. },
  93496. enumerable: true,
  93497. configurable: true
  93498. });
  93499. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93500. var vrDisplay = this._scene.getEngine().getVRDevice();
  93501. if (vrDisplay) {
  93502. var wasPresenting = this._webVRpresenting;
  93503. // A VR display is connected
  93504. this._webVRpresenting = vrDisplay.isPresenting;
  93505. if (wasPresenting && !this._webVRpresenting)
  93506. this.exitVR();
  93507. }
  93508. else {
  93509. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93510. }
  93511. this.updateButtonVisibility();
  93512. };
  93513. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93514. this._webVRsupported = eventArgs.vrSupported;
  93515. this._webVRready = !!eventArgs.vrDisplay;
  93516. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93517. this.updateButtonVisibility();
  93518. };
  93519. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93520. if (this._canvas && !this._useCustomVRButton) {
  93521. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93522. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93523. }
  93524. };
  93525. VRExperienceHelper.prototype.displayVRButton = function () {
  93526. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93527. document.body.appendChild(this._btnVR);
  93528. this._btnVRDisplayed = true;
  93529. }
  93530. };
  93531. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93532. if (!this._btnVR || this._useCustomVRButton) {
  93533. return;
  93534. }
  93535. this._btnVR.className = "babylonVRicon";
  93536. if (this.isInVRMode) {
  93537. this._btnVR.className += " vrdisplaypresenting";
  93538. }
  93539. else {
  93540. if (this._webVRready)
  93541. this._btnVR.className += " vrdisplayready";
  93542. if (this._webVRsupported)
  93543. this._btnVR.className += " vrdisplaysupported";
  93544. if (this._webVRrequesting)
  93545. this._btnVR.className += " vrdisplayrequesting";
  93546. }
  93547. };
  93548. /**
  93549. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93550. * Otherwise, will use the fullscreen API.
  93551. */
  93552. VRExperienceHelper.prototype.enterVR = function () {
  93553. if (this.onEnteringVRObservable) {
  93554. try {
  93555. this.onEnteringVRObservable.notifyObservers(this);
  93556. }
  93557. catch (err) {
  93558. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93559. }
  93560. }
  93561. if (this._scene.activeCamera) {
  93562. this._position = this._scene.activeCamera.position.clone();
  93563. // make sure that we return to the last active camera
  93564. this._existingCamera = this._scene.activeCamera;
  93565. }
  93566. if (this._webVRrequesting)
  93567. return;
  93568. // If WebVR is supported and a headset is connected
  93569. if (this._webVRready) {
  93570. if (!this._webVRpresenting) {
  93571. this._webVRCamera.position = this._position;
  93572. this._scene.activeCamera = this._webVRCamera;
  93573. }
  93574. }
  93575. else if (this._vrDeviceOrientationCamera) {
  93576. this._vrDeviceOrientationCamera.position = this._position;
  93577. if (this._scene.activeCamera) {
  93578. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93579. }
  93580. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93581. this._scene.getEngine().switchFullscreen(true);
  93582. this.updateButtonVisibility();
  93583. }
  93584. if (this._scene.activeCamera && this._canvas) {
  93585. this._scene.activeCamera.attachControl(this._canvas);
  93586. }
  93587. if (this._interactionsEnabled) {
  93588. this._scene.registerBeforeRender(this.beforeRender);
  93589. }
  93590. };
  93591. /**
  93592. * Attempt to exit VR, or fullscreen.
  93593. */
  93594. VRExperienceHelper.prototype.exitVR = function () {
  93595. if (this.onExitingVRObservable) {
  93596. try {
  93597. this.onExitingVRObservable.notifyObservers(this);
  93598. }
  93599. catch (err) {
  93600. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93601. }
  93602. }
  93603. if (this._webVRpresenting) {
  93604. this._scene.getEngine().disableVR();
  93605. }
  93606. if (this._scene.activeCamera) {
  93607. this._position = this._scene.activeCamera.position.clone();
  93608. }
  93609. if (this._deviceOrientationCamera) {
  93610. this._deviceOrientationCamera.position = this._position;
  93611. this._scene.activeCamera = this._deviceOrientationCamera;
  93612. if (this._canvas) {
  93613. this._scene.activeCamera.attachControl(this._canvas);
  93614. }
  93615. }
  93616. else if (this._existingCamera) {
  93617. this._existingCamera.position = this._position;
  93618. this._scene.activeCamera = this._existingCamera;
  93619. }
  93620. this.updateButtonVisibility();
  93621. if (this._interactionsEnabled) {
  93622. this._scene.unregisterBeforeRender(this.beforeRender);
  93623. }
  93624. // resize to update width and height when exiting vr exits fullscreen
  93625. this._scene.getEngine().resize();
  93626. };
  93627. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93628. /**
  93629. * The position of the vr experience helper.
  93630. */
  93631. get: function () {
  93632. return this._position;
  93633. },
  93634. /**
  93635. * Sets the position of the vr experience helper.
  93636. */
  93637. set: function (value) {
  93638. this._position = value;
  93639. if (this._scene.activeCamera) {
  93640. this._scene.activeCamera.position = value;
  93641. }
  93642. },
  93643. enumerable: true,
  93644. configurable: true
  93645. });
  93646. /**
  93647. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93648. */
  93649. VRExperienceHelper.prototype.enableInteractions = function () {
  93650. var _this = this;
  93651. if (!this._interactionsEnabled) {
  93652. this._interactionsRequested = true;
  93653. if (this.leftController) {
  93654. this._enableInteractionOnController(this.leftController);
  93655. }
  93656. if (this.rightController) {
  93657. this._enableInteractionOnController(this.rightController);
  93658. }
  93659. this.raySelectionPredicate = function (mesh) {
  93660. return mesh.isVisible && mesh.isPickable;
  93661. };
  93662. this.meshSelectionPredicate = function (mesh) {
  93663. return true;
  93664. };
  93665. this._raySelectionPredicate = function (mesh) {
  93666. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93667. && mesh.name.indexOf("teleportationTarget") === -1
  93668. && mesh.name.indexOf("torusTeleportation") === -1)) {
  93669. return _this.raySelectionPredicate(mesh);
  93670. }
  93671. return false;
  93672. };
  93673. this._interactionsEnabled = true;
  93674. }
  93675. };
  93676. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93677. get: function () {
  93678. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93679. },
  93680. enumerable: true,
  93681. configurable: true
  93682. });
  93683. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93684. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93685. if (this._floorMeshesCollection[i].id === mesh.id) {
  93686. return true;
  93687. }
  93688. }
  93689. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93690. return true;
  93691. }
  93692. return false;
  93693. };
  93694. /**
  93695. * Adds a floor mesh to be used for teleportation.
  93696. * @param floorMesh the mesh to be used for teleportation.
  93697. */
  93698. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93699. if (!this._floorMeshesCollection) {
  93700. return;
  93701. }
  93702. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93703. return;
  93704. }
  93705. this._floorMeshesCollection.push(floorMesh);
  93706. };
  93707. /**
  93708. * Removes a floor mesh from being used for teleportation.
  93709. * @param floorMesh the mesh to be removed.
  93710. */
  93711. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93712. if (!this._floorMeshesCollection) {
  93713. return;
  93714. }
  93715. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93716. if (meshIndex !== -1) {
  93717. this._floorMeshesCollection.splice(meshIndex, 1);
  93718. }
  93719. };
  93720. /**
  93721. * Enables interactions and teleportation using the VR controllers and gaze.
  93722. * @param vrTeleportationOptions options to modify teleportation behavior.
  93723. */
  93724. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93725. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93726. if (!this._teleportationInitialized) {
  93727. this._teleportationRequested = true;
  93728. this.enableInteractions();
  93729. if (vrTeleportationOptions.floorMeshName) {
  93730. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93731. }
  93732. if (vrTeleportationOptions.floorMeshes) {
  93733. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93734. }
  93735. if (this.leftController != null) {
  93736. this._enableTeleportationOnController(this.leftController);
  93737. }
  93738. if (this.rightController != null) {
  93739. this._enableTeleportationOnController(this.rightController);
  93740. }
  93741. // Creates an image processing post process for the vignette not relying
  93742. // on the main scene configuration for image processing to reduce setup and spaces
  93743. // (gamma/linear) conflicts.
  93744. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93745. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93746. imageProcessingConfiguration.vignetteEnabled = true;
  93747. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93748. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93749. this._teleportationInitialized = true;
  93750. if (this._isDefaultTeleportationTarget) {
  93751. this._createTeleportationCircles();
  93752. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93753. }
  93754. }
  93755. };
  93756. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93757. var _this = this;
  93758. var controllerMesh = controller.webVRController.mesh;
  93759. if (controllerMesh) {
  93760. controller._interactionsEnabled = true;
  93761. controller._activatePointer();
  93762. if (this.webVROptions.laserToggle) {
  93763. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93764. // Enabling / disabling laserPointer
  93765. if (_this._displayLaserPointer && stateObject.value === 1) {
  93766. if (controller._activePointer) {
  93767. controller._deactivatePointer();
  93768. }
  93769. else {
  93770. controller._activatePointer();
  93771. }
  93772. if (_this.displayGaze) {
  93773. controller._gazeTracker.isVisible = controller._activePointer;
  93774. }
  93775. }
  93776. });
  93777. }
  93778. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93779. var gazer = controller;
  93780. if (_this._noControllerIsActive) {
  93781. gazer = _this._cameraGazer;
  93782. }
  93783. if (!gazer._pointerDownOnMeshAsked) {
  93784. if (stateObject.value > _this._padSensibilityUp) {
  93785. gazer._selectionPointerDown();
  93786. }
  93787. }
  93788. else if (stateObject.value < _this._padSensibilityDown) {
  93789. gazer._selectionPointerUp();
  93790. }
  93791. });
  93792. }
  93793. };
  93794. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93795. // Dont teleport if another gaze already requested teleportation
  93796. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93797. return;
  93798. }
  93799. if (!gazer._teleportationRequestInitiated) {
  93800. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93801. gazer._activatePointer();
  93802. gazer._teleportationRequestInitiated = true;
  93803. }
  93804. }
  93805. else {
  93806. // Listening to the proper controller values changes to confirm teleportation
  93807. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93808. if (this._teleportActive) {
  93809. this._teleportCamera(this._haloCenter);
  93810. }
  93811. gazer._teleportationRequestInitiated = false;
  93812. }
  93813. }
  93814. };
  93815. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93816. // Only rotate when user is not currently selecting a teleportation location
  93817. if (gazer._teleportationRequestInitiated) {
  93818. return;
  93819. }
  93820. if (!gazer._rotationLeftAsked) {
  93821. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93822. gazer._rotationLeftAsked = true;
  93823. if (this._rotationAllowed) {
  93824. this._rotateCamera(false);
  93825. }
  93826. }
  93827. }
  93828. else {
  93829. if (stateObject.x > -this._padSensibilityDown) {
  93830. gazer._rotationLeftAsked = false;
  93831. }
  93832. }
  93833. if (!gazer._rotationRightAsked) {
  93834. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93835. gazer._rotationRightAsked = true;
  93836. if (this._rotationAllowed) {
  93837. this._rotateCamera(true);
  93838. }
  93839. }
  93840. }
  93841. else {
  93842. if (stateObject.x < this._padSensibilityDown) {
  93843. gazer._rotationRightAsked = false;
  93844. }
  93845. }
  93846. };
  93847. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93848. // Only teleport backwards when user is not currently selecting a teleportation location
  93849. if (gazer._teleportationRequestInitiated) {
  93850. return;
  93851. }
  93852. // Teleport backwards
  93853. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93854. if (!gazer._teleportationBackRequestInitiated) {
  93855. if (!this.currentVRCamera) {
  93856. return;
  93857. }
  93858. // Get rotation and position of the current camera
  93859. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93860. var position = this.currentVRCamera.position;
  93861. // If the camera has device position, use that instead
  93862. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93863. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93864. position = this.currentVRCamera.devicePosition;
  93865. }
  93866. // Get matrix with only the y rotation of the device rotation
  93867. rotation.toEulerAnglesToRef(this._workingVector);
  93868. this._workingVector.z = 0;
  93869. this._workingVector.x = 0;
  93870. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93871. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93872. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93873. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93874. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93875. var ray = new BABYLON.Ray(position, this._workingVector);
  93876. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93877. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93878. this._teleportCamera(hit.pickedPoint);
  93879. }
  93880. gazer._teleportationBackRequestInitiated = true;
  93881. }
  93882. }
  93883. else {
  93884. gazer._teleportationBackRequestInitiated = false;
  93885. }
  93886. };
  93887. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93888. var _this = this;
  93889. var controllerMesh = controller.webVRController.mesh;
  93890. if (controllerMesh) {
  93891. if (!controller._interactionsEnabled) {
  93892. this._enableInteractionOnController(controller);
  93893. }
  93894. controller._interactionsEnabled = true;
  93895. controller._teleportationEnabled = true;
  93896. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93897. controller._dpadPressed = false;
  93898. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93899. controller._dpadPressed = stateObject.pressed;
  93900. if (!controller._dpadPressed) {
  93901. controller._rotationLeftAsked = false;
  93902. controller._rotationRightAsked = false;
  93903. controller._teleportationBackRequestInitiated = false;
  93904. }
  93905. });
  93906. }
  93907. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93908. if (_this.teleportationEnabled) {
  93909. _this._checkTeleportBackwards(stateObject, controller);
  93910. _this._checkTeleportWithRay(stateObject, controller);
  93911. }
  93912. _this._checkRotate(stateObject, controller);
  93913. });
  93914. }
  93915. };
  93916. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93917. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93918. this._teleportationTarget.isPickable = false;
  93919. var length = 512;
  93920. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93921. dynamicTexture.hasAlpha = true;
  93922. var context = dynamicTexture.getContext();
  93923. var centerX = length / 2;
  93924. var centerY = length / 2;
  93925. var radius = 200;
  93926. context.beginPath();
  93927. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93928. context.fillStyle = this._teleportationFillColor;
  93929. context.fill();
  93930. context.lineWidth = 10;
  93931. context.strokeStyle = this._teleportationBorderColor;
  93932. context.stroke();
  93933. context.closePath();
  93934. dynamicTexture.update();
  93935. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93936. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93937. this._teleportationTarget.material = teleportationCircleMaterial;
  93938. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93939. torus.isPickable = false;
  93940. torus.parent = this._teleportationTarget;
  93941. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93942. var keys = [];
  93943. keys.push({
  93944. frame: 0,
  93945. value: 0
  93946. });
  93947. keys.push({
  93948. frame: 30,
  93949. value: 0.4
  93950. });
  93951. keys.push({
  93952. frame: 60,
  93953. value: 0
  93954. });
  93955. animationInnerCircle.setKeys(keys);
  93956. var easingFunction = new BABYLON.SineEase();
  93957. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93958. animationInnerCircle.setEasingFunction(easingFunction);
  93959. torus.animations = [];
  93960. torus.animations.push(animationInnerCircle);
  93961. this._scene.beginAnimation(torus, 0, 60, true);
  93962. this._hideTeleportationTarget();
  93963. };
  93964. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93965. this._teleportActive = true;
  93966. if (this._teleportationInitialized) {
  93967. this._teleportationTarget.isVisible = true;
  93968. if (this._isDefaultTeleportationTarget) {
  93969. this._teleportationTarget.getChildren()[0].isVisible = true;
  93970. }
  93971. }
  93972. };
  93973. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93974. this._teleportActive = false;
  93975. if (this._teleportationInitialized) {
  93976. this._teleportationTarget.isVisible = false;
  93977. if (this._isDefaultTeleportationTarget) {
  93978. this._teleportationTarget.getChildren()[0].isVisible = false;
  93979. }
  93980. }
  93981. };
  93982. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93983. var _this = this;
  93984. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93985. return;
  93986. }
  93987. if (right) {
  93988. this._rotationAngle++;
  93989. }
  93990. else {
  93991. this._rotationAngle--;
  93992. }
  93993. this.currentVRCamera.animations = [];
  93994. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93995. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93996. var animationRotationKeys = [];
  93997. animationRotationKeys.push({
  93998. frame: 0,
  93999. value: this.currentVRCamera.rotationQuaternion
  94000. });
  94001. animationRotationKeys.push({
  94002. frame: 6,
  94003. value: target
  94004. });
  94005. animationRotation.setKeys(animationRotationKeys);
  94006. animationRotation.setEasingFunction(this._circleEase);
  94007. this.currentVRCamera.animations.push(animationRotation);
  94008. this._postProcessMove.animations = [];
  94009. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94010. var vignetteWeightKeys = [];
  94011. vignetteWeightKeys.push({
  94012. frame: 0,
  94013. value: 0
  94014. });
  94015. vignetteWeightKeys.push({
  94016. frame: 3,
  94017. value: 4
  94018. });
  94019. vignetteWeightKeys.push({
  94020. frame: 6,
  94021. value: 0
  94022. });
  94023. animationPP.setKeys(vignetteWeightKeys);
  94024. animationPP.setEasingFunction(this._circleEase);
  94025. this._postProcessMove.animations.push(animationPP);
  94026. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94027. var vignetteStretchKeys = [];
  94028. vignetteStretchKeys.push({
  94029. frame: 0,
  94030. value: 0
  94031. });
  94032. vignetteStretchKeys.push({
  94033. frame: 3,
  94034. value: 10
  94035. });
  94036. vignetteStretchKeys.push({
  94037. frame: 6,
  94038. value: 0
  94039. });
  94040. animationPP2.setKeys(vignetteStretchKeys);
  94041. animationPP2.setEasingFunction(this._circleEase);
  94042. this._postProcessMove.animations.push(animationPP2);
  94043. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94044. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94045. this._postProcessMove.samples = 4;
  94046. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94047. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94048. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94049. });
  94050. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94051. };
  94052. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94053. if (hit.pickedPoint) {
  94054. if (gazer._teleportationRequestInitiated) {
  94055. this._displayTeleportationTarget();
  94056. this._haloCenter.copyFrom(hit.pickedPoint);
  94057. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94058. }
  94059. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94060. if (pickNormal) {
  94061. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94062. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94063. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94064. }
  94065. this._teleportationTarget.position.y += 0.1;
  94066. }
  94067. };
  94068. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94069. var _this = this;
  94070. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94071. return;
  94072. }
  94073. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94074. // offset of the headset from the anchor.
  94075. if (this.webVRCamera.leftCamera) {
  94076. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94077. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94078. location.subtractToRef(this._workingVector, this._workingVector);
  94079. }
  94080. else {
  94081. this._workingVector.copyFrom(location);
  94082. }
  94083. // Add height to account for user's height offset
  94084. if (this.isInVRMode) {
  94085. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94086. }
  94087. else {
  94088. this._workingVector.y += this._defaultHeight;
  94089. }
  94090. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94091. // Create animation from the camera's position to the new location
  94092. this.currentVRCamera.animations = [];
  94093. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94094. var animationCameraTeleportationKeys = [{
  94095. frame: 0,
  94096. value: this.currentVRCamera.position
  94097. },
  94098. {
  94099. frame: 11,
  94100. value: this._workingVector
  94101. }
  94102. ];
  94103. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94104. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94105. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94106. this._postProcessMove.animations = [];
  94107. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94108. var vignetteWeightKeys = [];
  94109. vignetteWeightKeys.push({
  94110. frame: 0,
  94111. value: 0
  94112. });
  94113. vignetteWeightKeys.push({
  94114. frame: 5,
  94115. value: 8
  94116. });
  94117. vignetteWeightKeys.push({
  94118. frame: 11,
  94119. value: 0
  94120. });
  94121. animationPP.setKeys(vignetteWeightKeys);
  94122. this._postProcessMove.animations.push(animationPP);
  94123. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94124. var vignetteStretchKeys = [];
  94125. vignetteStretchKeys.push({
  94126. frame: 0,
  94127. value: 0
  94128. });
  94129. vignetteStretchKeys.push({
  94130. frame: 5,
  94131. value: 10
  94132. });
  94133. vignetteStretchKeys.push({
  94134. frame: 11,
  94135. value: 0
  94136. });
  94137. animationPP2.setKeys(vignetteStretchKeys);
  94138. this._postProcessMove.animations.push(animationPP2);
  94139. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94140. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94141. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94142. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94143. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94144. });
  94145. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94146. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94147. });
  94148. this._hideTeleportationTarget();
  94149. };
  94150. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94151. if (normal) {
  94152. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94153. if (angle < Math.PI / 2) {
  94154. normal.scaleInPlace(-1);
  94155. }
  94156. }
  94157. return normal;
  94158. };
  94159. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94160. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94161. return;
  94162. }
  94163. var ray = gazer._getForwardRay(this._rayLength);
  94164. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94165. if (hit) {
  94166. // Populate the contrllers mesh that can be used for drag/drop
  94167. if (gazer._laserPointer) {
  94168. hit.originMesh = gazer._laserPointer.parent;
  94169. }
  94170. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94171. }
  94172. gazer._currentHit = hit;
  94173. // Moving the gazeTracker on the mesh face targetted
  94174. if (hit && hit.pickedPoint) {
  94175. if (this._displayGaze) {
  94176. var multiplier = 1;
  94177. gazer._gazeTracker.isVisible = true;
  94178. if (gazer._isActionableMesh) {
  94179. multiplier = 3;
  94180. }
  94181. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94182. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94183. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94184. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94185. // To avoid z-fighting
  94186. var deltaFighting = 0.002;
  94187. if (pickNormal) {
  94188. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94189. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94190. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94191. }
  94192. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94193. if (gazer._gazeTracker.position.x < 0) {
  94194. gazer._gazeTracker.position.x += deltaFighting;
  94195. }
  94196. else {
  94197. gazer._gazeTracker.position.x -= deltaFighting;
  94198. }
  94199. if (gazer._gazeTracker.position.y < 0) {
  94200. gazer._gazeTracker.position.y += deltaFighting;
  94201. }
  94202. else {
  94203. gazer._gazeTracker.position.y -= deltaFighting;
  94204. }
  94205. if (gazer._gazeTracker.position.z < 0) {
  94206. gazer._gazeTracker.position.z += deltaFighting;
  94207. }
  94208. else {
  94209. gazer._gazeTracker.position.z -= deltaFighting;
  94210. }
  94211. }
  94212. // Changing the size of the laser pointer based on the distance from the targetted point
  94213. gazer._updatePointerDistance(hit.distance);
  94214. }
  94215. else {
  94216. gazer._updatePointerDistance();
  94217. gazer._gazeTracker.isVisible = false;
  94218. }
  94219. if (hit && hit.pickedMesh) {
  94220. // The object selected is the floor, we're in a teleportation scenario
  94221. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94222. // Moving the teleportation area to this targetted point
  94223. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94224. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94225. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94226. }
  94227. gazer._currentMeshSelected = null;
  94228. if (gazer._teleportationRequestInitiated) {
  94229. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94230. }
  94231. return;
  94232. }
  94233. // If not, we're in a selection scenario
  94234. //this._teleportationAllowed = false;
  94235. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94236. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94237. this.onNewMeshPicked.notifyObservers(hit);
  94238. gazer._currentMeshSelected = hit.pickedMesh;
  94239. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94240. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94241. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94242. gazer._isActionableMesh = true;
  94243. }
  94244. else {
  94245. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94246. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94247. gazer._isActionableMesh = false;
  94248. }
  94249. try {
  94250. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94251. }
  94252. catch (err) {
  94253. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94254. }
  94255. }
  94256. else {
  94257. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94258. gazer._currentMeshSelected = null;
  94259. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94260. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94261. }
  94262. }
  94263. }
  94264. else {
  94265. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94266. gazer._currentMeshSelected = null;
  94267. //this._teleportationAllowed = false;
  94268. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94269. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94270. }
  94271. };
  94272. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94273. if (mesh) {
  94274. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94275. }
  94276. };
  94277. /**
  94278. * Sets the color of the laser ray from the vr controllers.
  94279. * @param color new color for the ray.
  94280. */
  94281. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94282. if (this.leftController) {
  94283. this.leftController._setLaserPointerColor(color);
  94284. }
  94285. if (this.rightController) {
  94286. this.rightController._setLaserPointerColor(color);
  94287. }
  94288. };
  94289. /**
  94290. * Sets the color of the ray from the vr headsets gaze.
  94291. * @param color new color for the ray.
  94292. */
  94293. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94294. if (!this._cameraGazer._gazeTracker.material) {
  94295. return;
  94296. }
  94297. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94298. if (this.leftController) {
  94299. this.leftController._gazeTracker.material.emissiveColor = color;
  94300. }
  94301. if (this.rightController) {
  94302. this.rightController._gazeTracker.material.emissiveColor = color;
  94303. }
  94304. };
  94305. /**
  94306. * Exits VR and disposes of the vr experience helper
  94307. */
  94308. VRExperienceHelper.prototype.dispose = function () {
  94309. if (this.isInVRMode) {
  94310. this.exitVR();
  94311. }
  94312. if (this._postProcessMove) {
  94313. this._postProcessMove.dispose();
  94314. }
  94315. if (this._webVRCamera) {
  94316. this._webVRCamera.dispose();
  94317. }
  94318. if (this._vrDeviceOrientationCamera) {
  94319. this._vrDeviceOrientationCamera.dispose();
  94320. }
  94321. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94322. document.body.removeChild(this._btnVR);
  94323. }
  94324. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94325. this._deviceOrientationCamera.dispose();
  94326. }
  94327. if (this._cameraGazer) {
  94328. this._cameraGazer.dispose();
  94329. }
  94330. if (this.leftController) {
  94331. this.leftController.dispose();
  94332. }
  94333. if (this.rightController) {
  94334. this.rightController.dispose();
  94335. }
  94336. if (this._teleportationTarget) {
  94337. this._teleportationTarget.dispose();
  94338. }
  94339. this._floorMeshesCollection = [];
  94340. document.removeEventListener("keydown", this._onKeyDown);
  94341. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94342. window.removeEventListener("resize", this._onResize);
  94343. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94344. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94345. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94346. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94347. document.onmsfullscreenchange = null;
  94348. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94349. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94350. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94351. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94352. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94353. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94354. this._scene.unregisterBeforeRender(this.beforeRender);
  94355. };
  94356. /**
  94357. * Gets the name of the VRExperienceHelper class
  94358. * @returns "VRExperienceHelper"
  94359. */
  94360. VRExperienceHelper.prototype.getClassName = function () {
  94361. return "VRExperienceHelper";
  94362. };
  94363. return VRExperienceHelper;
  94364. }());
  94365. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94366. })(BABYLON || (BABYLON = {}));
  94367. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94368. // Mainly based on these 2 articles :
  94369. // 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
  94370. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94371. var BABYLON;
  94372. (function (BABYLON) {
  94373. /**
  94374. * Defines the potential axis of a Joystick
  94375. */
  94376. var JoystickAxis;
  94377. (function (JoystickAxis) {
  94378. /** X axis */
  94379. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94380. /** Y axis */
  94381. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94382. /** Z axis */
  94383. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94384. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94385. /**
  94386. * Class used to define virtual joystick (used in touch mode)
  94387. */
  94388. var VirtualJoystick = /** @class */ (function () {
  94389. /**
  94390. * Creates a new virtual joystick
  94391. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94392. */
  94393. function VirtualJoystick(leftJoystick) {
  94394. var _this = this;
  94395. if (leftJoystick) {
  94396. this._leftJoystick = true;
  94397. }
  94398. else {
  94399. this._leftJoystick = false;
  94400. }
  94401. VirtualJoystick._globalJoystickIndex++;
  94402. // By default left & right arrow keys are moving the X
  94403. // and up & down keys are moving the Y
  94404. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94405. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94406. this.reverseLeftRight = false;
  94407. this.reverseUpDown = false;
  94408. // collections of pointers
  94409. this._touches = new BABYLON.StringDictionary();
  94410. this.deltaPosition = BABYLON.Vector3.Zero();
  94411. this._joystickSensibility = 25;
  94412. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94413. this._onResize = function (evt) {
  94414. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94415. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94416. if (VirtualJoystick.vjCanvas) {
  94417. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94418. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94419. }
  94420. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94421. };
  94422. // injecting a canvas element on top of the canvas 3D game
  94423. if (!VirtualJoystick.vjCanvas) {
  94424. window.addEventListener("resize", this._onResize, false);
  94425. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94426. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94427. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94428. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94429. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94430. VirtualJoystick.vjCanvas.style.width = "100%";
  94431. VirtualJoystick.vjCanvas.style.height = "100%";
  94432. VirtualJoystick.vjCanvas.style.position = "absolute";
  94433. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94434. VirtualJoystick.vjCanvas.style.top = "0px";
  94435. VirtualJoystick.vjCanvas.style.left = "0px";
  94436. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94437. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94438. // Support for jQuery PEP polyfill
  94439. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94440. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94441. if (!context) {
  94442. throw new Error("Unable to create canvas for virtual joystick");
  94443. }
  94444. VirtualJoystick.vjCanvasContext = context;
  94445. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94446. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94447. document.body.appendChild(VirtualJoystick.vjCanvas);
  94448. }
  94449. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94450. this.pressed = false;
  94451. // default joystick color
  94452. this._joystickColor = "cyan";
  94453. this._joystickPointerID = -1;
  94454. // current joystick position
  94455. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94456. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94457. // origin joystick position
  94458. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94459. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94460. this._onPointerDownHandlerRef = function (evt) {
  94461. _this._onPointerDown(evt);
  94462. };
  94463. this._onPointerMoveHandlerRef = function (evt) {
  94464. _this._onPointerMove(evt);
  94465. };
  94466. this._onPointerUpHandlerRef = function (evt) {
  94467. _this._onPointerUp(evt);
  94468. };
  94469. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94470. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94471. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94472. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94473. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94474. evt.preventDefault(); // Disables system menu
  94475. }, false);
  94476. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94477. }
  94478. /**
  94479. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94480. * @param newJoystickSensibility defines the new sensibility
  94481. */
  94482. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94483. this._joystickSensibility = newJoystickSensibility;
  94484. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94485. };
  94486. VirtualJoystick.prototype._onPointerDown = function (e) {
  94487. var positionOnScreenCondition;
  94488. e.preventDefault();
  94489. if (this._leftJoystick === true) {
  94490. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94491. }
  94492. else {
  94493. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94494. }
  94495. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94496. // First contact will be dedicated to the virtual joystick
  94497. this._joystickPointerID = e.pointerId;
  94498. this._joystickPointerStartPos.x = e.clientX;
  94499. this._joystickPointerStartPos.y = e.clientY;
  94500. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94501. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94502. this._deltaJoystickVector.x = 0;
  94503. this._deltaJoystickVector.y = 0;
  94504. this.pressed = true;
  94505. this._touches.add(e.pointerId.toString(), e);
  94506. }
  94507. else {
  94508. // You can only trigger the action buttons with a joystick declared
  94509. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94510. this._action();
  94511. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94512. }
  94513. }
  94514. };
  94515. VirtualJoystick.prototype._onPointerMove = function (e) {
  94516. // If the current pointer is the one associated to the joystick (first touch contact)
  94517. if (this._joystickPointerID == e.pointerId) {
  94518. this._joystickPointerPos.x = e.clientX;
  94519. this._joystickPointerPos.y = e.clientY;
  94520. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94521. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94522. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94523. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94524. switch (this._axisTargetedByLeftAndRight) {
  94525. case JoystickAxis.X:
  94526. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94527. break;
  94528. case JoystickAxis.Y:
  94529. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94530. break;
  94531. case JoystickAxis.Z:
  94532. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94533. break;
  94534. }
  94535. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94536. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94537. switch (this._axisTargetedByUpAndDown) {
  94538. case JoystickAxis.X:
  94539. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94540. break;
  94541. case JoystickAxis.Y:
  94542. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94543. break;
  94544. case JoystickAxis.Z:
  94545. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94546. break;
  94547. }
  94548. }
  94549. else {
  94550. var data = this._touches.get(e.pointerId.toString());
  94551. if (data) {
  94552. data.x = e.clientX;
  94553. data.y = e.clientY;
  94554. }
  94555. }
  94556. };
  94557. VirtualJoystick.prototype._onPointerUp = function (e) {
  94558. if (this._joystickPointerID == e.pointerId) {
  94559. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94560. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94561. this._joystickPointerID = -1;
  94562. this.pressed = false;
  94563. }
  94564. else {
  94565. var touch = this._touches.get(e.pointerId.toString());
  94566. if (touch) {
  94567. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94568. }
  94569. }
  94570. this._deltaJoystickVector.x = 0;
  94571. this._deltaJoystickVector.y = 0;
  94572. this._touches.remove(e.pointerId.toString());
  94573. };
  94574. /**
  94575. * Change the color of the virtual joystick
  94576. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94577. */
  94578. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94579. this._joystickColor = newColor;
  94580. };
  94581. /**
  94582. * Defines a callback to call when the joystick is touched
  94583. * @param action defines the callback
  94584. */
  94585. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94586. this._action = action;
  94587. };
  94588. /**
  94589. * Defines which axis you'd like to control for left & right
  94590. * @param axis defines the axis to use
  94591. */
  94592. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94593. switch (axis) {
  94594. case JoystickAxis.X:
  94595. case JoystickAxis.Y:
  94596. case JoystickAxis.Z:
  94597. this._axisTargetedByLeftAndRight = axis;
  94598. break;
  94599. default:
  94600. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94601. break;
  94602. }
  94603. };
  94604. /**
  94605. * Defines which axis you'd like to control for up & down
  94606. * @param axis defines the axis to use
  94607. */
  94608. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94609. switch (axis) {
  94610. case JoystickAxis.X:
  94611. case JoystickAxis.Y:
  94612. case JoystickAxis.Z:
  94613. this._axisTargetedByUpAndDown = axis;
  94614. break;
  94615. default:
  94616. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94617. break;
  94618. }
  94619. };
  94620. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94621. var _this = this;
  94622. if (this.pressed) {
  94623. this._touches.forEach(function (key, touch) {
  94624. if (touch.pointerId === _this._joystickPointerID) {
  94625. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94626. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94627. VirtualJoystick.vjCanvasContext.beginPath();
  94628. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94629. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94630. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94631. VirtualJoystick.vjCanvasContext.stroke();
  94632. VirtualJoystick.vjCanvasContext.closePath();
  94633. VirtualJoystick.vjCanvasContext.beginPath();
  94634. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94635. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94636. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94637. VirtualJoystick.vjCanvasContext.stroke();
  94638. VirtualJoystick.vjCanvasContext.closePath();
  94639. VirtualJoystick.vjCanvasContext.beginPath();
  94640. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94641. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94642. VirtualJoystick.vjCanvasContext.stroke();
  94643. VirtualJoystick.vjCanvasContext.closePath();
  94644. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94645. }
  94646. else {
  94647. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94648. VirtualJoystick.vjCanvasContext.beginPath();
  94649. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94650. VirtualJoystick.vjCanvasContext.beginPath();
  94651. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94652. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94653. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94654. VirtualJoystick.vjCanvasContext.stroke();
  94655. VirtualJoystick.vjCanvasContext.closePath();
  94656. touch.prevX = touch.x;
  94657. touch.prevY = touch.y;
  94658. }
  94659. ;
  94660. });
  94661. }
  94662. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94663. };
  94664. /**
  94665. * Release internal HTML canvas
  94666. */
  94667. VirtualJoystick.prototype.releaseCanvas = function () {
  94668. if (VirtualJoystick.vjCanvas) {
  94669. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94670. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94671. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94672. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94673. window.removeEventListener("resize", this._onResize);
  94674. document.body.removeChild(VirtualJoystick.vjCanvas);
  94675. VirtualJoystick.vjCanvas = null;
  94676. }
  94677. };
  94678. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94679. VirtualJoystick._globalJoystickIndex = 0;
  94680. return VirtualJoystick;
  94681. }());
  94682. BABYLON.VirtualJoystick = VirtualJoystick;
  94683. })(BABYLON || (BABYLON = {}));
  94684. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94685. var BABYLON;
  94686. (function (BABYLON) {
  94687. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94688. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94689. });
  94690. // We're mainly based on the logic defined into the FreeCamera code
  94691. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94692. __extends(VirtualJoysticksCamera, _super);
  94693. function VirtualJoysticksCamera(name, position, scene) {
  94694. var _this = _super.call(this, name, position, scene) || this;
  94695. _this.inputs.addVirtualJoystick();
  94696. return _this;
  94697. }
  94698. VirtualJoysticksCamera.prototype.getClassName = function () {
  94699. return "VirtualJoysticksCamera";
  94700. };
  94701. return VirtualJoysticksCamera;
  94702. }(BABYLON.FreeCamera));
  94703. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94704. })(BABYLON || (BABYLON = {}));
  94705. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94706. var BABYLON;
  94707. (function (BABYLON) {
  94708. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94709. function FreeCameraVirtualJoystickInput() {
  94710. }
  94711. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94712. return this._leftjoystick;
  94713. };
  94714. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94715. return this._rightjoystick;
  94716. };
  94717. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94718. if (this._leftjoystick) {
  94719. var camera = this.camera;
  94720. var speed = camera._computeLocalCameraSpeed() * 50;
  94721. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94722. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94723. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94724. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94725. if (!this._leftjoystick.pressed) {
  94726. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94727. }
  94728. if (!this._rightjoystick.pressed) {
  94729. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94730. }
  94731. }
  94732. };
  94733. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94734. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94735. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94736. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94737. this._leftjoystick.setJoystickSensibility(0.15);
  94738. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94739. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94740. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94741. this._rightjoystick.reverseUpDown = true;
  94742. this._rightjoystick.setJoystickSensibility(0.05);
  94743. this._rightjoystick.setJoystickColor("yellow");
  94744. };
  94745. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94746. this._leftjoystick.releaseCanvas();
  94747. this._rightjoystick.releaseCanvas();
  94748. };
  94749. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94750. return "FreeCameraVirtualJoystickInput";
  94751. };
  94752. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94753. return "virtualJoystick";
  94754. };
  94755. return FreeCameraVirtualJoystickInput;
  94756. }());
  94757. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94758. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94759. })(BABYLON || (BABYLON = {}));
  94760. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94761. var BABYLON;
  94762. (function (BABYLON) {
  94763. var SimplificationSettings = /** @class */ (function () {
  94764. function SimplificationSettings(quality, distance, optimizeMesh) {
  94765. this.quality = quality;
  94766. this.distance = distance;
  94767. this.optimizeMesh = optimizeMesh;
  94768. }
  94769. return SimplificationSettings;
  94770. }());
  94771. BABYLON.SimplificationSettings = SimplificationSettings;
  94772. var SimplificationQueue = /** @class */ (function () {
  94773. function SimplificationQueue() {
  94774. this.running = false;
  94775. this._simplificationArray = [];
  94776. }
  94777. SimplificationQueue.prototype.addTask = function (task) {
  94778. this._simplificationArray.push(task);
  94779. };
  94780. SimplificationQueue.prototype.executeNext = function () {
  94781. var task = this._simplificationArray.pop();
  94782. if (task) {
  94783. this.running = true;
  94784. this.runSimplification(task);
  94785. }
  94786. else {
  94787. this.running = false;
  94788. }
  94789. };
  94790. SimplificationQueue.prototype.runSimplification = function (task) {
  94791. var _this = this;
  94792. if (task.parallelProcessing) {
  94793. //parallel simplifier
  94794. task.settings.forEach(function (setting) {
  94795. var simplifier = _this.getSimplifier(task);
  94796. simplifier.simplify(setting, function (newMesh) {
  94797. task.mesh.addLODLevel(setting.distance, newMesh);
  94798. newMesh.isVisible = true;
  94799. //check if it is the last
  94800. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94801. //all done, run the success callback.
  94802. task.successCallback();
  94803. }
  94804. _this.executeNext();
  94805. });
  94806. });
  94807. }
  94808. else {
  94809. //single simplifier.
  94810. var simplifier = this.getSimplifier(task);
  94811. var runDecimation = function (setting, callback) {
  94812. simplifier.simplify(setting, function (newMesh) {
  94813. task.mesh.addLODLevel(setting.distance, newMesh);
  94814. newMesh.isVisible = true;
  94815. //run the next quality level
  94816. callback();
  94817. });
  94818. };
  94819. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94820. runDecimation(task.settings[loop.index], function () {
  94821. loop.executeNext();
  94822. });
  94823. }, function () {
  94824. //execution ended, run the success callback.
  94825. if (task.successCallback) {
  94826. task.successCallback();
  94827. }
  94828. _this.executeNext();
  94829. });
  94830. }
  94831. };
  94832. SimplificationQueue.prototype.getSimplifier = function (task) {
  94833. switch (task.simplificationType) {
  94834. case SimplificationType.QUADRATIC:
  94835. default:
  94836. return new QuadraticErrorSimplification(task.mesh);
  94837. }
  94838. };
  94839. return SimplificationQueue;
  94840. }());
  94841. BABYLON.SimplificationQueue = SimplificationQueue;
  94842. /**
  94843. * The implemented types of simplification
  94844. * At the moment only Quadratic Error Decimation is implemented
  94845. */
  94846. var SimplificationType;
  94847. (function (SimplificationType) {
  94848. /** Quadratic error decimation */
  94849. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94850. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94851. var DecimationTriangle = /** @class */ (function () {
  94852. function DecimationTriangle(vertices) {
  94853. this.vertices = vertices;
  94854. this.error = new Array(4);
  94855. this.deleted = false;
  94856. this.isDirty = false;
  94857. this.deletePending = false;
  94858. this.borderFactor = 0;
  94859. }
  94860. return DecimationTriangle;
  94861. }());
  94862. BABYLON.DecimationTriangle = DecimationTriangle;
  94863. var DecimationVertex = /** @class */ (function () {
  94864. function DecimationVertex(position, id) {
  94865. this.position = position;
  94866. this.id = id;
  94867. this.isBorder = true;
  94868. this.q = new QuadraticMatrix();
  94869. this.triangleCount = 0;
  94870. this.triangleStart = 0;
  94871. this.originalOffsets = [];
  94872. }
  94873. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94874. this.position.copyFrom(newPosition);
  94875. };
  94876. return DecimationVertex;
  94877. }());
  94878. BABYLON.DecimationVertex = DecimationVertex;
  94879. var QuadraticMatrix = /** @class */ (function () {
  94880. function QuadraticMatrix(data) {
  94881. this.data = new Array(10);
  94882. for (var i = 0; i < 10; ++i) {
  94883. if (data && data[i]) {
  94884. this.data[i] = data[i];
  94885. }
  94886. else {
  94887. this.data[i] = 0;
  94888. }
  94889. }
  94890. }
  94891. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94892. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94893. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94894. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94895. return det;
  94896. };
  94897. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94898. for (var i = 0; i < 10; ++i) {
  94899. this.data[i] += matrix.data[i];
  94900. }
  94901. };
  94902. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94903. for (var i = 0; i < 10; ++i) {
  94904. this.data[i] += data[i];
  94905. }
  94906. };
  94907. QuadraticMatrix.prototype.add = function (matrix) {
  94908. var m = new QuadraticMatrix();
  94909. for (var i = 0; i < 10; ++i) {
  94910. m.data[i] = this.data[i] + matrix.data[i];
  94911. }
  94912. return m;
  94913. };
  94914. QuadraticMatrix.FromData = function (a, b, c, d) {
  94915. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94916. };
  94917. //returning an array to avoid garbage collection
  94918. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94919. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94920. };
  94921. return QuadraticMatrix;
  94922. }());
  94923. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94924. var Reference = /** @class */ (function () {
  94925. function Reference(vertexId, triangleId) {
  94926. this.vertexId = vertexId;
  94927. this.triangleId = triangleId;
  94928. }
  94929. return Reference;
  94930. }());
  94931. BABYLON.Reference = Reference;
  94932. /**
  94933. * An implementation of the Quadratic Error simplification algorithm.
  94934. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94935. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94936. * @author RaananW
  94937. */
  94938. var QuadraticErrorSimplification = /** @class */ (function () {
  94939. function QuadraticErrorSimplification(_mesh) {
  94940. this._mesh = _mesh;
  94941. this.syncIterations = 5000;
  94942. this.aggressiveness = 7;
  94943. this.decimationIterations = 100;
  94944. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94945. }
  94946. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94947. var _this = this;
  94948. this.initDecimatedMesh();
  94949. //iterating through the submeshes array, one after the other.
  94950. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94951. _this.initWithMesh(loop.index, function () {
  94952. _this.runDecimation(settings, loop.index, function () {
  94953. loop.executeNext();
  94954. });
  94955. }, settings.optimizeMesh);
  94956. }, function () {
  94957. setTimeout(function () {
  94958. successCallback(_this._reconstructedMesh);
  94959. }, 0);
  94960. });
  94961. };
  94962. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94963. var _this = this;
  94964. var targetCount = ~~(this.triangles.length * settings.quality);
  94965. var deletedTriangles = 0;
  94966. var triangleCount = this.triangles.length;
  94967. var iterationFunction = function (iteration, callback) {
  94968. setTimeout(function () {
  94969. if (iteration % 5 === 0) {
  94970. _this.updateMesh(iteration === 0);
  94971. }
  94972. for (var i = 0; i < _this.triangles.length; ++i) {
  94973. _this.triangles[i].isDirty = false;
  94974. }
  94975. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94976. var trianglesIterator = function (i) {
  94977. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94978. var t = _this.triangles[tIdx];
  94979. if (!t)
  94980. return;
  94981. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94982. return;
  94983. }
  94984. for (var j = 0; j < 3; ++j) {
  94985. if (t.error[j] < threshold) {
  94986. var deleted0 = [];
  94987. var deleted1 = [];
  94988. var v0 = t.vertices[j];
  94989. var v1 = t.vertices[(j + 1) % 3];
  94990. if (v0.isBorder || v1.isBorder)
  94991. continue;
  94992. var p = BABYLON.Vector3.Zero();
  94993. var n = BABYLON.Vector3.Zero();
  94994. var uv = BABYLON.Vector2.Zero();
  94995. var color = new BABYLON.Color4(0, 0, 0, 1);
  94996. _this.calculateError(v0, v1, p, n, uv, color);
  94997. var delTr = new Array();
  94998. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94999. continue;
  95000. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95001. continue;
  95002. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95003. continue;
  95004. var uniqueArray = new Array();
  95005. delTr.forEach(function (deletedT) {
  95006. if (uniqueArray.indexOf(deletedT) === -1) {
  95007. deletedT.deletePending = true;
  95008. uniqueArray.push(deletedT);
  95009. }
  95010. });
  95011. if (uniqueArray.length % 2 !== 0) {
  95012. continue;
  95013. }
  95014. v0.q = v1.q.add(v0.q);
  95015. v0.updatePosition(p);
  95016. var tStart = _this.references.length;
  95017. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95018. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95019. var tCount = _this.references.length - tStart;
  95020. if (tCount <= v0.triangleCount) {
  95021. if (tCount) {
  95022. for (var c = 0; c < tCount; c++) {
  95023. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95024. }
  95025. }
  95026. }
  95027. else {
  95028. v0.triangleStart = tStart;
  95029. }
  95030. v0.triangleCount = tCount;
  95031. break;
  95032. }
  95033. }
  95034. };
  95035. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95036. }, 0);
  95037. };
  95038. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95039. if (triangleCount - deletedTriangles <= targetCount)
  95040. loop.breakLoop();
  95041. else {
  95042. iterationFunction(loop.index, function () {
  95043. loop.executeNext();
  95044. });
  95045. }
  95046. }, function () {
  95047. setTimeout(function () {
  95048. //reconstruct this part of the mesh
  95049. _this.reconstructMesh(submeshIndex);
  95050. successCallback();
  95051. }, 0);
  95052. });
  95053. };
  95054. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95055. var _this = this;
  95056. this.vertices = [];
  95057. this.triangles = [];
  95058. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95059. var indices = this._mesh.getIndices();
  95060. var submesh = this._mesh.subMeshes[submeshIndex];
  95061. var findInVertices = function (positionToSearch) {
  95062. if (optimizeMesh) {
  95063. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95064. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95065. return _this.vertices[ii];
  95066. }
  95067. }
  95068. }
  95069. return null;
  95070. };
  95071. var vertexReferences = [];
  95072. var vertexInit = function (i) {
  95073. if (!positionData) {
  95074. return;
  95075. }
  95076. var offset = i + submesh.verticesStart;
  95077. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95078. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95079. vertex.originalOffsets.push(offset);
  95080. if (vertex.id === _this.vertices.length) {
  95081. _this.vertices.push(vertex);
  95082. }
  95083. vertexReferences.push(vertex.id);
  95084. };
  95085. //var totalVertices = mesh.getTotalVertices();
  95086. var totalVertices = submesh.verticesCount;
  95087. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95088. var indicesInit = function (i) {
  95089. if (!indices) {
  95090. return;
  95091. }
  95092. var offset = (submesh.indexStart / 3) + i;
  95093. var pos = (offset * 3);
  95094. var i0 = indices[pos + 0];
  95095. var i1 = indices[pos + 1];
  95096. var i2 = indices[pos + 2];
  95097. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95098. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95099. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95100. var triangle = new DecimationTriangle([v0, v1, v2]);
  95101. triangle.originalOffset = pos;
  95102. _this.triangles.push(triangle);
  95103. };
  95104. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95105. _this.init(callback);
  95106. });
  95107. });
  95108. };
  95109. QuadraticErrorSimplification.prototype.init = function (callback) {
  95110. var _this = this;
  95111. var triangleInit1 = function (i) {
  95112. var t = _this.triangles[i];
  95113. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95114. for (var j = 0; j < 3; j++) {
  95115. 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))));
  95116. }
  95117. };
  95118. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95119. var triangleInit2 = function (i) {
  95120. var t = _this.triangles[i];
  95121. for (var j = 0; j < 3; ++j) {
  95122. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95123. }
  95124. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95125. };
  95126. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95127. callback();
  95128. });
  95129. });
  95130. };
  95131. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95132. var newTriangles = [];
  95133. var i;
  95134. for (i = 0; i < this.vertices.length; ++i) {
  95135. this.vertices[i].triangleCount = 0;
  95136. }
  95137. var t;
  95138. var j;
  95139. for (i = 0; i < this.triangles.length; ++i) {
  95140. if (!this.triangles[i].deleted) {
  95141. t = this.triangles[i];
  95142. for (j = 0; j < 3; ++j) {
  95143. t.vertices[j].triangleCount = 1;
  95144. }
  95145. newTriangles.push(t);
  95146. }
  95147. }
  95148. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95149. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95150. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95151. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95152. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95153. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95154. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95155. var vertexCount = 0;
  95156. for (i = 0; i < this.vertices.length; ++i) {
  95157. var vertex = this.vertices[i];
  95158. vertex.id = vertexCount;
  95159. if (vertex.triangleCount) {
  95160. vertex.originalOffsets.forEach(function (originalOffset) {
  95161. if (!normalData) {
  95162. return;
  95163. }
  95164. newPositionData.push(vertex.position.x);
  95165. newPositionData.push(vertex.position.y);
  95166. newPositionData.push(vertex.position.z);
  95167. newNormalData.push(normalData[originalOffset * 3]);
  95168. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95169. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95170. if (uvs && uvs.length) {
  95171. newUVsData.push(uvs[(originalOffset * 2)]);
  95172. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95173. }
  95174. else if (colorsData && colorsData.length) {
  95175. newColorsData.push(colorsData[(originalOffset * 4)]);
  95176. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95177. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95178. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95179. }
  95180. ++vertexCount;
  95181. });
  95182. }
  95183. }
  95184. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95185. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95186. var submeshesArray = this._reconstructedMesh.subMeshes;
  95187. this._reconstructedMesh.subMeshes = [];
  95188. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95189. var originalIndices = this._mesh.getIndices();
  95190. for (i = 0; i < newTriangles.length; ++i) {
  95191. t = newTriangles[i]; //now get the new referencing point for each vertex
  95192. [0, 1, 2].forEach(function (idx) {
  95193. var id = originalIndices[t.originalOffset + idx];
  95194. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95195. if (offset < 0)
  95196. offset = 0;
  95197. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95198. });
  95199. }
  95200. //overwriting the old vertex buffers and indices.
  95201. this._reconstructedMesh.setIndices(newIndicesArray);
  95202. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95203. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95204. if (newUVsData.length > 0)
  95205. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95206. if (newColorsData.length > 0)
  95207. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95208. //create submesh
  95209. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95210. if (submeshIndex > 0) {
  95211. this._reconstructedMesh.subMeshes = [];
  95212. submeshesArray.forEach(function (submesh) {
  95213. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95214. });
  95215. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95216. }
  95217. };
  95218. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95219. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95220. this._reconstructedMesh.material = this._mesh.material;
  95221. this._reconstructedMesh.parent = this._mesh.parent;
  95222. this._reconstructedMesh.isVisible = false;
  95223. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95224. };
  95225. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95226. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95227. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95228. if (t.deleted)
  95229. continue;
  95230. var s = this.references[vertex1.triangleStart + i].vertexId;
  95231. var v1 = t.vertices[(s + 1) % 3];
  95232. var v2 = t.vertices[(s + 2) % 3];
  95233. if ((v1 === vertex2 || v2 === vertex2)) {
  95234. deletedArray[i] = true;
  95235. delTr.push(t);
  95236. continue;
  95237. }
  95238. var d1 = v1.position.subtract(point);
  95239. d1 = d1.normalize();
  95240. var d2 = v2.position.subtract(point);
  95241. d2 = d2.normalize();
  95242. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95243. return true;
  95244. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95245. deletedArray[i] = false;
  95246. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95247. return true;
  95248. }
  95249. return false;
  95250. };
  95251. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95252. var newDeleted = deletedTriangles;
  95253. for (var i = 0; i < vertex.triangleCount; ++i) {
  95254. var ref = this.references[vertex.triangleStart + i];
  95255. var t = this.triangles[ref.triangleId];
  95256. if (t.deleted)
  95257. continue;
  95258. if (deletedArray[i] && t.deletePending) {
  95259. t.deleted = true;
  95260. newDeleted++;
  95261. continue;
  95262. }
  95263. t.vertices[ref.vertexId] = origVertex;
  95264. t.isDirty = true;
  95265. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95266. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95267. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95268. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95269. this.references.push(ref);
  95270. }
  95271. return newDeleted;
  95272. };
  95273. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95274. for (var i = 0; i < this.vertices.length; ++i) {
  95275. var vCount = [];
  95276. var vId = [];
  95277. var v = this.vertices[i];
  95278. var j;
  95279. for (j = 0; j < v.triangleCount; ++j) {
  95280. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95281. for (var ii = 0; ii < 3; ii++) {
  95282. var ofs = 0;
  95283. var vv = triangle.vertices[ii];
  95284. while (ofs < vCount.length) {
  95285. if (vId[ofs] === vv.id)
  95286. break;
  95287. ++ofs;
  95288. }
  95289. if (ofs === vCount.length) {
  95290. vCount.push(1);
  95291. vId.push(vv.id);
  95292. }
  95293. else {
  95294. vCount[ofs]++;
  95295. }
  95296. }
  95297. }
  95298. for (j = 0; j < vCount.length; ++j) {
  95299. if (vCount[j] === 1) {
  95300. this.vertices[vId[j]].isBorder = true;
  95301. }
  95302. else {
  95303. this.vertices[vId[j]].isBorder = false;
  95304. }
  95305. }
  95306. }
  95307. };
  95308. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95309. if (identifyBorders === void 0) { identifyBorders = false; }
  95310. var i;
  95311. if (!identifyBorders) {
  95312. var newTrianglesVector = [];
  95313. for (i = 0; i < this.triangles.length; ++i) {
  95314. if (!this.triangles[i].deleted) {
  95315. newTrianglesVector.push(this.triangles[i]);
  95316. }
  95317. }
  95318. this.triangles = newTrianglesVector;
  95319. }
  95320. for (i = 0; i < this.vertices.length; ++i) {
  95321. this.vertices[i].triangleCount = 0;
  95322. this.vertices[i].triangleStart = 0;
  95323. }
  95324. var t;
  95325. var j;
  95326. var v;
  95327. for (i = 0; i < this.triangles.length; ++i) {
  95328. t = this.triangles[i];
  95329. for (j = 0; j < 3; ++j) {
  95330. v = t.vertices[j];
  95331. v.triangleCount++;
  95332. }
  95333. }
  95334. var tStart = 0;
  95335. for (i = 0; i < this.vertices.length; ++i) {
  95336. this.vertices[i].triangleStart = tStart;
  95337. tStart += this.vertices[i].triangleCount;
  95338. this.vertices[i].triangleCount = 0;
  95339. }
  95340. var newReferences = new Array(this.triangles.length * 3);
  95341. for (i = 0; i < this.triangles.length; ++i) {
  95342. t = this.triangles[i];
  95343. for (j = 0; j < 3; ++j) {
  95344. v = t.vertices[j];
  95345. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95346. v.triangleCount++;
  95347. }
  95348. }
  95349. this.references = newReferences;
  95350. if (identifyBorders) {
  95351. this.identifyBorder();
  95352. }
  95353. };
  95354. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95355. var x = point.x;
  95356. var y = point.y;
  95357. var z = point.z;
  95358. 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
  95359. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95360. };
  95361. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95362. var q = vertex1.q.add(vertex2.q);
  95363. var border = vertex1.isBorder && vertex2.isBorder;
  95364. var error = 0;
  95365. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95366. if (qDet !== 0 && !border) {
  95367. if (!pointResult) {
  95368. pointResult = BABYLON.Vector3.Zero();
  95369. }
  95370. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95371. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95372. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95373. error = this.vertexError(q, pointResult);
  95374. }
  95375. else {
  95376. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95377. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95378. var error1 = this.vertexError(q, vertex1.position);
  95379. var error2 = this.vertexError(q, vertex2.position);
  95380. var error3 = this.vertexError(q, p3);
  95381. error = Math.min(error1, error2, error3);
  95382. if (error === error1) {
  95383. if (pointResult) {
  95384. pointResult.copyFrom(vertex1.position);
  95385. }
  95386. }
  95387. else if (error === error2) {
  95388. if (pointResult) {
  95389. pointResult.copyFrom(vertex2.position);
  95390. }
  95391. }
  95392. else {
  95393. if (pointResult) {
  95394. pointResult.copyFrom(p3);
  95395. }
  95396. }
  95397. }
  95398. return error;
  95399. };
  95400. return QuadraticErrorSimplification;
  95401. }());
  95402. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95403. })(BABYLON || (BABYLON = {}));
  95404. //# sourceMappingURL=babylon.meshSimplification.js.map
  95405. var BABYLON;
  95406. (function (BABYLON) {
  95407. var MeshLODLevel = /** @class */ (function () {
  95408. function MeshLODLevel(distance, mesh) {
  95409. this.distance = distance;
  95410. this.mesh = mesh;
  95411. }
  95412. return MeshLODLevel;
  95413. }());
  95414. BABYLON.MeshLODLevel = MeshLODLevel;
  95415. })(BABYLON || (BABYLON = {}));
  95416. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95417. var BABYLON;
  95418. (function (BABYLON) {
  95419. /**
  95420. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95421. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95422. */
  95423. var SceneOptimization = /** @class */ (function () {
  95424. /**
  95425. * Creates the SceneOptimization object
  95426. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95427. * @param desc defines the description associated with the optimization
  95428. */
  95429. function SceneOptimization(
  95430. /**
  95431. * Defines the priority of this optimization (0 by default which means first in the list)
  95432. */
  95433. priority) {
  95434. if (priority === void 0) { priority = 0; }
  95435. this.priority = priority;
  95436. }
  95437. /**
  95438. * Gets a string describing the action executed by the current optimization
  95439. * @returns description string
  95440. */
  95441. SceneOptimization.prototype.getDescription = function () {
  95442. return "";
  95443. };
  95444. /**
  95445. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95446. * @param scene defines the current scene where to apply this optimization
  95447. * @param optimizer defines the current optimizer
  95448. * @returns true if everything that can be done was applied
  95449. */
  95450. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95451. return true;
  95452. };
  95453. ;
  95454. return SceneOptimization;
  95455. }());
  95456. BABYLON.SceneOptimization = SceneOptimization;
  95457. /**
  95458. * Defines an optimization used to reduce the size of render target textures
  95459. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95460. */
  95461. var TextureOptimization = /** @class */ (function (_super) {
  95462. __extends(TextureOptimization, _super);
  95463. /**
  95464. * Creates the TextureOptimization object
  95465. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95466. * @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
  95467. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95468. */
  95469. function TextureOptimization(
  95470. /**
  95471. * Defines the priority of this optimization (0 by default which means first in the list)
  95472. */
  95473. priority,
  95474. /**
  95475. * 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
  95476. */
  95477. maximumSize,
  95478. /**
  95479. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95480. */
  95481. step) {
  95482. if (priority === void 0) { priority = 0; }
  95483. if (maximumSize === void 0) { maximumSize = 1024; }
  95484. if (step === void 0) { step = 0.5; }
  95485. var _this = _super.call(this, priority) || this;
  95486. _this.priority = priority;
  95487. _this.maximumSize = maximumSize;
  95488. _this.step = step;
  95489. return _this;
  95490. }
  95491. /**
  95492. * Gets a string describing the action executed by the current optimization
  95493. * @returns description string
  95494. */
  95495. TextureOptimization.prototype.getDescription = function () {
  95496. return "Reducing render target texture size to " + this.maximumSize;
  95497. };
  95498. /**
  95499. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95500. * @param scene defines the current scene where to apply this optimization
  95501. * @param optimizer defines the current optimizer
  95502. * @returns true if everything that can be done was applied
  95503. */
  95504. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95505. var allDone = true;
  95506. for (var index = 0; index < scene.textures.length; index++) {
  95507. var texture = scene.textures[index];
  95508. if (!texture.canRescale || texture.getContext) {
  95509. continue;
  95510. }
  95511. var currentSize = texture.getSize();
  95512. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95513. if (maxDimension > this.maximumSize) {
  95514. texture.scale(this.step);
  95515. allDone = false;
  95516. }
  95517. }
  95518. return allDone;
  95519. };
  95520. return TextureOptimization;
  95521. }(SceneOptimization));
  95522. BABYLON.TextureOptimization = TextureOptimization;
  95523. /**
  95524. * Defines an optimization used to increase or decrease the rendering resolution
  95525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95526. */
  95527. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95528. __extends(HardwareScalingOptimization, _super);
  95529. /**
  95530. * Creates the HardwareScalingOptimization object
  95531. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95532. * @param maximumScale defines the maximum scale to use (2 by default)
  95533. * @param step defines the step to use between two passes (0.5 by default)
  95534. */
  95535. function HardwareScalingOptimization(
  95536. /**
  95537. * Defines the priority of this optimization (0 by default which means first in the list)
  95538. */
  95539. priority,
  95540. /**
  95541. * Defines the maximum scale to use (2 by default)
  95542. */
  95543. maximumScale,
  95544. /**
  95545. * Defines the step to use between two passes (0.5 by default)
  95546. */
  95547. step) {
  95548. if (priority === void 0) { priority = 0; }
  95549. if (maximumScale === void 0) { maximumScale = 2; }
  95550. if (step === void 0) { step = 0.25; }
  95551. var _this = _super.call(this, priority) || this;
  95552. _this.priority = priority;
  95553. _this.maximumScale = maximumScale;
  95554. _this.step = step;
  95555. _this._currentScale = -1;
  95556. _this._directionOffset = 1;
  95557. return _this;
  95558. }
  95559. /**
  95560. * Gets a string describing the action executed by the current optimization
  95561. * @return description string
  95562. */
  95563. HardwareScalingOptimization.prototype.getDescription = function () {
  95564. return "Setting hardware scaling level to " + this._currentScale;
  95565. };
  95566. /**
  95567. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95568. * @param scene defines the current scene where to apply this optimization
  95569. * @param optimizer defines the current optimizer
  95570. * @returns true if everything that can be done was applied
  95571. */
  95572. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95573. if (this._currentScale === -1) {
  95574. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95575. if (this._currentScale > this.maximumScale) {
  95576. this._directionOffset = -1;
  95577. }
  95578. }
  95579. this._currentScale += this._directionOffset * this.step;
  95580. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95581. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95582. };
  95583. ;
  95584. return HardwareScalingOptimization;
  95585. }(SceneOptimization));
  95586. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95587. /**
  95588. * Defines an optimization used to remove shadows
  95589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95590. */
  95591. var ShadowsOptimization = /** @class */ (function (_super) {
  95592. __extends(ShadowsOptimization, _super);
  95593. function ShadowsOptimization() {
  95594. return _super !== null && _super.apply(this, arguments) || this;
  95595. }
  95596. /**
  95597. * Gets a string describing the action executed by the current optimization
  95598. * @return description string
  95599. */
  95600. ShadowsOptimization.prototype.getDescription = function () {
  95601. return "Turning shadows on/off";
  95602. };
  95603. /**
  95604. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95605. * @param scene defines the current scene where to apply this optimization
  95606. * @param optimizer defines the current optimizer
  95607. * @returns true if everything that can be done was applied
  95608. */
  95609. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95610. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95611. return true;
  95612. };
  95613. ;
  95614. return ShadowsOptimization;
  95615. }(SceneOptimization));
  95616. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95617. /**
  95618. * Defines an optimization used to turn post-processes off
  95619. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95620. */
  95621. var PostProcessesOptimization = /** @class */ (function (_super) {
  95622. __extends(PostProcessesOptimization, _super);
  95623. function PostProcessesOptimization() {
  95624. return _super !== null && _super.apply(this, arguments) || this;
  95625. }
  95626. /**
  95627. * Gets a string describing the action executed by the current optimization
  95628. * @return description string
  95629. */
  95630. PostProcessesOptimization.prototype.getDescription = function () {
  95631. return "Turning post-processes on/off";
  95632. };
  95633. /**
  95634. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95635. * @param scene defines the current scene where to apply this optimization
  95636. * @param optimizer defines the current optimizer
  95637. * @returns true if everything that can be done was applied
  95638. */
  95639. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95640. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95641. return true;
  95642. };
  95643. ;
  95644. return PostProcessesOptimization;
  95645. }(SceneOptimization));
  95646. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95647. /**
  95648. * Defines an optimization used to turn lens flares off
  95649. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95650. */
  95651. var LensFlaresOptimization = /** @class */ (function (_super) {
  95652. __extends(LensFlaresOptimization, _super);
  95653. function LensFlaresOptimization() {
  95654. return _super !== null && _super.apply(this, arguments) || this;
  95655. }
  95656. /**
  95657. * Gets a string describing the action executed by the current optimization
  95658. * @return description string
  95659. */
  95660. LensFlaresOptimization.prototype.getDescription = function () {
  95661. return "Turning lens flares on/off";
  95662. };
  95663. /**
  95664. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95665. * @param scene defines the current scene where to apply this optimization
  95666. * @param optimizer defines the current optimizer
  95667. * @returns true if everything that can be done was applied
  95668. */
  95669. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95670. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95671. return true;
  95672. };
  95673. ;
  95674. return LensFlaresOptimization;
  95675. }(SceneOptimization));
  95676. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95677. /**
  95678. * Defines an optimization based on user defined callback.
  95679. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95680. */
  95681. var CustomOptimization = /** @class */ (function (_super) {
  95682. __extends(CustomOptimization, _super);
  95683. function CustomOptimization() {
  95684. return _super !== null && _super.apply(this, arguments) || this;
  95685. }
  95686. /**
  95687. * Gets a string describing the action executed by the current optimization
  95688. * @returns description string
  95689. */
  95690. CustomOptimization.prototype.getDescription = function () {
  95691. if (this.onGetDescription) {
  95692. return this.onGetDescription();
  95693. }
  95694. return "Running user defined callback";
  95695. };
  95696. /**
  95697. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95698. * @param scene defines the current scene where to apply this optimization
  95699. * @param optimizer defines the current optimizer
  95700. * @returns true if everything that can be done was applied
  95701. */
  95702. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95703. if (this.onApply) {
  95704. return this.onApply(scene, optimizer);
  95705. }
  95706. return true;
  95707. };
  95708. ;
  95709. return CustomOptimization;
  95710. }(SceneOptimization));
  95711. BABYLON.CustomOptimization = CustomOptimization;
  95712. /**
  95713. * Defines an optimization used to turn particles off
  95714. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95715. */
  95716. var ParticlesOptimization = /** @class */ (function (_super) {
  95717. __extends(ParticlesOptimization, _super);
  95718. function ParticlesOptimization() {
  95719. return _super !== null && _super.apply(this, arguments) || this;
  95720. }
  95721. /**
  95722. * Gets a string describing the action executed by the current optimization
  95723. * @return description string
  95724. */
  95725. ParticlesOptimization.prototype.getDescription = function () {
  95726. return "Turning particles on/off";
  95727. };
  95728. /**
  95729. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95730. * @param scene defines the current scene where to apply this optimization
  95731. * @param optimizer defines the current optimizer
  95732. * @returns true if everything that can be done was applied
  95733. */
  95734. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95735. scene.particlesEnabled = optimizer.isInImprovementMode;
  95736. return true;
  95737. };
  95738. ;
  95739. return ParticlesOptimization;
  95740. }(SceneOptimization));
  95741. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95742. /**
  95743. * Defines an optimization used to turn render targets off
  95744. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95745. */
  95746. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95747. __extends(RenderTargetsOptimization, _super);
  95748. function RenderTargetsOptimization() {
  95749. return _super !== null && _super.apply(this, arguments) || this;
  95750. }
  95751. /**
  95752. * Gets a string describing the action executed by the current optimization
  95753. * @return description string
  95754. */
  95755. RenderTargetsOptimization.prototype.getDescription = function () {
  95756. return "Turning render targets off";
  95757. };
  95758. /**
  95759. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95760. * @param scene defines the current scene where to apply this optimization
  95761. * @param optimizer defines the current optimizer
  95762. * @returns true if everything that can be done was applied
  95763. */
  95764. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95765. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95766. return true;
  95767. };
  95768. ;
  95769. return RenderTargetsOptimization;
  95770. }(SceneOptimization));
  95771. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95772. /**
  95773. * Defines an optimization used to merge meshes with compatible materials
  95774. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95775. */
  95776. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95777. __extends(MergeMeshesOptimization, _super);
  95778. function MergeMeshesOptimization() {
  95779. var _this = _super !== null && _super.apply(this, arguments) || this;
  95780. _this._canBeMerged = function (abstractMesh) {
  95781. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95782. return false;
  95783. }
  95784. var mesh = abstractMesh;
  95785. if (mesh.isDisposed()) {
  95786. return false;
  95787. }
  95788. if (!mesh.isVisible || !mesh.isEnabled()) {
  95789. return false;
  95790. }
  95791. if (mesh.instances.length > 0) {
  95792. return false;
  95793. }
  95794. if (mesh.skeleton || mesh.hasLODLevels) {
  95795. return false;
  95796. }
  95797. return true;
  95798. };
  95799. return _this;
  95800. }
  95801. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95802. /**
  95803. * Gets or sets a boolean which defines if optimization octree has to be updated
  95804. */
  95805. get: function () {
  95806. return MergeMeshesOptimization._UpdateSelectionTree;
  95807. },
  95808. /**
  95809. * Gets or sets a boolean which defines if optimization octree has to be updated
  95810. */
  95811. set: function (value) {
  95812. MergeMeshesOptimization._UpdateSelectionTree = value;
  95813. },
  95814. enumerable: true,
  95815. configurable: true
  95816. });
  95817. /**
  95818. * Gets a string describing the action executed by the current optimization
  95819. * @return description string
  95820. */
  95821. MergeMeshesOptimization.prototype.getDescription = function () {
  95822. return "Merging similar meshes together";
  95823. };
  95824. /**
  95825. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95826. * @param scene defines the current scene where to apply this optimization
  95827. * @param optimizer defines the current optimizer
  95828. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95829. * @returns true if everything that can be done was applied
  95830. */
  95831. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95832. var globalPool = scene.meshes.slice(0);
  95833. var globalLength = globalPool.length;
  95834. for (var index = 0; index < globalLength; index++) {
  95835. var currentPool = new Array();
  95836. var current = globalPool[index];
  95837. // Checks
  95838. if (!this._canBeMerged(current)) {
  95839. continue;
  95840. }
  95841. currentPool.push(current);
  95842. // Find compatible meshes
  95843. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95844. var otherMesh = globalPool[subIndex];
  95845. if (!this._canBeMerged(otherMesh)) {
  95846. continue;
  95847. }
  95848. if (otherMesh.material !== current.material) {
  95849. continue;
  95850. }
  95851. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95852. continue;
  95853. }
  95854. currentPool.push(otherMesh);
  95855. globalLength--;
  95856. globalPool.splice(subIndex, 1);
  95857. subIndex--;
  95858. }
  95859. if (currentPool.length < 2) {
  95860. continue;
  95861. }
  95862. // Merge meshes
  95863. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95864. }
  95865. if (updateSelectionTree != undefined) {
  95866. if (updateSelectionTree) {
  95867. scene.createOrUpdateSelectionOctree();
  95868. }
  95869. }
  95870. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95871. scene.createOrUpdateSelectionOctree();
  95872. }
  95873. return true;
  95874. };
  95875. ;
  95876. MergeMeshesOptimization._UpdateSelectionTree = false;
  95877. return MergeMeshesOptimization;
  95878. }(SceneOptimization));
  95879. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95880. /**
  95881. * Defines a list of options used by SceneOptimizer
  95882. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95883. */
  95884. var SceneOptimizerOptions = /** @class */ (function () {
  95885. /**
  95886. * Creates a new list of options used by SceneOptimizer
  95887. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95888. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95889. */
  95890. function SceneOptimizerOptions(
  95891. /**
  95892. * Defines the target frame rate to reach (60 by default)
  95893. */
  95894. targetFrameRate,
  95895. /**
  95896. * Defines the interval between two checkes (2000ms by default)
  95897. */
  95898. trackerDuration) {
  95899. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95900. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95901. this.targetFrameRate = targetFrameRate;
  95902. this.trackerDuration = trackerDuration;
  95903. /**
  95904. * Gets the list of optimizations to apply
  95905. */
  95906. this.optimizations = new Array();
  95907. }
  95908. /**
  95909. * Add a new optimization
  95910. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95911. * @returns the current SceneOptimizerOptions
  95912. */
  95913. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95914. this.optimizations.push(optimization);
  95915. return this;
  95916. };
  95917. /**
  95918. * Add a new custom optimization
  95919. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95920. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95921. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95922. * @returns the current SceneOptimizerOptions
  95923. */
  95924. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95925. if (priority === void 0) { priority = 0; }
  95926. var optimization = new CustomOptimization(priority);
  95927. optimization.onApply = onApply;
  95928. optimization.onGetDescription = onGetDescription;
  95929. this.optimizations.push(optimization);
  95930. return this;
  95931. };
  95932. /**
  95933. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95934. * @param targetFrameRate defines the target frame rate (60 by default)
  95935. * @returns a SceneOptimizerOptions object
  95936. */
  95937. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95938. var result = new SceneOptimizerOptions(targetFrameRate);
  95939. var priority = 0;
  95940. result.addOptimization(new MergeMeshesOptimization(priority));
  95941. result.addOptimization(new ShadowsOptimization(priority));
  95942. result.addOptimization(new LensFlaresOptimization(priority));
  95943. // Next priority
  95944. priority++;
  95945. result.addOptimization(new PostProcessesOptimization(priority));
  95946. result.addOptimization(new ParticlesOptimization(priority));
  95947. // Next priority
  95948. priority++;
  95949. result.addOptimization(new TextureOptimization(priority, 1024));
  95950. return result;
  95951. };
  95952. /**
  95953. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95954. * @param targetFrameRate defines the target frame rate (60 by default)
  95955. * @returns a SceneOptimizerOptions object
  95956. */
  95957. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95958. var result = new SceneOptimizerOptions(targetFrameRate);
  95959. var priority = 0;
  95960. result.addOptimization(new MergeMeshesOptimization(priority));
  95961. result.addOptimization(new ShadowsOptimization(priority));
  95962. result.addOptimization(new LensFlaresOptimization(priority));
  95963. // Next priority
  95964. priority++;
  95965. result.addOptimization(new PostProcessesOptimization(priority));
  95966. result.addOptimization(new ParticlesOptimization(priority));
  95967. // Next priority
  95968. priority++;
  95969. result.addOptimization(new TextureOptimization(priority, 512));
  95970. // Next priority
  95971. priority++;
  95972. result.addOptimization(new RenderTargetsOptimization(priority));
  95973. // Next priority
  95974. priority++;
  95975. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95976. return result;
  95977. };
  95978. /**
  95979. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95980. * @param targetFrameRate defines the target frame rate (60 by default)
  95981. * @returns a SceneOptimizerOptions object
  95982. */
  95983. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95984. var result = new SceneOptimizerOptions(targetFrameRate);
  95985. var priority = 0;
  95986. result.addOptimization(new MergeMeshesOptimization(priority));
  95987. result.addOptimization(new ShadowsOptimization(priority));
  95988. result.addOptimization(new LensFlaresOptimization(priority));
  95989. // Next priority
  95990. priority++;
  95991. result.addOptimization(new PostProcessesOptimization(priority));
  95992. result.addOptimization(new ParticlesOptimization(priority));
  95993. // Next priority
  95994. priority++;
  95995. result.addOptimization(new TextureOptimization(priority, 256));
  95996. // Next priority
  95997. priority++;
  95998. result.addOptimization(new RenderTargetsOptimization(priority));
  95999. // Next priority
  96000. priority++;
  96001. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96002. return result;
  96003. };
  96004. return SceneOptimizerOptions;
  96005. }());
  96006. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96007. /**
  96008. * Class used to run optimizations in order to reach a target frame rate
  96009. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96010. */
  96011. var SceneOptimizer = /** @class */ (function () {
  96012. /**
  96013. * Creates a new SceneOptimizer
  96014. * @param scene defines the scene to work on
  96015. * @param options defines the options to use with the SceneOptimizer
  96016. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96017. * @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)
  96018. */
  96019. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96020. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96021. if (improvementMode === void 0) { improvementMode = false; }
  96022. var _this = this;
  96023. this._isRunning = false;
  96024. this._currentPriorityLevel = 0;
  96025. this._targetFrameRate = 60;
  96026. this._trackerDuration = 2000;
  96027. this._currentFrameRate = 0;
  96028. this._improvementMode = false;
  96029. /**
  96030. * Defines an observable called when the optimizer reaches the target frame rate
  96031. */
  96032. this.onSuccessObservable = new BABYLON.Observable();
  96033. /**
  96034. * Defines an observable called when the optimizer enables an optimization
  96035. */
  96036. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96037. /**
  96038. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96039. */
  96040. this.onFailureObservable = new BABYLON.Observable();
  96041. if (!options) {
  96042. this._options = new SceneOptimizerOptions();
  96043. }
  96044. else {
  96045. this._options = options;
  96046. }
  96047. if (this._options.targetFrameRate) {
  96048. this._targetFrameRate = this._options.targetFrameRate;
  96049. }
  96050. if (this._options.trackerDuration) {
  96051. this._trackerDuration = this._options.trackerDuration;
  96052. }
  96053. if (autoGeneratePriorities) {
  96054. var priority = 0;
  96055. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96056. var optim = _a[_i];
  96057. optim.priority = priority++;
  96058. }
  96059. }
  96060. this._improvementMode = improvementMode;
  96061. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96062. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96063. _this._sceneDisposeObserver = null;
  96064. _this.dispose();
  96065. });
  96066. }
  96067. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96068. /**
  96069. * Gets a boolean indicating if the optimizer is in improvement mode
  96070. */
  96071. get: function () {
  96072. return this._improvementMode;
  96073. },
  96074. enumerable: true,
  96075. configurable: true
  96076. });
  96077. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96078. /**
  96079. * Gets the current priority level (0 at start)
  96080. */
  96081. get: function () {
  96082. return this._currentPriorityLevel;
  96083. },
  96084. enumerable: true,
  96085. configurable: true
  96086. });
  96087. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96088. /**
  96089. * Gets the current frame rate checked by the SceneOptimizer
  96090. */
  96091. get: function () {
  96092. return this._currentFrameRate;
  96093. },
  96094. enumerable: true,
  96095. configurable: true
  96096. });
  96097. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96098. /**
  96099. * Gets or sets the current target frame rate (60 by default)
  96100. */
  96101. get: function () {
  96102. return this._targetFrameRate;
  96103. },
  96104. /**
  96105. * Gets or sets the current target frame rate (60 by default)
  96106. */
  96107. set: function (value) {
  96108. this._targetFrameRate = value;
  96109. },
  96110. enumerable: true,
  96111. configurable: true
  96112. });
  96113. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96114. /**
  96115. * Gets or sets the current interval between two checks (every 2000ms by default)
  96116. */
  96117. get: function () {
  96118. return this._trackerDuration;
  96119. },
  96120. /**
  96121. * Gets or sets the current interval between two checks (every 2000ms by default)
  96122. */
  96123. set: function (value) {
  96124. this._trackerDuration = value;
  96125. },
  96126. enumerable: true,
  96127. configurable: true
  96128. });
  96129. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96130. /**
  96131. * Gets the list of active optimizations
  96132. */
  96133. get: function () {
  96134. return this._options.optimizations;
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. /**
  96140. * Stops the current optimizer
  96141. */
  96142. SceneOptimizer.prototype.stop = function () {
  96143. this._isRunning = false;
  96144. };
  96145. /**
  96146. * Reset the optimizer to initial step (current priority level = 0)
  96147. */
  96148. SceneOptimizer.prototype.reset = function () {
  96149. this._currentPriorityLevel = 0;
  96150. };
  96151. /**
  96152. * Start the optimizer. By default it will try to reach a specific framerate
  96153. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96154. */
  96155. SceneOptimizer.prototype.start = function () {
  96156. var _this = this;
  96157. if (this._isRunning) {
  96158. return;
  96159. }
  96160. this._isRunning = true;
  96161. // Let's wait for the scene to be ready before running our check
  96162. this._scene.executeWhenReady(function () {
  96163. setTimeout(function () {
  96164. _this._checkCurrentState();
  96165. }, _this._trackerDuration);
  96166. });
  96167. };
  96168. SceneOptimizer.prototype._checkCurrentState = function () {
  96169. var _this = this;
  96170. if (!this._isRunning) {
  96171. return;
  96172. }
  96173. var scene = this._scene;
  96174. var options = this._options;
  96175. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96176. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96177. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96178. this._isRunning = false;
  96179. this.onSuccessObservable.notifyObservers(this);
  96180. return;
  96181. }
  96182. // Apply current level of optimizations
  96183. var allDone = true;
  96184. var noOptimizationApplied = true;
  96185. for (var index = 0; index < options.optimizations.length; index++) {
  96186. var optimization = options.optimizations[index];
  96187. if (optimization.priority === this._currentPriorityLevel) {
  96188. noOptimizationApplied = false;
  96189. allDone = allDone && optimization.apply(scene, this);
  96190. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96191. }
  96192. }
  96193. // If no optimization was applied, this is a failure :(
  96194. if (noOptimizationApplied) {
  96195. this._isRunning = false;
  96196. this.onFailureObservable.notifyObservers(this);
  96197. return;
  96198. }
  96199. // If all optimizations were done, move to next level
  96200. if (allDone) {
  96201. this._currentPriorityLevel++;
  96202. }
  96203. // Let's the system running for a specific amount of time before checking FPS
  96204. scene.executeWhenReady(function () {
  96205. setTimeout(function () {
  96206. _this._checkCurrentState();
  96207. }, _this._trackerDuration);
  96208. });
  96209. };
  96210. /**
  96211. * Release all resources
  96212. */
  96213. SceneOptimizer.prototype.dispose = function () {
  96214. this.stop();
  96215. this.onSuccessObservable.clear();
  96216. this.onFailureObservable.clear();
  96217. this.onNewOptimizationAppliedObservable.clear();
  96218. if (this._sceneDisposeObserver) {
  96219. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96220. }
  96221. };
  96222. /**
  96223. * Helper function to create a SceneOptimizer with one single line of code
  96224. * @param scene defines the scene to work on
  96225. * @param options defines the options to use with the SceneOptimizer
  96226. * @param onSuccess defines a callback to call on success
  96227. * @param onFailure defines a callback to call on failure
  96228. * @returns the new SceneOptimizer object
  96229. */
  96230. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96231. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96232. if (onSuccess) {
  96233. optimizer.onSuccessObservable.add(function () {
  96234. onSuccess();
  96235. });
  96236. }
  96237. if (onFailure) {
  96238. optimizer.onFailureObservable.add(function () {
  96239. onFailure();
  96240. });
  96241. }
  96242. optimizer.start();
  96243. return optimizer;
  96244. };
  96245. return SceneOptimizer;
  96246. }());
  96247. BABYLON.SceneOptimizer = SceneOptimizer;
  96248. })(BABYLON || (BABYLON = {}));
  96249. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96250. var BABYLON;
  96251. (function (BABYLON) {
  96252. var OutlineRenderer = /** @class */ (function () {
  96253. function OutlineRenderer(scene) {
  96254. this.zOffset = 1;
  96255. this._scene = scene;
  96256. }
  96257. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96258. var _this = this;
  96259. if (useOverlay === void 0) { useOverlay = false; }
  96260. var scene = this._scene;
  96261. var engine = this._scene.getEngine();
  96262. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96263. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96264. return;
  96265. }
  96266. var mesh = subMesh.getRenderingMesh();
  96267. var material = subMesh.getMaterial();
  96268. if (!material || !scene.activeCamera) {
  96269. return;
  96270. }
  96271. engine.enableEffect(this._effect);
  96272. // Logarithmic depth
  96273. if (material.useLogarithmicDepth) {
  96274. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96275. }
  96276. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96277. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96278. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96279. // Bones
  96280. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96281. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96282. }
  96283. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96284. // Alpha test
  96285. if (material && material.needAlphaTesting()) {
  96286. var alphaTexture = material.getAlphaTestTexture();
  96287. if (alphaTexture) {
  96288. this._effect.setTexture("diffuseSampler", alphaTexture);
  96289. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96290. }
  96291. }
  96292. engine.setZOffset(-this.zOffset);
  96293. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96294. engine.setZOffset(0);
  96295. };
  96296. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96297. var defines = [];
  96298. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96299. var mesh = subMesh.getMesh();
  96300. var material = subMesh.getMaterial();
  96301. if (material) {
  96302. // Alpha test
  96303. if (material.needAlphaTesting()) {
  96304. defines.push("#define ALPHATEST");
  96305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96306. attribs.push(BABYLON.VertexBuffer.UVKind);
  96307. defines.push("#define UV1");
  96308. }
  96309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96311. defines.push("#define UV2");
  96312. }
  96313. }
  96314. //Logarithmic depth
  96315. if (material.useLogarithmicDepth) {
  96316. defines.push("#define LOGARITHMICDEPTH");
  96317. }
  96318. }
  96319. // Bones
  96320. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96321. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96322. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96323. if (mesh.numBoneInfluencers > 4) {
  96324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96326. }
  96327. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96328. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96329. }
  96330. else {
  96331. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96332. }
  96333. // Instances
  96334. if (useInstances) {
  96335. defines.push("#define INSTANCES");
  96336. attribs.push("world0");
  96337. attribs.push("world1");
  96338. attribs.push("world2");
  96339. attribs.push("world3");
  96340. }
  96341. // Get correct effect
  96342. var join = defines.join("\n");
  96343. if (this._cachedDefines !== join) {
  96344. this._cachedDefines = join;
  96345. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96346. }
  96347. return this._effect.isReady();
  96348. };
  96349. return OutlineRenderer;
  96350. }());
  96351. BABYLON.OutlineRenderer = OutlineRenderer;
  96352. })(BABYLON || (BABYLON = {}));
  96353. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96354. var BABYLON;
  96355. (function (BABYLON) {
  96356. var FaceAdjacencies = /** @class */ (function () {
  96357. function FaceAdjacencies() {
  96358. this.edges = new Array();
  96359. this.edgesConnectedCount = 0;
  96360. }
  96361. return FaceAdjacencies;
  96362. }());
  96363. var EdgesRenderer = /** @class */ (function () {
  96364. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96365. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96366. if (epsilon === void 0) { epsilon = 0.95; }
  96367. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96368. this.edgesWidthScalerForOrthographic = 1000.0;
  96369. this.edgesWidthScalerForPerspective = 50.0;
  96370. this._linesPositions = new Array();
  96371. this._linesNormals = new Array();
  96372. this._linesIndices = new Array();
  96373. this._buffers = {};
  96374. this._checkVerticesInsteadOfIndices = false;
  96375. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96376. this.isEnabled = true;
  96377. this._source = source;
  96378. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96379. this._epsilon = epsilon;
  96380. this._prepareRessources();
  96381. this._generateEdgesLines();
  96382. }
  96383. EdgesRenderer.prototype._prepareRessources = function () {
  96384. if (this._lineShader) {
  96385. return;
  96386. }
  96387. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96388. attributes: ["position", "normal"],
  96389. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96390. });
  96391. this._lineShader.disableDepthWrite = true;
  96392. this._lineShader.backFaceCulling = false;
  96393. };
  96394. EdgesRenderer.prototype._rebuild = function () {
  96395. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96396. if (buffer) {
  96397. buffer._rebuild();
  96398. }
  96399. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96400. if (buffer) {
  96401. buffer._rebuild();
  96402. }
  96403. var scene = this._source.getScene();
  96404. var engine = scene.getEngine();
  96405. this._ib = engine.createIndexBuffer(this._linesIndices);
  96406. };
  96407. EdgesRenderer.prototype.dispose = function () {
  96408. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96409. if (buffer) {
  96410. buffer.dispose();
  96411. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96412. }
  96413. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96414. if (buffer) {
  96415. buffer.dispose();
  96416. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96417. }
  96418. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96419. this._lineShader.dispose();
  96420. };
  96421. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96422. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96423. return 0;
  96424. }
  96425. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96426. return 1;
  96427. }
  96428. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96429. return 2;
  96430. }
  96431. return -1;
  96432. };
  96433. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96434. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96435. return 0;
  96436. }
  96437. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96438. return 1;
  96439. }
  96440. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96441. return 2;
  96442. }
  96443. return -1;
  96444. };
  96445. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96446. var needToCreateLine;
  96447. if (edge === undefined) {
  96448. needToCreateLine = true;
  96449. }
  96450. else {
  96451. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96452. needToCreateLine = dotProduct < this._epsilon;
  96453. }
  96454. if (needToCreateLine) {
  96455. var offset = this._linesPositions.length / 3;
  96456. var normal = p0.subtract(p1);
  96457. normal.normalize();
  96458. // Positions
  96459. this._linesPositions.push(p0.x);
  96460. this._linesPositions.push(p0.y);
  96461. this._linesPositions.push(p0.z);
  96462. this._linesPositions.push(p0.x);
  96463. this._linesPositions.push(p0.y);
  96464. this._linesPositions.push(p0.z);
  96465. this._linesPositions.push(p1.x);
  96466. this._linesPositions.push(p1.y);
  96467. this._linesPositions.push(p1.z);
  96468. this._linesPositions.push(p1.x);
  96469. this._linesPositions.push(p1.y);
  96470. this._linesPositions.push(p1.z);
  96471. // Normals
  96472. this._linesNormals.push(p1.x);
  96473. this._linesNormals.push(p1.y);
  96474. this._linesNormals.push(p1.z);
  96475. this._linesNormals.push(-1);
  96476. this._linesNormals.push(p1.x);
  96477. this._linesNormals.push(p1.y);
  96478. this._linesNormals.push(p1.z);
  96479. this._linesNormals.push(1);
  96480. this._linesNormals.push(p0.x);
  96481. this._linesNormals.push(p0.y);
  96482. this._linesNormals.push(p0.z);
  96483. this._linesNormals.push(-1);
  96484. this._linesNormals.push(p0.x);
  96485. this._linesNormals.push(p0.y);
  96486. this._linesNormals.push(p0.z);
  96487. this._linesNormals.push(1);
  96488. // Indices
  96489. this._linesIndices.push(offset);
  96490. this._linesIndices.push(offset + 1);
  96491. this._linesIndices.push(offset + 2);
  96492. this._linesIndices.push(offset);
  96493. this._linesIndices.push(offset + 2);
  96494. this._linesIndices.push(offset + 3);
  96495. }
  96496. };
  96497. EdgesRenderer.prototype._generateEdgesLines = function () {
  96498. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96499. var indices = this._source.getIndices();
  96500. if (!indices || !positions) {
  96501. return;
  96502. }
  96503. // First let's find adjacencies
  96504. var adjacencies = new Array();
  96505. var faceNormals = new Array();
  96506. var index;
  96507. var faceAdjacencies;
  96508. // Prepare faces
  96509. for (index = 0; index < indices.length; index += 3) {
  96510. faceAdjacencies = new FaceAdjacencies();
  96511. var p0Index = indices[index];
  96512. var p1Index = indices[index + 1];
  96513. var p2Index = indices[index + 2];
  96514. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96515. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96516. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96517. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96518. faceNormal.normalize();
  96519. faceNormals.push(faceNormal);
  96520. adjacencies.push(faceAdjacencies);
  96521. }
  96522. // Scan
  96523. for (index = 0; index < adjacencies.length; index++) {
  96524. faceAdjacencies = adjacencies[index];
  96525. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96526. var otherFaceAdjacencies = adjacencies[otherIndex];
  96527. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96528. break;
  96529. }
  96530. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96531. continue;
  96532. }
  96533. var otherP0 = indices[otherIndex * 3];
  96534. var otherP1 = indices[otherIndex * 3 + 1];
  96535. var otherP2 = indices[otherIndex * 3 + 2];
  96536. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96537. var otherEdgeIndex = 0;
  96538. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96539. continue;
  96540. }
  96541. switch (edgeIndex) {
  96542. case 0:
  96543. if (this._checkVerticesInsteadOfIndices) {
  96544. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96545. }
  96546. else {
  96547. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96548. }
  96549. break;
  96550. case 1:
  96551. if (this._checkVerticesInsteadOfIndices) {
  96552. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96553. }
  96554. else {
  96555. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96556. }
  96557. break;
  96558. case 2:
  96559. if (this._checkVerticesInsteadOfIndices) {
  96560. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96561. }
  96562. else {
  96563. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96564. }
  96565. break;
  96566. }
  96567. if (otherEdgeIndex === -1) {
  96568. continue;
  96569. }
  96570. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96571. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96572. faceAdjacencies.edgesConnectedCount++;
  96573. otherFaceAdjacencies.edgesConnectedCount++;
  96574. if (faceAdjacencies.edgesConnectedCount === 3) {
  96575. break;
  96576. }
  96577. }
  96578. }
  96579. }
  96580. // Create lines
  96581. for (index = 0; index < adjacencies.length; index++) {
  96582. // 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
  96583. var current = adjacencies[index];
  96584. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96585. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96586. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96587. }
  96588. // Merge into a single mesh
  96589. var engine = this._source.getScene().getEngine();
  96590. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96591. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96592. this._ib = engine.createIndexBuffer(this._linesIndices);
  96593. this._indicesCount = this._linesIndices.length;
  96594. };
  96595. EdgesRenderer.prototype.render = function () {
  96596. var scene = this._source.getScene();
  96597. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96598. return;
  96599. }
  96600. var engine = scene.getEngine();
  96601. this._lineShader._preBind();
  96602. // VBOs
  96603. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96604. scene.resetCachedMaterial();
  96605. this._lineShader.setColor4("color", this._source.edgesColor);
  96606. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96607. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96608. }
  96609. else {
  96610. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96611. }
  96612. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96613. this._lineShader.bind(this._source.getWorldMatrix());
  96614. // Draw order
  96615. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96616. this._lineShader.unbind();
  96617. engine.setDepthWrite(true);
  96618. };
  96619. return EdgesRenderer;
  96620. }());
  96621. BABYLON.EdgesRenderer = EdgesRenderer;
  96622. })(BABYLON || (BABYLON = {}));
  96623. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96624. var BABYLON;
  96625. (function (BABYLON) {
  96626. // Adds the parser to the scene parsers.
  96627. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96628. if (parsedData.effectLayers) {
  96629. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96630. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96631. container.effectLayers.push(effectLayer);
  96632. }
  96633. }
  96634. });
  96635. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96636. var index = this.effectLayers.indexOf(toRemove);
  96637. if (index !== -1) {
  96638. this.effectLayers.splice(index, 1);
  96639. }
  96640. return index;
  96641. };
  96642. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96643. this.effectLayers.push(newEffectLayer);
  96644. };
  96645. /**
  96646. * Defines the layer scene component responsible to manage any effect layers
  96647. * in a given scene.
  96648. */
  96649. var EffectLayerSceneComponent = /** @class */ (function () {
  96650. /**
  96651. * Creates a new instance of the component for the given scene
  96652. * @param scene Defines the scene to register the component in
  96653. */
  96654. function EffectLayerSceneComponent(scene) {
  96655. /**
  96656. * The component name helpfull to identify the component in the list of scene components.
  96657. */
  96658. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96659. this._renderEffects = false;
  96660. this._needStencil = false;
  96661. this._previousStencilState = false;
  96662. this.scene = scene;
  96663. this._engine = scene.getEngine();
  96664. scene.effectLayers = new Array();
  96665. }
  96666. /**
  96667. * Registers the component in a given scene
  96668. */
  96669. EffectLayerSceneComponent.prototype.register = function () {
  96670. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96671. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96672. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96673. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96674. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96675. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96676. };
  96677. /**
  96678. * Rebuilds the elements related to this component in case of
  96679. * context lost for instance.
  96680. */
  96681. EffectLayerSceneComponent.prototype.rebuild = function () {
  96682. var layers = this.scene.effectLayers;
  96683. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96684. var effectLayer = layers_1[_i];
  96685. effectLayer._rebuild();
  96686. }
  96687. };
  96688. /**
  96689. * Serializes the component data to the specified json object
  96690. * @param serializationObject The object to serialize to
  96691. */
  96692. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96693. // Effect layers
  96694. serializationObject.effectLayers = [];
  96695. var layers = this.scene.effectLayers;
  96696. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96697. var effectLayer = layers_2[_i];
  96698. if (effectLayer.serialize) {
  96699. serializationObject.effectLayers.push(effectLayer.serialize());
  96700. }
  96701. }
  96702. };
  96703. /**
  96704. * Adds all the element from the container to the scene
  96705. * @param container the container holding the elements
  96706. */
  96707. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96708. var _this = this;
  96709. if (!container.effectLayers) {
  96710. return;
  96711. }
  96712. container.effectLayers.forEach(function (o) {
  96713. _this.scene.addEffectLayer(o);
  96714. });
  96715. };
  96716. /**
  96717. * Removes all the elements in the container from the scene
  96718. * @param container contains the elements to remove
  96719. */
  96720. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96721. var _this = this;
  96722. if (!container.effectLayers) {
  96723. return;
  96724. }
  96725. container.effectLayers.forEach(function (o) {
  96726. _this.scene.removeEffectLayer(o);
  96727. });
  96728. };
  96729. /**
  96730. * Disposes the component and the associated ressources.
  96731. */
  96732. EffectLayerSceneComponent.prototype.dispose = function () {
  96733. var layers = this.scene.effectLayers;
  96734. while (layers.length) {
  96735. layers[0].dispose();
  96736. }
  96737. };
  96738. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96739. var layers = this.scene.effectLayers;
  96740. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96741. var layer = layers_3[_i];
  96742. if (!layer.hasMesh(mesh)) {
  96743. continue;
  96744. }
  96745. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96746. var subMesh = _b[_a];
  96747. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96748. return false;
  96749. }
  96750. }
  96751. }
  96752. return true;
  96753. };
  96754. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96755. this._renderEffects = false;
  96756. this._needStencil = false;
  96757. var layers = this.scene.effectLayers;
  96758. if (layers && layers.length > 0) {
  96759. this._previousStencilState = this._engine.getStencilBuffer();
  96760. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96761. var effectLayer = layers_4[_i];
  96762. if (effectLayer.shouldRender() &&
  96763. (!effectLayer.camera ||
  96764. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96765. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96766. this._renderEffects = true;
  96767. this._needStencil = this._needStencil || effectLayer.needStencil();
  96768. var renderTarget = effectLayer._mainTexture;
  96769. if (renderTarget._shouldRender()) {
  96770. this.scene.incrementRenderId();
  96771. renderTarget.render(false, false);
  96772. }
  96773. }
  96774. }
  96775. this.scene.incrementRenderId();
  96776. }
  96777. };
  96778. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96779. // Activate effect Layer stencil
  96780. if (this._needStencil) {
  96781. this._engine.setStencilBuffer(true);
  96782. }
  96783. };
  96784. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96785. // Restore effect Layer stencil
  96786. if (this._needStencil) {
  96787. this._engine.setStencilBuffer(this._previousStencilState);
  96788. }
  96789. };
  96790. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96791. if (this._renderEffects) {
  96792. this._engine.setDepthBuffer(false);
  96793. var layers = this.scene.effectLayers;
  96794. for (var i = 0; i < layers.length; i++) {
  96795. var effectLayer = layers[i];
  96796. if (effectLayer.renderingGroupId === renderingGroupId) {
  96797. if (effectLayer.shouldRender()) {
  96798. effectLayer.render();
  96799. }
  96800. }
  96801. }
  96802. this._engine.setDepthBuffer(true);
  96803. }
  96804. };
  96805. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96806. if (this._renderEffects) {
  96807. this._draw(-1);
  96808. }
  96809. };
  96810. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96811. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96812. this._draw(index);
  96813. }
  96814. };
  96815. return EffectLayerSceneComponent;
  96816. }());
  96817. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96818. })(BABYLON || (BABYLON = {}));
  96819. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96820. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96821. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96822. s = arguments[i];
  96823. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96824. t[p] = s[p];
  96825. }
  96826. return t;
  96827. };
  96828. var BABYLON;
  96829. (function (BABYLON) {
  96830. /**
  96831. * The effect layer Helps adding post process effect blended with the main pass.
  96832. *
  96833. * This can be for instance use to generate glow or higlight effects on the scene.
  96834. *
  96835. * The effect layer class can not be used directly and is intented to inherited from to be
  96836. * customized per effects.
  96837. */
  96838. var EffectLayer = /** @class */ (function () {
  96839. /**
  96840. * Instantiates a new effect Layer and references it in the scene.
  96841. * @param name The name of the layer
  96842. * @param scene The scene to use the layer in
  96843. */
  96844. function EffectLayer(
  96845. /** The Friendly of the effect in the scene */
  96846. name, scene) {
  96847. this._vertexBuffers = {};
  96848. this._maxSize = 0;
  96849. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96850. this._shouldRender = true;
  96851. this._postProcesses = [];
  96852. this._textures = [];
  96853. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96854. /**
  96855. * The clear color of the texture used to generate the glow map.
  96856. */
  96857. this.neutralColor = new BABYLON.Color4();
  96858. /**
  96859. * Specifies wether the highlight layer is enabled or not.
  96860. */
  96861. this.isEnabled = true;
  96862. /**
  96863. * An event triggered when the effect layer has been disposed.
  96864. */
  96865. this.onDisposeObservable = new BABYLON.Observable();
  96866. /**
  96867. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96868. */
  96869. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96870. /**
  96871. * An event triggered when the generated texture is being merged in the scene.
  96872. */
  96873. this.onBeforeComposeObservable = new BABYLON.Observable();
  96874. /**
  96875. * An event triggered when the generated texture has been merged in the scene.
  96876. */
  96877. this.onAfterComposeObservable = new BABYLON.Observable();
  96878. /**
  96879. * An event triggered when the efffect layer changes its size.
  96880. */
  96881. this.onSizeChangedObservable = new BABYLON.Observable();
  96882. this.name = name;
  96883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96884. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96885. if (!component) {
  96886. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96887. this._scene._addComponent(component);
  96888. }
  96889. this._engine = this._scene.getEngine();
  96890. this._maxSize = this._engine.getCaps().maxTextureSize;
  96891. this._scene.effectLayers.push(this);
  96892. // Generate Buffers
  96893. this._generateIndexBuffer();
  96894. this._genrateVertexBuffer();
  96895. }
  96896. Object.defineProperty(EffectLayer.prototype, "camera", {
  96897. /**
  96898. * Gets the camera attached to the layer.
  96899. */
  96900. get: function () {
  96901. return this._effectLayerOptions.camera;
  96902. },
  96903. enumerable: true,
  96904. configurable: true
  96905. });
  96906. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96907. /**
  96908. * Gets the rendering group id the layer should render in.
  96909. */
  96910. get: function () {
  96911. return this._effectLayerOptions.renderingGroupId;
  96912. },
  96913. enumerable: true,
  96914. configurable: true
  96915. });
  96916. /**
  96917. * Initializes the effect layer with the required options.
  96918. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96919. */
  96920. EffectLayer.prototype._init = function (options) {
  96921. // Adapt options
  96922. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96923. this._setMainTextureSize();
  96924. this._createMainTexture();
  96925. this._createTextureAndPostProcesses();
  96926. this._mergeEffect = this._createMergeEffect();
  96927. };
  96928. /**
  96929. * Generates the index buffer of the full screen quad blending to the main canvas.
  96930. */
  96931. EffectLayer.prototype._generateIndexBuffer = function () {
  96932. // Indices
  96933. var indices = [];
  96934. indices.push(0);
  96935. indices.push(1);
  96936. indices.push(2);
  96937. indices.push(0);
  96938. indices.push(2);
  96939. indices.push(3);
  96940. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96941. };
  96942. /**
  96943. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96944. */
  96945. EffectLayer.prototype._genrateVertexBuffer = function () {
  96946. // VBO
  96947. var vertices = [];
  96948. vertices.push(1, 1);
  96949. vertices.push(-1, 1);
  96950. vertices.push(-1, -1);
  96951. vertices.push(1, -1);
  96952. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96953. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96954. };
  96955. /**
  96956. * Sets the main texture desired size which is the closest power of two
  96957. * of the engine canvas size.
  96958. */
  96959. EffectLayer.prototype._setMainTextureSize = function () {
  96960. if (this._effectLayerOptions.mainTextureFixedSize) {
  96961. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96962. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96963. }
  96964. else {
  96965. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96966. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96967. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96968. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96969. }
  96970. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96971. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96972. };
  96973. /**
  96974. * Creates the main texture for the effect layer.
  96975. */
  96976. EffectLayer.prototype._createMainTexture = function () {
  96977. var _this = this;
  96978. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96979. width: this._mainTextureDesiredSize.width,
  96980. height: this._mainTextureDesiredSize.height
  96981. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96982. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96983. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96984. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96985. this._mainTexture.anisotropicFilteringLevel = 1;
  96986. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96987. this._mainTexture.renderParticles = false;
  96988. this._mainTexture.renderList = null;
  96989. this._mainTexture.ignoreCameraViewport = true;
  96990. // Custom render function
  96991. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96992. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96993. var index;
  96994. var engine = _this._scene.getEngine();
  96995. if (depthOnlySubMeshes.length) {
  96996. engine.setColorWrite(false);
  96997. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96998. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96999. }
  97000. engine.setColorWrite(true);
  97001. }
  97002. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97003. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97004. }
  97005. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97006. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97007. }
  97008. for (index = 0; index < transparentSubMeshes.length; index++) {
  97009. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97010. }
  97011. };
  97012. this._mainTexture.onClearObservable.add(function (engine) {
  97013. engine.clear(_this.neutralColor, true, true, true);
  97014. });
  97015. };
  97016. /**
  97017. * Checks for the readiness of the element composing the layer.
  97018. * @param subMesh the mesh to check for
  97019. * @param useInstances specify wether or not to use instances to render the mesh
  97020. * @param emissiveTexture the associated emissive texture used to generate the glow
  97021. * @return true if ready otherwise, false
  97022. */
  97023. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97024. var material = subMesh.getMaterial();
  97025. if (!material) {
  97026. return false;
  97027. }
  97028. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97029. return false;
  97030. }
  97031. var defines = [];
  97032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97033. var mesh = subMesh.getMesh();
  97034. var uv1 = false;
  97035. var uv2 = false;
  97036. // Alpha test
  97037. if (material && material.needAlphaTesting()) {
  97038. var alphaTexture = material.getAlphaTestTexture();
  97039. if (alphaTexture) {
  97040. defines.push("#define ALPHATEST");
  97041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97042. alphaTexture.coordinatesIndex === 1) {
  97043. defines.push("#define DIFFUSEUV2");
  97044. uv2 = true;
  97045. }
  97046. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97047. defines.push("#define DIFFUSEUV1");
  97048. uv1 = true;
  97049. }
  97050. }
  97051. }
  97052. // Emissive
  97053. if (emissiveTexture) {
  97054. defines.push("#define EMISSIVE");
  97055. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97056. emissiveTexture.coordinatesIndex === 1) {
  97057. defines.push("#define EMISSIVEUV2");
  97058. uv2 = true;
  97059. }
  97060. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97061. defines.push("#define EMISSIVEUV1");
  97062. uv1 = true;
  97063. }
  97064. }
  97065. if (uv1) {
  97066. attribs.push(BABYLON.VertexBuffer.UVKind);
  97067. defines.push("#define UV1");
  97068. }
  97069. if (uv2) {
  97070. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97071. defines.push("#define UV2");
  97072. }
  97073. // Bones
  97074. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97075. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97076. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97077. if (mesh.numBoneInfluencers > 4) {
  97078. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97079. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97080. }
  97081. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97082. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97083. }
  97084. else {
  97085. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97086. }
  97087. // Morph targets
  97088. var manager = mesh.morphTargetManager;
  97089. var morphInfluencers = 0;
  97090. if (manager) {
  97091. if (manager.numInfluencers > 0) {
  97092. defines.push("#define MORPHTARGETS");
  97093. morphInfluencers = manager.numInfluencers;
  97094. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97095. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97096. }
  97097. }
  97098. // Instances
  97099. if (useInstances) {
  97100. defines.push("#define INSTANCES");
  97101. attribs.push("world0");
  97102. attribs.push("world1");
  97103. attribs.push("world2");
  97104. attribs.push("world3");
  97105. }
  97106. // Get correct effect
  97107. var join = defines.join("\n");
  97108. if (this._cachedDefines !== join) {
  97109. this._cachedDefines = join;
  97110. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97111. }
  97112. return this._effectLayerMapGenerationEffect.isReady();
  97113. };
  97114. /**
  97115. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97116. */
  97117. EffectLayer.prototype.render = function () {
  97118. var currentEffect = this._mergeEffect;
  97119. // Check
  97120. if (!currentEffect.isReady())
  97121. return;
  97122. for (var i = 0; i < this._postProcesses.length; i++) {
  97123. if (!this._postProcesses[i].isReady()) {
  97124. return;
  97125. }
  97126. }
  97127. var engine = this._scene.getEngine();
  97128. this.onBeforeComposeObservable.notifyObservers(this);
  97129. // Render
  97130. engine.enableEffect(currentEffect);
  97131. engine.setState(false);
  97132. // VBOs
  97133. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97134. // Cache
  97135. var previousAlphaMode = engine.getAlphaMode();
  97136. // Go Blend.
  97137. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97138. // Blends the map on the main canvas.
  97139. this._internalRender(currentEffect);
  97140. // Restore Alpha
  97141. engine.setAlphaMode(previousAlphaMode);
  97142. this.onAfterComposeObservable.notifyObservers(this);
  97143. // Handle size changes.
  97144. var size = this._mainTexture.getSize();
  97145. this._setMainTextureSize();
  97146. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97147. // Recreate RTT and post processes on size change.
  97148. this.onSizeChangedObservable.notifyObservers(this);
  97149. this._disposeTextureAndPostProcesses();
  97150. this._createMainTexture();
  97151. this._createTextureAndPostProcesses();
  97152. }
  97153. };
  97154. /**
  97155. * Determine if a given mesh will be used in the current effect.
  97156. * @param mesh mesh to test
  97157. * @returns true if the mesh will be used
  97158. */
  97159. EffectLayer.prototype.hasMesh = function (mesh) {
  97160. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97161. return true;
  97162. }
  97163. return false;
  97164. };
  97165. /**
  97166. * Returns true if the layer contains information to display, otherwise false.
  97167. * @returns true if the glow layer should be rendered
  97168. */
  97169. EffectLayer.prototype.shouldRender = function () {
  97170. return this.isEnabled && this._shouldRender;
  97171. };
  97172. /**
  97173. * Returns true if the mesh should render, otherwise false.
  97174. * @param mesh The mesh to render
  97175. * @returns true if it should render otherwise false
  97176. */
  97177. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97178. return true;
  97179. };
  97180. /**
  97181. * Returns true if the mesh should render, otherwise false.
  97182. * @param mesh The mesh to render
  97183. * @returns true if it should render otherwise false
  97184. */
  97185. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97186. return true;
  97187. };
  97188. /**
  97189. * Renders the submesh passed in parameter to the generation map.
  97190. */
  97191. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97192. var _this = this;
  97193. if (!this.shouldRender()) {
  97194. return;
  97195. }
  97196. var material = subMesh.getMaterial();
  97197. var mesh = subMesh.getRenderingMesh();
  97198. var scene = this._scene;
  97199. var engine = scene.getEngine();
  97200. if (!material) {
  97201. return;
  97202. }
  97203. // Do not block in blend mode.
  97204. if (material.needAlphaBlendingForMesh(mesh)) {
  97205. return;
  97206. }
  97207. // Culling
  97208. engine.setState(material.backFaceCulling);
  97209. // Managing instances
  97210. var batch = mesh._getInstancesRenderList(subMesh._id);
  97211. if (batch.mustReturn) {
  97212. return;
  97213. }
  97214. // Early Exit per mesh
  97215. if (!this._shouldRenderMesh(mesh)) {
  97216. return;
  97217. }
  97218. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97219. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97220. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97221. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97222. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97223. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97224. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97225. // Alpha test
  97226. if (material && material.needAlphaTesting()) {
  97227. var alphaTexture = material.getAlphaTestTexture();
  97228. if (alphaTexture) {
  97229. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97230. var textureMatrix = alphaTexture.getTextureMatrix();
  97231. if (textureMatrix) {
  97232. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97233. }
  97234. }
  97235. }
  97236. // Glow emissive only
  97237. if (this._emissiveTextureAndColor.texture) {
  97238. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97239. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97240. }
  97241. // Bones
  97242. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97243. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97244. }
  97245. // Morph targets
  97246. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97247. // Draw
  97248. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97249. }
  97250. else {
  97251. // Need to reset refresh rate of the main map
  97252. this._mainTexture.resetRefreshCounter();
  97253. }
  97254. };
  97255. /**
  97256. * Rebuild the required buffers.
  97257. * @hidden Internal use only.
  97258. */
  97259. EffectLayer.prototype._rebuild = function () {
  97260. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97261. if (vb) {
  97262. vb._rebuild();
  97263. }
  97264. this._generateIndexBuffer();
  97265. };
  97266. /**
  97267. * Dispose only the render target textures and post process.
  97268. */
  97269. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97270. this._mainTexture.dispose();
  97271. for (var i = 0; i < this._postProcesses.length; i++) {
  97272. if (this._postProcesses[i]) {
  97273. this._postProcesses[i].dispose();
  97274. }
  97275. }
  97276. this._postProcesses = [];
  97277. for (var i = 0; i < this._textures.length; i++) {
  97278. if (this._textures[i]) {
  97279. this._textures[i].dispose();
  97280. }
  97281. }
  97282. this._textures = [];
  97283. };
  97284. /**
  97285. * Dispose the highlight layer and free resources.
  97286. */
  97287. EffectLayer.prototype.dispose = function () {
  97288. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97289. if (vertexBuffer) {
  97290. vertexBuffer.dispose();
  97291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97292. }
  97293. if (this._indexBuffer) {
  97294. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97295. this._indexBuffer = null;
  97296. }
  97297. // Clean textures and post processes
  97298. this._disposeTextureAndPostProcesses();
  97299. // Remove from scene
  97300. var index = this._scene.effectLayers.indexOf(this, 0);
  97301. if (index > -1) {
  97302. this._scene.effectLayers.splice(index, 1);
  97303. }
  97304. // Callback
  97305. this.onDisposeObservable.notifyObservers(this);
  97306. this.onDisposeObservable.clear();
  97307. this.onBeforeRenderMainTextureObservable.clear();
  97308. this.onBeforeComposeObservable.clear();
  97309. this.onAfterComposeObservable.clear();
  97310. this.onSizeChangedObservable.clear();
  97311. };
  97312. /**
  97313. * Gets the class name of the effect layer
  97314. * @returns the string with the class name of the effect layer
  97315. */
  97316. EffectLayer.prototype.getClassName = function () {
  97317. return "EffectLayer";
  97318. };
  97319. /**
  97320. * Creates an effect layer from parsed effect layer data
  97321. * @param parsedEffectLayer defines effect layer data
  97322. * @param scene defines the current scene
  97323. * @param rootUrl defines the root URL containing the effect layer information
  97324. * @returns a parsed effect Layer
  97325. */
  97326. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97327. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97328. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97329. };
  97330. __decorate([
  97331. BABYLON.serialize()
  97332. ], EffectLayer.prototype, "name", void 0);
  97333. __decorate([
  97334. BABYLON.serializeAsColor4()
  97335. ], EffectLayer.prototype, "neutralColor", void 0);
  97336. __decorate([
  97337. BABYLON.serialize()
  97338. ], EffectLayer.prototype, "isEnabled", void 0);
  97339. __decorate([
  97340. BABYLON.serializeAsCameraReference()
  97341. ], EffectLayer.prototype, "camera", null);
  97342. __decorate([
  97343. BABYLON.serialize()
  97344. ], EffectLayer.prototype, "renderingGroupId", null);
  97345. return EffectLayer;
  97346. }());
  97347. BABYLON.EffectLayer = EffectLayer;
  97348. })(BABYLON || (BABYLON = {}));
  97349. //# sourceMappingURL=babylon.effectLayer.js.map
  97350. var BABYLON;
  97351. (function (BABYLON) {
  97352. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97353. for (var index = 0; index < this.effectLayers.length; index++) {
  97354. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97355. return this.effectLayers[index];
  97356. }
  97357. }
  97358. return null;
  97359. };
  97360. /**
  97361. * Special Glow Blur post process only blurring the alpha channel
  97362. * It enforces keeping the most luminous color in the color channel.
  97363. */
  97364. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97365. __extends(GlowBlurPostProcess, _super);
  97366. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97368. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97369. _this.direction = direction;
  97370. _this.kernel = kernel;
  97371. _this.onApplyObservable.add(function (effect) {
  97372. effect.setFloat2("screenSize", _this.width, _this.height);
  97373. effect.setVector2("direction", _this.direction);
  97374. effect.setFloat("blurWidth", _this.kernel);
  97375. });
  97376. return _this;
  97377. }
  97378. return GlowBlurPostProcess;
  97379. }(BABYLON.PostProcess));
  97380. /**
  97381. * The highlight layer Helps adding a glow effect around a mesh.
  97382. *
  97383. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97384. * glowy meshes to your scene.
  97385. *
  97386. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97387. */
  97388. var HighlightLayer = /** @class */ (function (_super) {
  97389. __extends(HighlightLayer, _super);
  97390. /**
  97391. * Instantiates a new highlight Layer and references it to the scene..
  97392. * @param name The name of the layer
  97393. * @param scene The scene to use the layer in
  97394. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97395. */
  97396. function HighlightLayer(name, scene, options) {
  97397. var _this = _super.call(this, name, scene) || this;
  97398. _this.name = name;
  97399. /**
  97400. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97401. */
  97402. _this.innerGlow = true;
  97403. /**
  97404. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97405. */
  97406. _this.outerGlow = true;
  97407. /**
  97408. * An event triggered when the highlight layer is being blurred.
  97409. */
  97410. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97411. /**
  97412. * An event triggered when the highlight layer has been blurred.
  97413. */
  97414. _this.onAfterBlurObservable = new BABYLON.Observable();
  97415. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97416. _this._meshes = {};
  97417. _this._excludedMeshes = {};
  97418. _this.neutralColor = HighlightLayer.NeutralColor;
  97419. // Warn on stencil
  97420. if (!_this._engine.isStencilEnable) {
  97421. 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 }");
  97422. }
  97423. // Adapt options
  97424. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97425. // Initialize the layer
  97426. _this._init({
  97427. alphaBlendingMode: _this._options.alphaBlendingMode,
  97428. camera: _this._options.camera,
  97429. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97430. mainTextureRatio: _this._options.mainTextureRatio,
  97431. renderingGroupId: _this._options.renderingGroupId
  97432. });
  97433. // Do not render as long as no meshes have been added
  97434. _this._shouldRender = false;
  97435. return _this;
  97436. }
  97437. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97438. /**
  97439. * Gets the horizontal size of the blur.
  97440. */
  97441. get: function () {
  97442. return this._horizontalBlurPostprocess.kernel;
  97443. },
  97444. /**
  97445. * Specifies the horizontal size of the blur.
  97446. */
  97447. set: function (value) {
  97448. this._horizontalBlurPostprocess.kernel = value;
  97449. },
  97450. enumerable: true,
  97451. configurable: true
  97452. });
  97453. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97454. /**
  97455. * Gets the vertical size of the blur.
  97456. */
  97457. get: function () {
  97458. return this._verticalBlurPostprocess.kernel;
  97459. },
  97460. /**
  97461. * Specifies the vertical size of the blur.
  97462. */
  97463. set: function (value) {
  97464. this._verticalBlurPostprocess.kernel = value;
  97465. },
  97466. enumerable: true,
  97467. configurable: true
  97468. });
  97469. /**
  97470. * Get the effect name of the layer.
  97471. * @return The effect name
  97472. */
  97473. HighlightLayer.prototype.getEffectName = function () {
  97474. return HighlightLayer.EffectName;
  97475. };
  97476. /**
  97477. * Create the merge effect. This is the shader use to blit the information back
  97478. * to the main canvas at the end of the scene rendering.
  97479. */
  97480. HighlightLayer.prototype._createMergeEffect = function () {
  97481. // Effect
  97482. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97483. };
  97484. /**
  97485. * Creates the render target textures and post processes used in the highlight layer.
  97486. */
  97487. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97488. var _this = this;
  97489. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97490. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97491. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97492. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97493. var textureType = 0;
  97494. if (this._engine.getCaps().textureHalfFloatRender) {
  97495. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97496. }
  97497. else {
  97498. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97499. }
  97500. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97501. width: blurTextureWidth,
  97502. height: blurTextureHeight
  97503. }, this._scene, false, true, textureType);
  97504. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97505. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97506. this._blurTexture.anisotropicFilteringLevel = 16;
  97507. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97508. this._blurTexture.renderParticles = false;
  97509. this._blurTexture.ignoreCameraViewport = true;
  97510. this._textures = [this._blurTexture];
  97511. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97512. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97513. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97514. effect.setTexture("textureSampler", _this._mainTexture);
  97515. });
  97516. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97517. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97518. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97519. });
  97520. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97521. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97522. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97523. });
  97524. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97525. }
  97526. else {
  97527. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97528. width: blurTextureWidth,
  97529. height: blurTextureHeight
  97530. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97531. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97532. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97533. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97534. effect.setTexture("textureSampler", _this._mainTexture);
  97535. });
  97536. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97537. width: blurTextureWidth,
  97538. height: blurTextureHeight
  97539. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97540. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97541. }
  97542. this._mainTexture.onAfterUnbindObservable.add(function () {
  97543. _this.onBeforeBlurObservable.notifyObservers(_this);
  97544. var internalTexture = _this._blurTexture.getInternalTexture();
  97545. if (internalTexture) {
  97546. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97547. }
  97548. _this.onAfterBlurObservable.notifyObservers(_this);
  97549. });
  97550. // Prevent autoClear.
  97551. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97552. };
  97553. /**
  97554. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97555. */
  97556. HighlightLayer.prototype.needStencil = function () {
  97557. return true;
  97558. };
  97559. /**
  97560. * Checks for the readiness of the element composing the layer.
  97561. * @param subMesh the mesh to check for
  97562. * @param useInstances specify wether or not to use instances to render the mesh
  97563. * @param emissiveTexture the associated emissive texture used to generate the glow
  97564. * @return true if ready otherwise, false
  97565. */
  97566. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97567. var material = subMesh.getMaterial();
  97568. var mesh = subMesh.getRenderingMesh();
  97569. if (!material || !mesh || !this._meshes) {
  97570. return false;
  97571. }
  97572. var emissiveTexture = null;
  97573. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97574. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97575. emissiveTexture = material.emissiveTexture;
  97576. }
  97577. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97578. };
  97579. /**
  97580. * Implementation specific of rendering the generating effect on the main canvas.
  97581. * @param effect The effect used to render through
  97582. */
  97583. HighlightLayer.prototype._internalRender = function (effect) {
  97584. // Texture
  97585. effect.setTexture("textureSampler", this._blurTexture);
  97586. // Cache
  97587. var engine = this._engine;
  97588. var previousStencilBuffer = engine.getStencilBuffer();
  97589. var previousStencilFunction = engine.getStencilFunction();
  97590. var previousStencilMask = engine.getStencilMask();
  97591. var previousStencilOperationPass = engine.getStencilOperationPass();
  97592. var previousStencilOperationFail = engine.getStencilOperationFail();
  97593. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97594. var previousStencilReference = engine.getStencilFunctionReference();
  97595. // Stencil operations
  97596. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97597. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97598. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97599. // Draw order
  97600. engine.setStencilMask(0x00);
  97601. engine.setStencilBuffer(true);
  97602. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97603. // 2 passes inner outer
  97604. if (this.outerGlow) {
  97605. effect.setFloat("offset", 0);
  97606. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97607. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97608. }
  97609. if (this.innerGlow) {
  97610. effect.setFloat("offset", 1);
  97611. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97612. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97613. }
  97614. // Restore Cache
  97615. engine.setStencilFunction(previousStencilFunction);
  97616. engine.setStencilMask(previousStencilMask);
  97617. engine.setStencilBuffer(previousStencilBuffer);
  97618. engine.setStencilOperationPass(previousStencilOperationPass);
  97619. engine.setStencilOperationFail(previousStencilOperationFail);
  97620. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97621. engine.setStencilFunctionReference(previousStencilReference);
  97622. };
  97623. /**
  97624. * Returns true if the layer contains information to display, otherwise false.
  97625. */
  97626. HighlightLayer.prototype.shouldRender = function () {
  97627. if (_super.prototype.shouldRender.call(this)) {
  97628. return this._meshes ? true : false;
  97629. }
  97630. return false;
  97631. };
  97632. /**
  97633. * Returns true if the mesh should render, otherwise false.
  97634. * @param mesh The mesh to render
  97635. * @returns true if it should render otherwise false
  97636. */
  97637. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97638. // Excluded Mesh
  97639. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97640. return false;
  97641. }
  97642. ;
  97643. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97644. return false;
  97645. }
  97646. return true;
  97647. };
  97648. /**
  97649. * Sets the required values for both the emissive texture and and the main color.
  97650. */
  97651. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97652. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97653. if (highlightLayerMesh) {
  97654. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97655. }
  97656. else {
  97657. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97658. }
  97659. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97660. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97661. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97662. }
  97663. else {
  97664. this._emissiveTextureAndColor.texture = null;
  97665. }
  97666. };
  97667. /**
  97668. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97669. * @param mesh The mesh to exclude from the highlight layer
  97670. */
  97671. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97672. if (!this._excludedMeshes) {
  97673. return;
  97674. }
  97675. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97676. if (!meshExcluded) {
  97677. this._excludedMeshes[mesh.uniqueId] = {
  97678. mesh: mesh,
  97679. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97680. mesh.getEngine().setStencilBuffer(false);
  97681. }),
  97682. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97683. mesh.getEngine().setStencilBuffer(true);
  97684. }),
  97685. };
  97686. }
  97687. };
  97688. /**
  97689. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97690. * @param mesh The mesh to highlight
  97691. */
  97692. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97693. if (!this._excludedMeshes) {
  97694. return;
  97695. }
  97696. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97697. if (meshExcluded) {
  97698. if (meshExcluded.beforeRender) {
  97699. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97700. }
  97701. if (meshExcluded.afterRender) {
  97702. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97703. }
  97704. }
  97705. this._excludedMeshes[mesh.uniqueId] = null;
  97706. };
  97707. /**
  97708. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97709. * @param mesh mesh to test
  97710. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97711. */
  97712. HighlightLayer.prototype.hasMesh = function (mesh) {
  97713. if (!this._meshes) {
  97714. return false;
  97715. }
  97716. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97717. return false;
  97718. }
  97719. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97720. };
  97721. /**
  97722. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97723. * @param mesh The mesh to highlight
  97724. * @param color The color of the highlight
  97725. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97726. */
  97727. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97728. var _this = this;
  97729. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97730. if (!this._meshes) {
  97731. return;
  97732. }
  97733. var meshHighlight = this._meshes[mesh.uniqueId];
  97734. if (meshHighlight) {
  97735. meshHighlight.color = color;
  97736. }
  97737. else {
  97738. this._meshes[mesh.uniqueId] = {
  97739. mesh: mesh,
  97740. color: color,
  97741. // Lambda required for capture due to Observable this context
  97742. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97743. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97744. _this._defaultStencilReference(mesh);
  97745. }
  97746. else {
  97747. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97748. }
  97749. }),
  97750. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97751. glowEmissiveOnly: glowEmissiveOnly
  97752. };
  97753. mesh.onDisposeObservable.add(function () {
  97754. _this._disposeMesh(mesh);
  97755. });
  97756. }
  97757. this._shouldRender = true;
  97758. };
  97759. /**
  97760. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97761. * @param mesh The mesh to highlight
  97762. */
  97763. HighlightLayer.prototype.removeMesh = function (mesh) {
  97764. if (!this._meshes) {
  97765. return;
  97766. }
  97767. var meshHighlight = this._meshes[mesh.uniqueId];
  97768. if (meshHighlight) {
  97769. if (meshHighlight.observerHighlight) {
  97770. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97771. }
  97772. if (meshHighlight.observerDefault) {
  97773. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97774. }
  97775. delete this._meshes[mesh.uniqueId];
  97776. }
  97777. this._shouldRender = false;
  97778. for (var meshHighlightToCheck in this._meshes) {
  97779. if (this._meshes[meshHighlightToCheck]) {
  97780. this._shouldRender = true;
  97781. break;
  97782. }
  97783. }
  97784. };
  97785. /**
  97786. * Force the stencil to the normal expected value for none glowing parts
  97787. */
  97788. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97789. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97790. };
  97791. /**
  97792. * Free any resources and references associated to a mesh.
  97793. * Internal use
  97794. * @param mesh The mesh to free.
  97795. */
  97796. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97797. this.removeMesh(mesh);
  97798. this.removeExcludedMesh(mesh);
  97799. };
  97800. /**
  97801. * Dispose the highlight layer and free resources.
  97802. */
  97803. HighlightLayer.prototype.dispose = function () {
  97804. if (this._meshes) {
  97805. // Clean mesh references
  97806. for (var id in this._meshes) {
  97807. var meshHighlight = this._meshes[id];
  97808. if (meshHighlight && meshHighlight.mesh) {
  97809. if (meshHighlight.observerHighlight) {
  97810. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97811. }
  97812. if (meshHighlight.observerDefault) {
  97813. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97814. }
  97815. }
  97816. }
  97817. this._meshes = null;
  97818. }
  97819. if (this._excludedMeshes) {
  97820. for (var id in this._excludedMeshes) {
  97821. var meshHighlight = this._excludedMeshes[id];
  97822. if (meshHighlight) {
  97823. if (meshHighlight.beforeRender) {
  97824. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97825. }
  97826. if (meshHighlight.afterRender) {
  97827. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97828. }
  97829. }
  97830. }
  97831. this._excludedMeshes = null;
  97832. }
  97833. _super.prototype.dispose.call(this);
  97834. };
  97835. /**
  97836. * Gets the class name of the effect layer
  97837. * @returns the string with the class name of the effect layer
  97838. */
  97839. HighlightLayer.prototype.getClassName = function () {
  97840. return "HighlightLayer";
  97841. };
  97842. /**
  97843. * Serializes this Highlight layer
  97844. * @returns a serialized Highlight layer object
  97845. */
  97846. HighlightLayer.prototype.serialize = function () {
  97847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97848. serializationObject.customType = "BABYLON.HighlightLayer";
  97849. // Highlighted meshes
  97850. serializationObject.meshes = [];
  97851. if (this._meshes) {
  97852. for (var m in this._meshes) {
  97853. var mesh = this._meshes[m];
  97854. if (mesh) {
  97855. serializationObject.meshes.push({
  97856. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97857. color: mesh.color.asArray(),
  97858. meshId: mesh.mesh.id
  97859. });
  97860. }
  97861. }
  97862. }
  97863. // Excluded meshes
  97864. serializationObject.excludedMeshes = [];
  97865. if (this._excludedMeshes) {
  97866. for (var e in this._excludedMeshes) {
  97867. var excludedMesh = this._excludedMeshes[e];
  97868. if (excludedMesh) {
  97869. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97870. }
  97871. }
  97872. }
  97873. return serializationObject;
  97874. };
  97875. /**
  97876. * Creates a Highlight layer from parsed Highlight layer data
  97877. * @param parsedHightlightLayer defines the Highlight layer data
  97878. * @param scene defines the current scene
  97879. * @param rootUrl defines the root URL containing the Highlight layer information
  97880. * @returns a parsed Highlight layer
  97881. */
  97882. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97883. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97884. var index;
  97885. // Excluded meshes
  97886. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97887. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97888. if (mesh) {
  97889. hl.addExcludedMesh(mesh);
  97890. }
  97891. }
  97892. // Included meshes
  97893. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97894. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97895. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97896. if (mesh) {
  97897. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97898. }
  97899. }
  97900. return hl;
  97901. };
  97902. /**
  97903. * Effect Name of the highlight layer.
  97904. */
  97905. HighlightLayer.EffectName = "HighlightLayer";
  97906. /**
  97907. * The neutral color used during the preparation of the glow effect.
  97908. * This is black by default as the blend operation is a blend operation.
  97909. */
  97910. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97911. /**
  97912. * Stencil value used for glowing meshes.
  97913. */
  97914. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97915. /**
  97916. * Stencil value used for the other meshes in the scene.
  97917. */
  97918. HighlightLayer.NormalMeshStencilReference = 0x01;
  97919. __decorate([
  97920. BABYLON.serialize()
  97921. ], HighlightLayer.prototype, "innerGlow", void 0);
  97922. __decorate([
  97923. BABYLON.serialize()
  97924. ], HighlightLayer.prototype, "outerGlow", void 0);
  97925. __decorate([
  97926. BABYLON.serialize()
  97927. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97928. __decorate([
  97929. BABYLON.serialize()
  97930. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97931. __decorate([
  97932. BABYLON.serialize("options")
  97933. ], HighlightLayer.prototype, "_options", void 0);
  97934. return HighlightLayer;
  97935. }(BABYLON.EffectLayer));
  97936. BABYLON.HighlightLayer = HighlightLayer;
  97937. })(BABYLON || (BABYLON = {}));
  97938. //# sourceMappingURL=babylon.highlightLayer.js.map
  97939. var BABYLON;
  97940. (function (BABYLON) {
  97941. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97942. for (var index = 0; index < this.effectLayers.length; index++) {
  97943. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97944. return this.effectLayers[index];
  97945. }
  97946. }
  97947. return null;
  97948. };
  97949. /**
  97950. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97951. *
  97952. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97953. * glowy meshes to your scene.
  97954. *
  97955. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97956. */
  97957. var GlowLayer = /** @class */ (function (_super) {
  97958. __extends(GlowLayer, _super);
  97959. /**
  97960. * Instantiates a new glow Layer and references it to the scene.
  97961. * @param name The name of the layer
  97962. * @param scene The scene to use the layer in
  97963. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97964. */
  97965. function GlowLayer(name, scene, options) {
  97966. var _this = _super.call(this, name, scene) || this;
  97967. _this._intensity = 1.0;
  97968. _this._includedOnlyMeshes = [];
  97969. _this._excludedMeshes = [];
  97970. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97971. // Adapt options
  97972. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97973. // Initialize the layer
  97974. _this._init({
  97975. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97976. camera: _this._options.camera,
  97977. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97978. mainTextureRatio: _this._options.mainTextureRatio,
  97979. renderingGroupId: _this._options.renderingGroupId
  97980. });
  97981. return _this;
  97982. }
  97983. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97984. /**
  97985. * Gets the kernel size of the blur.
  97986. */
  97987. get: function () {
  97988. return this._horizontalBlurPostprocess1.kernel;
  97989. },
  97990. /**
  97991. * Sets the kernel size of the blur.
  97992. */
  97993. set: function (value) {
  97994. this._horizontalBlurPostprocess1.kernel = value;
  97995. this._verticalBlurPostprocess1.kernel = value;
  97996. this._horizontalBlurPostprocess2.kernel = value;
  97997. this._verticalBlurPostprocess2.kernel = value;
  97998. },
  97999. enumerable: true,
  98000. configurable: true
  98001. });
  98002. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98003. /**
  98004. * Gets the glow intensity.
  98005. */
  98006. get: function () {
  98007. return this._intensity;
  98008. },
  98009. /**
  98010. * Sets the glow intensity.
  98011. */
  98012. set: function (value) {
  98013. this._intensity = value;
  98014. },
  98015. enumerable: true,
  98016. configurable: true
  98017. });
  98018. /**
  98019. * Get the effect name of the layer.
  98020. * @return The effect name
  98021. */
  98022. GlowLayer.prototype.getEffectName = function () {
  98023. return GlowLayer.EffectName;
  98024. };
  98025. /**
  98026. * Create the merge effect. This is the shader use to blit the information back
  98027. * to the main canvas at the end of the scene rendering.
  98028. */
  98029. GlowLayer.prototype._createMergeEffect = function () {
  98030. // Effect
  98031. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98032. };
  98033. /**
  98034. * Creates the render target textures and post processes used in the glow layer.
  98035. */
  98036. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98037. var _this = this;
  98038. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98039. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98040. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98041. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98042. var textureType = 0;
  98043. if (this._engine.getCaps().textureHalfFloatRender) {
  98044. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98045. }
  98046. else {
  98047. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98048. }
  98049. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98050. width: blurTextureWidth,
  98051. height: blurTextureHeight
  98052. }, this._scene, false, true, textureType);
  98053. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98054. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98055. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98056. this._blurTexture1.renderParticles = false;
  98057. this._blurTexture1.ignoreCameraViewport = true;
  98058. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98059. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98060. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98061. width: blurTextureWidth2,
  98062. height: blurTextureHeight2
  98063. }, this._scene, false, true, textureType);
  98064. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98065. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98066. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98067. this._blurTexture2.renderParticles = false;
  98068. this._blurTexture2.ignoreCameraViewport = true;
  98069. this._textures = [this._blurTexture1, this._blurTexture2];
  98070. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98071. width: blurTextureWidth,
  98072. height: blurTextureHeight
  98073. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98074. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98075. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98076. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98077. effect.setTexture("textureSampler", _this._mainTexture);
  98078. });
  98079. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98080. width: blurTextureWidth,
  98081. height: blurTextureHeight
  98082. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98083. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98084. width: blurTextureWidth2,
  98085. height: blurTextureHeight2
  98086. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98087. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98088. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98089. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98090. effect.setTexture("textureSampler", _this._blurTexture1);
  98091. });
  98092. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98093. width: blurTextureWidth2,
  98094. height: blurTextureHeight2
  98095. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98096. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98097. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98098. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98099. this._mainTexture.samples = this._options.mainTextureSamples;
  98100. this._mainTexture.onAfterUnbindObservable.add(function () {
  98101. var internalTexture = _this._blurTexture1.getInternalTexture();
  98102. if (internalTexture) {
  98103. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98104. internalTexture = _this._blurTexture2.getInternalTexture();
  98105. if (internalTexture) {
  98106. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98107. }
  98108. }
  98109. });
  98110. // Prevent autoClear.
  98111. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98112. };
  98113. /**
  98114. * Checks for the readiness of the element composing the layer.
  98115. * @param subMesh the mesh to check for
  98116. * @param useInstances specify wether or not to use instances to render the mesh
  98117. * @param emissiveTexture the associated emissive texture used to generate the glow
  98118. * @return true if ready otherwise, false
  98119. */
  98120. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98121. var material = subMesh.getMaterial();
  98122. var mesh = subMesh.getRenderingMesh();
  98123. if (!material || !mesh) {
  98124. return false;
  98125. }
  98126. var emissiveTexture = material.emissiveTexture;
  98127. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98128. };
  98129. /**
  98130. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98131. */
  98132. GlowLayer.prototype.needStencil = function () {
  98133. return false;
  98134. };
  98135. /**
  98136. * Implementation specific of rendering the generating effect on the main canvas.
  98137. * @param effect The effect used to render through
  98138. */
  98139. GlowLayer.prototype._internalRender = function (effect) {
  98140. // Texture
  98141. effect.setTexture("textureSampler", this._blurTexture1);
  98142. effect.setTexture("textureSampler2", this._blurTexture2);
  98143. effect.setFloat("offset", this._intensity);
  98144. // Cache
  98145. var engine = this._engine;
  98146. var previousStencilBuffer = engine.getStencilBuffer();
  98147. // Draw order
  98148. engine.setStencilBuffer(false);
  98149. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98150. // Draw order
  98151. engine.setStencilBuffer(previousStencilBuffer);
  98152. };
  98153. /**
  98154. * Sets the required values for both the emissive texture and and the main color.
  98155. */
  98156. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98157. var textureLevel = 1.0;
  98158. if (this.customEmissiveTextureSelector) {
  98159. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98160. }
  98161. else {
  98162. if (material) {
  98163. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98164. if (this._emissiveTextureAndColor.texture) {
  98165. textureLevel = this._emissiveTextureAndColor.texture.level;
  98166. }
  98167. }
  98168. else {
  98169. this._emissiveTextureAndColor.texture = null;
  98170. }
  98171. }
  98172. if (this.customEmissiveColorSelector) {
  98173. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98174. }
  98175. else {
  98176. if (material.emissiveColor) {
  98177. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98178. }
  98179. else {
  98180. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98181. }
  98182. }
  98183. };
  98184. /**
  98185. * Returns true if the mesh should render, otherwise false.
  98186. * @param mesh The mesh to render
  98187. * @returns true if it should render otherwise false
  98188. */
  98189. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98190. return this.hasMesh(mesh);
  98191. };
  98192. /**
  98193. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98194. * @param mesh The mesh to exclude from the glow layer
  98195. */
  98196. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98197. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98198. this._excludedMeshes.push(mesh.uniqueId);
  98199. }
  98200. };
  98201. /**
  98202. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98203. * @param mesh The mesh to remove
  98204. */
  98205. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98206. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98207. if (index !== -1) {
  98208. this._excludedMeshes.splice(index, 1);
  98209. }
  98210. };
  98211. /**
  98212. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98213. * @param mesh The mesh to include in the glow layer
  98214. */
  98215. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98216. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98217. this._includedOnlyMeshes.push(mesh.uniqueId);
  98218. }
  98219. };
  98220. /**
  98221. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98222. * @param mesh The mesh to remove
  98223. */
  98224. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98225. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98226. if (index !== -1) {
  98227. this._includedOnlyMeshes.splice(index, 1);
  98228. }
  98229. };
  98230. /**
  98231. * Determine if a given mesh will be used in the glow layer
  98232. * @param mesh The mesh to test
  98233. * @returns true if the mesh will be highlighted by the current glow layer
  98234. */
  98235. GlowLayer.prototype.hasMesh = function (mesh) {
  98236. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98237. return false;
  98238. }
  98239. // Included Mesh
  98240. if (this._includedOnlyMeshes.length) {
  98241. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98242. }
  98243. ;
  98244. // Excluded Mesh
  98245. if (this._excludedMeshes.length) {
  98246. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98247. }
  98248. ;
  98249. return true;
  98250. };
  98251. /**
  98252. * Free any resources and references associated to a mesh.
  98253. * Internal use
  98254. * @param mesh The mesh to free.
  98255. */
  98256. GlowLayer.prototype._disposeMesh = function (mesh) {
  98257. this.removeIncludedOnlyMesh(mesh);
  98258. this.removeExcludedMesh(mesh);
  98259. };
  98260. /**
  98261. * Gets the class name of the effect layer
  98262. * @returns the string with the class name of the effect layer
  98263. */
  98264. GlowLayer.prototype.getClassName = function () {
  98265. return "GlowLayer";
  98266. };
  98267. /**
  98268. * Serializes this glow layer
  98269. * @returns a serialized glow layer object
  98270. */
  98271. GlowLayer.prototype.serialize = function () {
  98272. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98273. serializationObject.customType = "BABYLON.GlowLayer";
  98274. var index;
  98275. // Included meshes
  98276. serializationObject.includedMeshes = [];
  98277. if (this._includedOnlyMeshes.length) {
  98278. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98279. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98280. if (mesh) {
  98281. serializationObject.includedMeshes.push(mesh.id);
  98282. }
  98283. }
  98284. }
  98285. // Excluded meshes
  98286. serializationObject.excludedMeshes = [];
  98287. if (this._excludedMeshes.length) {
  98288. for (index = 0; index < this._excludedMeshes.length; index++) {
  98289. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98290. if (mesh) {
  98291. serializationObject.excludedMeshes.push(mesh.id);
  98292. }
  98293. }
  98294. }
  98295. return serializationObject;
  98296. };
  98297. /**
  98298. * Creates a Glow Layer from parsed glow layer data
  98299. * @param parsedGlowLayer defines glow layer data
  98300. * @param scene defines the current scene
  98301. * @param rootUrl defines the root URL containing the glow layer information
  98302. * @returns a parsed Glow Layer
  98303. */
  98304. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98305. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98306. var index;
  98307. // Excluded meshes
  98308. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98309. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98310. if (mesh) {
  98311. gl.addExcludedMesh(mesh);
  98312. }
  98313. }
  98314. // Included meshes
  98315. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98316. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98317. if (mesh) {
  98318. gl.addIncludedOnlyMesh(mesh);
  98319. }
  98320. }
  98321. return gl;
  98322. };
  98323. /**
  98324. * Effect Name of the layer.
  98325. */
  98326. GlowLayer.EffectName = "GlowLayer";
  98327. /**
  98328. * The default blur kernel size used for the glow.
  98329. */
  98330. GlowLayer.DefaultBlurKernelSize = 32;
  98331. /**
  98332. * The default texture size ratio used for the glow.
  98333. */
  98334. GlowLayer.DefaultTextureRatio = 0.5;
  98335. __decorate([
  98336. BABYLON.serialize()
  98337. ], GlowLayer.prototype, "blurKernelSize", null);
  98338. __decorate([
  98339. BABYLON.serialize()
  98340. ], GlowLayer.prototype, "intensity", null);
  98341. __decorate([
  98342. BABYLON.serialize("options")
  98343. ], GlowLayer.prototype, "_options", void 0);
  98344. return GlowLayer;
  98345. }(BABYLON.EffectLayer));
  98346. BABYLON.GlowLayer = GlowLayer;
  98347. })(BABYLON || (BABYLON = {}));
  98348. //# sourceMappingURL=babylon.glowLayer.js.map
  98349. var BABYLON;
  98350. (function (BABYLON) {
  98351. /**
  98352. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98353. */
  98354. var AssetTaskState;
  98355. (function (AssetTaskState) {
  98356. /**
  98357. * Initialization
  98358. */
  98359. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98360. /**
  98361. * Running
  98362. */
  98363. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98364. /**
  98365. * Done
  98366. */
  98367. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98368. /**
  98369. * Error
  98370. */
  98371. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98372. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98373. /**
  98374. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98375. */
  98376. var AbstractAssetTask = /** @class */ (function () {
  98377. /**
  98378. * Creates a new {BABYLON.AssetsManager}
  98379. * @param name defines the name of the task
  98380. */
  98381. function AbstractAssetTask(
  98382. /**
  98383. * Task name
  98384. */ name) {
  98385. this.name = name;
  98386. this._isCompleted = false;
  98387. this._taskState = AssetTaskState.INIT;
  98388. }
  98389. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98390. /**
  98391. * Get if the task is completed
  98392. */
  98393. get: function () {
  98394. return this._isCompleted;
  98395. },
  98396. enumerable: true,
  98397. configurable: true
  98398. });
  98399. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98400. /**
  98401. * Gets the current state of the task
  98402. */
  98403. get: function () {
  98404. return this._taskState;
  98405. },
  98406. enumerable: true,
  98407. configurable: true
  98408. });
  98409. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98410. /**
  98411. * Gets the current error object (if task is in error)
  98412. */
  98413. get: function () {
  98414. return this._errorObject;
  98415. },
  98416. enumerable: true,
  98417. configurable: true
  98418. });
  98419. /**
  98420. * Internal only
  98421. * @hidden
  98422. */
  98423. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98424. if (this._errorObject) {
  98425. return;
  98426. }
  98427. this._errorObject = {
  98428. message: message,
  98429. exception: exception
  98430. };
  98431. };
  98432. /**
  98433. * Execute the current task
  98434. * @param scene defines the scene where you want your assets to be loaded
  98435. * @param onSuccess is a callback called when the task is successfully executed
  98436. * @param onError is a callback called if an error occurs
  98437. */
  98438. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98439. var _this = this;
  98440. this._taskState = AssetTaskState.RUNNING;
  98441. this.runTask(scene, function () {
  98442. _this.onDoneCallback(onSuccess, onError);
  98443. }, function (msg, exception) {
  98444. _this.onErrorCallback(onError, msg, exception);
  98445. });
  98446. };
  98447. /**
  98448. * Execute the current task
  98449. * @param scene defines the scene where you want your assets to be loaded
  98450. * @param onSuccess is a callback called when the task is successfully executed
  98451. * @param onError is a callback called if an error occurs
  98452. */
  98453. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98454. throw new Error("runTask is not implemented");
  98455. };
  98456. /**
  98457. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98458. * This can be used with failed tasks that have the reason for failure fixed.
  98459. */
  98460. AbstractAssetTask.prototype.reset = function () {
  98461. this._taskState = AssetTaskState.INIT;
  98462. };
  98463. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98464. this._taskState = AssetTaskState.ERROR;
  98465. this._errorObject = {
  98466. message: message,
  98467. exception: exception
  98468. };
  98469. if (this.onError) {
  98470. this.onError(this, message, exception);
  98471. }
  98472. onError();
  98473. };
  98474. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98475. try {
  98476. this._taskState = AssetTaskState.DONE;
  98477. this._isCompleted = true;
  98478. if (this.onSuccess) {
  98479. this.onSuccess(this);
  98480. }
  98481. onSuccess();
  98482. }
  98483. catch (e) {
  98484. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98485. }
  98486. };
  98487. return AbstractAssetTask;
  98488. }());
  98489. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98490. /**
  98491. * Class used to share progress information about assets loading
  98492. */
  98493. var AssetsProgressEvent = /** @class */ (function () {
  98494. /**
  98495. * Creates a {BABYLON.AssetsProgressEvent}
  98496. * @param remainingCount defines the number of remaining tasks to process
  98497. * @param totalCount defines the total number of tasks
  98498. * @param task defines the task that was just processed
  98499. */
  98500. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98501. this.remainingCount = remainingCount;
  98502. this.totalCount = totalCount;
  98503. this.task = task;
  98504. }
  98505. return AssetsProgressEvent;
  98506. }());
  98507. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98508. /**
  98509. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98510. */
  98511. var MeshAssetTask = /** @class */ (function (_super) {
  98512. __extends(MeshAssetTask, _super);
  98513. /**
  98514. * Creates a new {BABYLON.MeshAssetTask}
  98515. * @param name defines the name of the task
  98516. * @param meshesNames defines the list of mesh's names you want to load
  98517. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98518. * @param sceneFilename defines the filename of the scene to load from
  98519. */
  98520. function MeshAssetTask(
  98521. /**
  98522. * Defines the name of the task
  98523. */
  98524. name,
  98525. /**
  98526. * Defines the list of mesh's names you want to load
  98527. */
  98528. meshesNames,
  98529. /**
  98530. * Defines the root url to use as a base to load your meshes and associated resources
  98531. */
  98532. rootUrl,
  98533. /**
  98534. * Defines the filename of the scene to load from
  98535. */
  98536. sceneFilename) {
  98537. var _this = _super.call(this, name) || this;
  98538. _this.name = name;
  98539. _this.meshesNames = meshesNames;
  98540. _this.rootUrl = rootUrl;
  98541. _this.sceneFilename = sceneFilename;
  98542. return _this;
  98543. }
  98544. /**
  98545. * Execute the current task
  98546. * @param scene defines the scene where you want your assets to be loaded
  98547. * @param onSuccess is a callback called when the task is successfully executed
  98548. * @param onError is a callback called if an error occurs
  98549. */
  98550. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98551. var _this = this;
  98552. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98553. _this.loadedMeshes = meshes;
  98554. _this.loadedParticleSystems = particleSystems;
  98555. _this.loadedSkeletons = skeletons;
  98556. onSuccess();
  98557. }, null, function (scene, message, exception) {
  98558. onError(message, exception);
  98559. });
  98560. };
  98561. return MeshAssetTask;
  98562. }(AbstractAssetTask));
  98563. BABYLON.MeshAssetTask = MeshAssetTask;
  98564. /**
  98565. * Define a task used by {BABYLON.AssetsManager} to load text content
  98566. */
  98567. var TextFileAssetTask = /** @class */ (function (_super) {
  98568. __extends(TextFileAssetTask, _super);
  98569. /**
  98570. * Creates a new TextFileAssetTask object
  98571. * @param name defines the name of the task
  98572. * @param url defines the location of the file to load
  98573. */
  98574. function TextFileAssetTask(
  98575. /**
  98576. * Defines the name of the task
  98577. */
  98578. name,
  98579. /**
  98580. * Defines the location of the file to load
  98581. */
  98582. url) {
  98583. var _this = _super.call(this, name) || this;
  98584. _this.name = name;
  98585. _this.url = url;
  98586. return _this;
  98587. }
  98588. /**
  98589. * Execute the current task
  98590. * @param scene defines the scene where you want your assets to be loaded
  98591. * @param onSuccess is a callback called when the task is successfully executed
  98592. * @param onError is a callback called if an error occurs
  98593. */
  98594. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98595. var _this = this;
  98596. scene._loadFile(this.url, function (data) {
  98597. _this.text = data;
  98598. onSuccess();
  98599. }, undefined, false, false, function (request, exception) {
  98600. if (request) {
  98601. onError(request.status + " " + request.statusText, exception);
  98602. }
  98603. });
  98604. };
  98605. return TextFileAssetTask;
  98606. }(AbstractAssetTask));
  98607. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98608. /**
  98609. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98610. */
  98611. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98612. __extends(BinaryFileAssetTask, _super);
  98613. /**
  98614. * Creates a new BinaryFileAssetTask object
  98615. * @param name defines the name of the new task
  98616. * @param url defines the location of the file to load
  98617. */
  98618. function BinaryFileAssetTask(
  98619. /**
  98620. * Defines the name of the task
  98621. */
  98622. name,
  98623. /**
  98624. * Defines the location of the file to load
  98625. */
  98626. url) {
  98627. var _this = _super.call(this, name) || this;
  98628. _this.name = name;
  98629. _this.url = url;
  98630. return _this;
  98631. }
  98632. /**
  98633. * Execute the current task
  98634. * @param scene defines the scene where you want your assets to be loaded
  98635. * @param onSuccess is a callback called when the task is successfully executed
  98636. * @param onError is a callback called if an error occurs
  98637. */
  98638. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98639. var _this = this;
  98640. scene._loadFile(this.url, function (data) {
  98641. _this.data = data;
  98642. onSuccess();
  98643. }, undefined, true, true, function (request, exception) {
  98644. if (request) {
  98645. onError(request.status + " " + request.statusText, exception);
  98646. }
  98647. });
  98648. };
  98649. return BinaryFileAssetTask;
  98650. }(AbstractAssetTask));
  98651. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98652. /**
  98653. * Define a task used by {BABYLON.AssetsManager} to load images
  98654. */
  98655. var ImageAssetTask = /** @class */ (function (_super) {
  98656. __extends(ImageAssetTask, _super);
  98657. /**
  98658. * Creates a new ImageAssetTask
  98659. * @param name defines the name of the task
  98660. * @param url defines the location of the image to load
  98661. */
  98662. function ImageAssetTask(
  98663. /**
  98664. * Defines the name of the task
  98665. */
  98666. name,
  98667. /**
  98668. * Defines the location of the image to load
  98669. */
  98670. url) {
  98671. var _this = _super.call(this, name) || this;
  98672. _this.name = name;
  98673. _this.url = url;
  98674. return _this;
  98675. }
  98676. /**
  98677. * Execute the current task
  98678. * @param scene defines the scene where you want your assets to be loaded
  98679. * @param onSuccess is a callback called when the task is successfully executed
  98680. * @param onError is a callback called if an error occurs
  98681. */
  98682. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98683. var _this = this;
  98684. var img = new Image();
  98685. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98686. img.onload = function () {
  98687. _this.image = img;
  98688. onSuccess();
  98689. };
  98690. img.onerror = function (err) {
  98691. onError("Error loading image", err);
  98692. };
  98693. img.src = this.url;
  98694. };
  98695. return ImageAssetTask;
  98696. }(AbstractAssetTask));
  98697. BABYLON.ImageAssetTask = ImageAssetTask;
  98698. /**
  98699. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98700. */
  98701. var TextureAssetTask = /** @class */ (function (_super) {
  98702. __extends(TextureAssetTask, _super);
  98703. /**
  98704. * Creates a new TextureAssetTask object
  98705. * @param name defines the name of the task
  98706. * @param url defines the location of the file to load
  98707. * @param noMipmap defines if mipmap should not be generated (default is false)
  98708. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98709. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98710. */
  98711. function TextureAssetTask(
  98712. /**
  98713. * Defines the name of the task
  98714. */
  98715. name,
  98716. /**
  98717. * Defines the location of the file to load
  98718. */
  98719. url,
  98720. /**
  98721. * Defines if mipmap should not be generated (default is false)
  98722. */
  98723. noMipmap,
  98724. /**
  98725. * Defines if texture must be inverted on Y axis (default is false)
  98726. */
  98727. invertY,
  98728. /**
  98729. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98730. */
  98731. samplingMode) {
  98732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98733. var _this = _super.call(this, name) || this;
  98734. _this.name = name;
  98735. _this.url = url;
  98736. _this.noMipmap = noMipmap;
  98737. _this.invertY = invertY;
  98738. _this.samplingMode = samplingMode;
  98739. return _this;
  98740. }
  98741. /**
  98742. * Execute the current task
  98743. * @param scene defines the scene where you want your assets to be loaded
  98744. * @param onSuccess is a callback called when the task is successfully executed
  98745. * @param onError is a callback called if an error occurs
  98746. */
  98747. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98748. var onload = function () {
  98749. onSuccess();
  98750. };
  98751. var onerror = function (message, exception) {
  98752. onError(message, exception);
  98753. };
  98754. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98755. };
  98756. return TextureAssetTask;
  98757. }(AbstractAssetTask));
  98758. BABYLON.TextureAssetTask = TextureAssetTask;
  98759. /**
  98760. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98761. */
  98762. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98763. __extends(CubeTextureAssetTask, _super);
  98764. /**
  98765. * Creates a new CubeTextureAssetTask
  98766. * @param name defines the name of the task
  98767. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98768. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98769. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98770. * @param files defines the explicit list of files (undefined by default)
  98771. */
  98772. function CubeTextureAssetTask(
  98773. /**
  98774. * Defines the name of the task
  98775. */
  98776. name,
  98777. /**
  98778. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98779. */
  98780. url,
  98781. /**
  98782. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98783. */
  98784. extensions,
  98785. /**
  98786. * Defines if mipmaps should not be generated (default is false)
  98787. */
  98788. noMipmap,
  98789. /**
  98790. * Defines the explicit list of files (undefined by default)
  98791. */
  98792. files) {
  98793. var _this = _super.call(this, name) || this;
  98794. _this.name = name;
  98795. _this.url = url;
  98796. _this.extensions = extensions;
  98797. _this.noMipmap = noMipmap;
  98798. _this.files = files;
  98799. return _this;
  98800. }
  98801. /**
  98802. * Execute the current task
  98803. * @param scene defines the scene where you want your assets to be loaded
  98804. * @param onSuccess is a callback called when the task is successfully executed
  98805. * @param onError is a callback called if an error occurs
  98806. */
  98807. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98808. var onload = function () {
  98809. onSuccess();
  98810. };
  98811. var onerror = function (message, exception) {
  98812. onError(message, exception);
  98813. };
  98814. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98815. };
  98816. return CubeTextureAssetTask;
  98817. }(AbstractAssetTask));
  98818. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98819. /**
  98820. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98821. */
  98822. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98823. __extends(HDRCubeTextureAssetTask, _super);
  98824. /**
  98825. * Creates a new HDRCubeTextureAssetTask object
  98826. * @param name defines the name of the task
  98827. * @param url defines the location of the file to load
  98828. * @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.
  98829. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98830. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98831. * @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)
  98832. * @param reserved Internal use only
  98833. */
  98834. function HDRCubeTextureAssetTask(
  98835. /**
  98836. * Defines the name of the task
  98837. */
  98838. name,
  98839. /**
  98840. * Defines the location of the file to load
  98841. */
  98842. url,
  98843. /**
  98844. * Defines the desired size (the more it increases the longer the generation will be)
  98845. */
  98846. size,
  98847. /**
  98848. * Defines if mipmaps should not be generated (default is false)
  98849. */
  98850. noMipmap,
  98851. /**
  98852. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98853. */
  98854. generateHarmonics,
  98855. /**
  98856. * 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)
  98857. */
  98858. gammaSpace,
  98859. /**
  98860. * Internal Use Only
  98861. */
  98862. reserved) {
  98863. if (noMipmap === void 0) { noMipmap = false; }
  98864. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98865. if (gammaSpace === void 0) { gammaSpace = false; }
  98866. if (reserved === void 0) { reserved = false; }
  98867. var _this = _super.call(this, name) || this;
  98868. _this.name = name;
  98869. _this.url = url;
  98870. _this.size = size;
  98871. _this.noMipmap = noMipmap;
  98872. _this.generateHarmonics = generateHarmonics;
  98873. _this.gammaSpace = gammaSpace;
  98874. _this.reserved = reserved;
  98875. return _this;
  98876. }
  98877. /**
  98878. * Execute the current task
  98879. * @param scene defines the scene where you want your assets to be loaded
  98880. * @param onSuccess is a callback called when the task is successfully executed
  98881. * @param onError is a callback called if an error occurs
  98882. */
  98883. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98884. var onload = function () {
  98885. onSuccess();
  98886. };
  98887. var onerror = function (message, exception) {
  98888. onError(message, exception);
  98889. };
  98890. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98891. };
  98892. return HDRCubeTextureAssetTask;
  98893. }(AbstractAssetTask));
  98894. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98895. /**
  98896. * This class can be used to easily import assets into a scene
  98897. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98898. */
  98899. var AssetsManager = /** @class */ (function () {
  98900. /**
  98901. * Creates a new AssetsManager
  98902. * @param scene defines the scene to work on
  98903. */
  98904. function AssetsManager(scene) {
  98905. this._isLoading = false;
  98906. this._tasks = new Array();
  98907. this._waitingTasksCount = 0;
  98908. this._totalTasksCount = 0;
  98909. /**
  98910. * Observable called when all tasks are processed
  98911. */
  98912. this.onTaskSuccessObservable = new BABYLON.Observable();
  98913. /**
  98914. * Observable called when a task had an error
  98915. */
  98916. this.onTaskErrorObservable = new BABYLON.Observable();
  98917. /**
  98918. * Observable called when a task is successful
  98919. */
  98920. this.onTasksDoneObservable = new BABYLON.Observable();
  98921. /**
  98922. * Observable called when a task is done (whatever the result is)
  98923. */
  98924. this.onProgressObservable = new BABYLON.Observable();
  98925. /**
  98926. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98927. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98928. */
  98929. this.useDefaultLoadingScreen = true;
  98930. this._scene = scene;
  98931. }
  98932. /**
  98933. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98934. * @param taskName defines the name of the new task
  98935. * @param meshesNames defines the name of meshes to load
  98936. * @param rootUrl defines the root url to use to locate files
  98937. * @param sceneFilename defines the filename of the scene file
  98938. * @returns a new {BABYLON.MeshAssetTask} object
  98939. */
  98940. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98941. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98942. this._tasks.push(task);
  98943. return task;
  98944. };
  98945. /**
  98946. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98947. * @param taskName defines the name of the new task
  98948. * @param url defines the url of the file to load
  98949. * @returns a new {BABYLON.TextFileAssetTask} object
  98950. */
  98951. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98952. var task = new TextFileAssetTask(taskName, url);
  98953. this._tasks.push(task);
  98954. return task;
  98955. };
  98956. /**
  98957. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98958. * @param taskName defines the name of the new task
  98959. * @param url defines the url of the file to load
  98960. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98961. */
  98962. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98963. var task = new BinaryFileAssetTask(taskName, url);
  98964. this._tasks.push(task);
  98965. return task;
  98966. };
  98967. /**
  98968. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98969. * @param taskName defines the name of the new task
  98970. * @param url defines the url of the file to load
  98971. * @returns a new {BABYLON.ImageAssetTask} object
  98972. */
  98973. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98974. var task = new ImageAssetTask(taskName, url);
  98975. this._tasks.push(task);
  98976. return task;
  98977. };
  98978. /**
  98979. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98980. * @param taskName defines the name of the new task
  98981. * @param url defines the url of the file to load
  98982. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98983. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98984. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98985. * @returns a new {BABYLON.TextureAssetTask} object
  98986. */
  98987. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98989. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98990. this._tasks.push(task);
  98991. return task;
  98992. };
  98993. /**
  98994. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98995. * @param taskName defines the name of the new task
  98996. * @param url defines the url of the file to load
  98997. * @param extensions defines the extension to use to load the cube map (can be null)
  98998. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98999. * @param files defines the list of files to load (can be null)
  99000. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99001. */
  99002. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99003. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99004. this._tasks.push(task);
  99005. return task;
  99006. };
  99007. /**
  99008. *
  99009. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99010. * @param taskName defines the name of the new task
  99011. * @param url defines the url of the file to load
  99012. * @param size defines the size you want for the cubemap (can be null)
  99013. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99014. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99015. * @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)
  99016. * @param reserved Internal use only
  99017. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99018. */
  99019. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99020. if (noMipmap === void 0) { noMipmap = false; }
  99021. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99022. if (gammaSpace === void 0) { gammaSpace = false; }
  99023. if (reserved === void 0) { reserved = false; }
  99024. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99025. this._tasks.push(task);
  99026. return task;
  99027. };
  99028. /**
  99029. * Remove a task from the assets manager.
  99030. * @param task the task to remove
  99031. */
  99032. AssetsManager.prototype.removeTask = function (task) {
  99033. var index = this._tasks.indexOf(task);
  99034. if (index > -1) {
  99035. this._tasks.splice(index, 1);
  99036. }
  99037. };
  99038. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99039. this._waitingTasksCount--;
  99040. try {
  99041. if (this.onProgress) {
  99042. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99043. }
  99044. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99045. }
  99046. catch (e) {
  99047. BABYLON.Tools.Error("Error running progress callbacks.");
  99048. console.log(e);
  99049. }
  99050. if (this._waitingTasksCount === 0) {
  99051. try {
  99052. if (this.onFinish) {
  99053. this.onFinish(this._tasks);
  99054. }
  99055. // Let's remove successfull tasks
  99056. var currentTasks = this._tasks.slice();
  99057. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99058. var task = currentTasks_1[_i];
  99059. if (task.taskState === AssetTaskState.DONE) {
  99060. var index = this._tasks.indexOf(task);
  99061. if (index > -1) {
  99062. this._tasks.splice(index, 1);
  99063. }
  99064. }
  99065. }
  99066. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99067. }
  99068. catch (e) {
  99069. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99070. console.log(e);
  99071. }
  99072. this._isLoading = false;
  99073. this._scene.getEngine().hideLoadingUI();
  99074. }
  99075. };
  99076. AssetsManager.prototype._runTask = function (task) {
  99077. var _this = this;
  99078. var done = function () {
  99079. try {
  99080. if (_this.onTaskSuccess) {
  99081. _this.onTaskSuccess(task);
  99082. }
  99083. _this.onTaskSuccessObservable.notifyObservers(task);
  99084. _this._decreaseWaitingTasksCount(task);
  99085. }
  99086. catch (e) {
  99087. error("Error executing task success callbacks", e);
  99088. }
  99089. };
  99090. var error = function (message, exception) {
  99091. task._setErrorObject(message, exception);
  99092. if (_this.onTaskError) {
  99093. _this.onTaskError(task);
  99094. }
  99095. _this.onTaskErrorObservable.notifyObservers(task);
  99096. _this._decreaseWaitingTasksCount(task);
  99097. };
  99098. task.run(this._scene, done, error);
  99099. };
  99100. /**
  99101. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99102. * @return the current instance of the {BABYLON.AssetsManager}
  99103. */
  99104. AssetsManager.prototype.reset = function () {
  99105. this._isLoading = false;
  99106. this._tasks = new Array();
  99107. return this;
  99108. };
  99109. /**
  99110. * Start the loading process
  99111. * @return the current instance of the {BABYLON.AssetsManager}
  99112. */
  99113. AssetsManager.prototype.load = function () {
  99114. if (this._isLoading) {
  99115. return this;
  99116. }
  99117. this._isLoading = true;
  99118. this._waitingTasksCount = this._tasks.length;
  99119. this._totalTasksCount = this._tasks.length;
  99120. if (this._waitingTasksCount === 0) {
  99121. this._isLoading = false;
  99122. if (this.onFinish) {
  99123. this.onFinish(this._tasks);
  99124. }
  99125. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99126. return this;
  99127. }
  99128. if (this.useDefaultLoadingScreen) {
  99129. this._scene.getEngine().displayLoadingUI();
  99130. }
  99131. for (var index = 0; index < this._tasks.length; index++) {
  99132. var task = this._tasks[index];
  99133. if (task.taskState === AssetTaskState.INIT) {
  99134. this._runTask(task);
  99135. }
  99136. }
  99137. return this;
  99138. };
  99139. return AssetsManager;
  99140. }());
  99141. BABYLON.AssetsManager = AssetsManager;
  99142. })(BABYLON || (BABYLON = {}));
  99143. //# sourceMappingURL=babylon.assetsManager.js.map
  99144. var BABYLON;
  99145. (function (BABYLON) {
  99146. var serializedGeometries = [];
  99147. var serializeGeometry = function (geometry, serializationGeometries) {
  99148. if (serializedGeometries[geometry.id]) {
  99149. return;
  99150. }
  99151. if (geometry.doNotSerialize) {
  99152. return;
  99153. }
  99154. if (geometry instanceof BABYLON.BoxGeometry) {
  99155. serializationGeometries.boxes.push(geometry.serialize());
  99156. }
  99157. else if (geometry instanceof BABYLON.SphereGeometry) {
  99158. serializationGeometries.spheres.push(geometry.serialize());
  99159. }
  99160. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99161. serializationGeometries.cylinders.push(geometry.serialize());
  99162. }
  99163. else if (geometry instanceof BABYLON.TorusGeometry) {
  99164. serializationGeometries.toruses.push(geometry.serialize());
  99165. }
  99166. else if (geometry instanceof BABYLON.GroundGeometry) {
  99167. serializationGeometries.grounds.push(geometry.serialize());
  99168. }
  99169. else if (geometry instanceof BABYLON.Plane) {
  99170. serializationGeometries.planes.push(geometry.serialize());
  99171. }
  99172. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99173. serializationGeometries.torusKnots.push(geometry.serialize());
  99174. }
  99175. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99176. throw new Error("Unknown primitive type");
  99177. }
  99178. else {
  99179. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99180. }
  99181. serializedGeometries[geometry.id] = true;
  99182. };
  99183. var serializeMesh = function (mesh, serializationScene) {
  99184. var serializationObject = {};
  99185. // Geometry
  99186. var geometry = mesh._geometry;
  99187. if (geometry) {
  99188. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99189. // 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
  99190. serializeGeometry(geometry, serializationScene.geometries);
  99191. }
  99192. }
  99193. // Custom
  99194. if (mesh.serialize) {
  99195. mesh.serialize(serializationObject);
  99196. }
  99197. return serializationObject;
  99198. };
  99199. var finalizeSingleMesh = function (mesh, serializationObject) {
  99200. //only works if the mesh is already loaded
  99201. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99202. //serialize material
  99203. if (mesh.material) {
  99204. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99205. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99206. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99207. serializationObject.multiMaterials.push(mesh.material.serialize());
  99208. }
  99209. }
  99210. else {
  99211. serializationObject.materials = serializationObject.materials || [];
  99212. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99213. serializationObject.materials.push(mesh.material.serialize());
  99214. }
  99215. }
  99216. }
  99217. //serialize geometry
  99218. var geometry = mesh._geometry;
  99219. if (geometry) {
  99220. if (!serializationObject.geometries) {
  99221. serializationObject.geometries = {};
  99222. serializationObject.geometries.boxes = [];
  99223. serializationObject.geometries.spheres = [];
  99224. serializationObject.geometries.cylinders = [];
  99225. serializationObject.geometries.toruses = [];
  99226. serializationObject.geometries.grounds = [];
  99227. serializationObject.geometries.planes = [];
  99228. serializationObject.geometries.torusKnots = [];
  99229. serializationObject.geometries.vertexData = [];
  99230. }
  99231. serializeGeometry(geometry, serializationObject.geometries);
  99232. }
  99233. // Skeletons
  99234. if (mesh.skeleton) {
  99235. serializationObject.skeletons = serializationObject.skeletons || [];
  99236. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99237. }
  99238. //serialize the actual mesh
  99239. serializationObject.meshes = serializationObject.meshes || [];
  99240. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99241. }
  99242. };
  99243. var SceneSerializer = /** @class */ (function () {
  99244. function SceneSerializer() {
  99245. }
  99246. SceneSerializer.ClearCache = function () {
  99247. serializedGeometries = [];
  99248. };
  99249. SceneSerializer.Serialize = function (scene) {
  99250. var serializationObject = {};
  99251. SceneSerializer.ClearCache();
  99252. // Scene
  99253. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99254. serializationObject.autoClear = scene.autoClear;
  99255. serializationObject.clearColor = scene.clearColor.asArray();
  99256. serializationObject.ambientColor = scene.ambientColor.asArray();
  99257. serializationObject.gravity = scene.gravity.asArray();
  99258. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99259. serializationObject.workerCollisions = scene.workerCollisions;
  99260. // Fog
  99261. if (scene.fogMode && scene.fogMode !== 0) {
  99262. serializationObject.fogMode = scene.fogMode;
  99263. serializationObject.fogColor = scene.fogColor.asArray();
  99264. serializationObject.fogStart = scene.fogStart;
  99265. serializationObject.fogEnd = scene.fogEnd;
  99266. serializationObject.fogDensity = scene.fogDensity;
  99267. }
  99268. //Physics
  99269. if (scene.isPhysicsEnabled()) {
  99270. var physicEngine = scene.getPhysicsEngine();
  99271. if (physicEngine) {
  99272. serializationObject.physicsEnabled = true;
  99273. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99274. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99275. }
  99276. }
  99277. // Metadata
  99278. if (scene.metadata) {
  99279. serializationObject.metadata = scene.metadata;
  99280. }
  99281. // Morph targets
  99282. serializationObject.morphTargetManagers = [];
  99283. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99284. var abstractMesh = _a[_i];
  99285. var manager = abstractMesh.morphTargetManager;
  99286. if (manager) {
  99287. serializationObject.morphTargetManagers.push(manager.serialize());
  99288. }
  99289. }
  99290. // Lights
  99291. serializationObject.lights = [];
  99292. var index;
  99293. var light;
  99294. for (index = 0; index < scene.lights.length; index++) {
  99295. light = scene.lights[index];
  99296. if (!light.doNotSerialize) {
  99297. serializationObject.lights.push(light.serialize());
  99298. }
  99299. }
  99300. // Cameras
  99301. serializationObject.cameras = [];
  99302. for (index = 0; index < scene.cameras.length; index++) {
  99303. var camera = scene.cameras[index];
  99304. if (!camera.doNotSerialize) {
  99305. serializationObject.cameras.push(camera.serialize());
  99306. }
  99307. }
  99308. if (scene.activeCamera) {
  99309. serializationObject.activeCameraID = scene.activeCamera.id;
  99310. }
  99311. // Animations
  99312. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99313. // Materials
  99314. serializationObject.materials = [];
  99315. serializationObject.multiMaterials = [];
  99316. var material;
  99317. for (index = 0; index < scene.materials.length; index++) {
  99318. material = scene.materials[index];
  99319. if (!material.doNotSerialize) {
  99320. serializationObject.materials.push(material.serialize());
  99321. }
  99322. }
  99323. // MultiMaterials
  99324. serializationObject.multiMaterials = [];
  99325. for (index = 0; index < scene.multiMaterials.length; index++) {
  99326. var multiMaterial = scene.multiMaterials[index];
  99327. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99328. }
  99329. // Environment texture
  99330. if (scene.environmentTexture) {
  99331. serializationObject.environmentTexture = scene.environmentTexture.name;
  99332. }
  99333. // Skeletons
  99334. serializationObject.skeletons = [];
  99335. for (index = 0; index < scene.skeletons.length; index++) {
  99336. var skeleton = scene.skeletons[index];
  99337. if (!skeleton.doNotSerialize) {
  99338. serializationObject.skeletons.push(skeleton.serialize());
  99339. }
  99340. }
  99341. // Transform nodes
  99342. serializationObject.transformNodes = [];
  99343. for (index = 0; index < scene.transformNodes.length; index++) {
  99344. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99345. }
  99346. // Geometries
  99347. serializationObject.geometries = {};
  99348. serializationObject.geometries.boxes = [];
  99349. serializationObject.geometries.spheres = [];
  99350. serializationObject.geometries.cylinders = [];
  99351. serializationObject.geometries.toruses = [];
  99352. serializationObject.geometries.grounds = [];
  99353. serializationObject.geometries.planes = [];
  99354. serializationObject.geometries.torusKnots = [];
  99355. serializationObject.geometries.vertexData = [];
  99356. serializedGeometries = [];
  99357. var geometries = scene.getGeometries();
  99358. for (index = 0; index < geometries.length; index++) {
  99359. var geometry = geometries[index];
  99360. if (geometry.isReady()) {
  99361. serializeGeometry(geometry, serializationObject.geometries);
  99362. }
  99363. }
  99364. // Meshes
  99365. serializationObject.meshes = [];
  99366. for (index = 0; index < scene.meshes.length; index++) {
  99367. var abstractMesh = scene.meshes[index];
  99368. if (abstractMesh instanceof BABYLON.Mesh) {
  99369. var mesh = abstractMesh;
  99370. if (!mesh.doNotSerialize) {
  99371. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99372. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99373. }
  99374. }
  99375. }
  99376. }
  99377. // Particles Systems
  99378. serializationObject.particleSystems = [];
  99379. for (index = 0; index < scene.particleSystems.length; index++) {
  99380. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99381. }
  99382. // Shadows
  99383. serializationObject.shadowGenerators = [];
  99384. for (index = 0; index < scene.lights.length; index++) {
  99385. light = scene.lights[index];
  99386. var shadowGenerator = light.getShadowGenerator();
  99387. if (shadowGenerator) {
  99388. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99389. }
  99390. }
  99391. // Action Manager
  99392. if (scene.actionManager) {
  99393. serializationObject.actions = scene.actionManager.serialize("scene");
  99394. }
  99395. // Audio
  99396. serializationObject.sounds = [];
  99397. for (index = 0; index < scene.soundTracks.length; index++) {
  99398. var soundtrack = scene.soundTracks[index];
  99399. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99400. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99401. }
  99402. }
  99403. // Components
  99404. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99405. var component = _c[_b];
  99406. component.serialize(serializationObject);
  99407. }
  99408. return serializationObject;
  99409. };
  99410. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99411. if (withParents === void 0) { withParents = false; }
  99412. if (withChildren === void 0) { withChildren = false; }
  99413. var serializationObject = {};
  99414. SceneSerializer.ClearCache();
  99415. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99416. if (withParents || withChildren) {
  99417. //deliberate for loop! not for each, appended should be processed as well.
  99418. for (var i = 0; i < toSerialize.length; ++i) {
  99419. if (withChildren) {
  99420. toSerialize[i].getDescendants().forEach(function (node) {
  99421. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99422. toSerialize.push(node);
  99423. }
  99424. });
  99425. }
  99426. //make sure the array doesn't contain the object already
  99427. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99428. toSerialize.push(toSerialize[i].parent);
  99429. }
  99430. }
  99431. }
  99432. toSerialize.forEach(function (mesh) {
  99433. finalizeSingleMesh(mesh, serializationObject);
  99434. });
  99435. return serializationObject;
  99436. };
  99437. return SceneSerializer;
  99438. }());
  99439. BABYLON.SceneSerializer = SceneSerializer;
  99440. })(BABYLON || (BABYLON = {}));
  99441. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99442. var BABYLON;
  99443. (function (BABYLON) {
  99444. var ReflectionProbe = /** @class */ (function () {
  99445. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99446. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99447. var _this = this;
  99448. this.name = name;
  99449. this._viewMatrix = BABYLON.Matrix.Identity();
  99450. this._target = BABYLON.Vector3.Zero();
  99451. this._add = BABYLON.Vector3.Zero();
  99452. this._invertYAxis = false;
  99453. this.position = BABYLON.Vector3.Zero();
  99454. this._scene = scene;
  99455. this._scene.reflectionProbes.push(this);
  99456. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99457. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99458. switch (faceIndex) {
  99459. case 0:
  99460. _this._add.copyFromFloats(1, 0, 0);
  99461. break;
  99462. case 1:
  99463. _this._add.copyFromFloats(-1, 0, 0);
  99464. break;
  99465. case 2:
  99466. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99467. break;
  99468. case 3:
  99469. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99470. break;
  99471. case 4:
  99472. _this._add.copyFromFloats(0, 0, 1);
  99473. break;
  99474. case 5:
  99475. _this._add.copyFromFloats(0, 0, -1);
  99476. break;
  99477. }
  99478. if (_this._attachedMesh) {
  99479. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99480. }
  99481. _this.position.addToRef(_this._add, _this._target);
  99482. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99483. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99484. scene._forcedViewPosition = _this.position;
  99485. });
  99486. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99487. scene._forcedViewPosition = null;
  99488. scene.updateTransformMatrix(true);
  99489. });
  99490. if (scene.activeCamera) {
  99491. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99492. }
  99493. }
  99494. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99495. get: function () {
  99496. return this._renderTargetTexture.samples;
  99497. },
  99498. set: function (value) {
  99499. this._renderTargetTexture.samples = value;
  99500. },
  99501. enumerable: true,
  99502. configurable: true
  99503. });
  99504. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99505. get: function () {
  99506. return this._renderTargetTexture.refreshRate;
  99507. },
  99508. set: function (value) {
  99509. this._renderTargetTexture.refreshRate = value;
  99510. },
  99511. enumerable: true,
  99512. configurable: true
  99513. });
  99514. ReflectionProbe.prototype.getScene = function () {
  99515. return this._scene;
  99516. };
  99517. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99518. get: function () {
  99519. return this._renderTargetTexture;
  99520. },
  99521. enumerable: true,
  99522. configurable: true
  99523. });
  99524. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99525. get: function () {
  99526. return this._renderTargetTexture.renderList;
  99527. },
  99528. enumerable: true,
  99529. configurable: true
  99530. });
  99531. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99532. this._attachedMesh = mesh;
  99533. };
  99534. /**
  99535. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99536. *
  99537. * @param renderingGroupId The rendering group id corresponding to its index
  99538. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99539. */
  99540. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99541. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99542. };
  99543. ReflectionProbe.prototype.dispose = function () {
  99544. var index = this._scene.reflectionProbes.indexOf(this);
  99545. if (index !== -1) {
  99546. // Remove from the scene if found
  99547. this._scene.reflectionProbes.splice(index, 1);
  99548. }
  99549. if (this._renderTargetTexture) {
  99550. this._renderTargetTexture.dispose();
  99551. this._renderTargetTexture = null;
  99552. }
  99553. };
  99554. return ReflectionProbe;
  99555. }());
  99556. BABYLON.ReflectionProbe = ReflectionProbe;
  99557. })(BABYLON || (BABYLON = {}));
  99558. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99559. var BABYLON;
  99560. (function (BABYLON) {
  99561. /**
  99562. * Defines the layer scene component responsible to manage any layers
  99563. * in a given scene.
  99564. */
  99565. var LayerSceneComponent = /** @class */ (function () {
  99566. /**
  99567. * Creates a new instance of the component for the given scene
  99568. * @param scene Defines the scene to register the component in
  99569. */
  99570. function LayerSceneComponent(scene) {
  99571. /**
  99572. * The component name helpfull to identify the component in the list of scene components.
  99573. */
  99574. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99575. this.scene = scene;
  99576. this._engine = scene.getEngine();
  99577. scene.layers = new Array();
  99578. }
  99579. /**
  99580. * Registers the component in a given scene
  99581. */
  99582. LayerSceneComponent.prototype.register = function () {
  99583. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99584. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99585. };
  99586. /**
  99587. * Rebuilds the elements related to this component in case of
  99588. * context lost for instance.
  99589. */
  99590. LayerSceneComponent.prototype.rebuild = function () {
  99591. var layers = this.scene.layers;
  99592. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99593. var layer = layers_1[_i];
  99594. layer._rebuild();
  99595. }
  99596. };
  99597. /**
  99598. * Disposes the component and the associated ressources.
  99599. */
  99600. LayerSceneComponent.prototype.dispose = function () {
  99601. var layers = this.scene.layers;
  99602. while (layers.length) {
  99603. layers[0].dispose();
  99604. }
  99605. };
  99606. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99607. var layers = this.scene.layers;
  99608. if (layers.length) {
  99609. this._engine.setDepthBuffer(false);
  99610. var cameraLayerMask = camera.layerMask;
  99611. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99612. var layer = layers_2[_i];
  99613. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99614. layer.render();
  99615. }
  99616. }
  99617. this._engine.setDepthBuffer(true);
  99618. }
  99619. };
  99620. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99621. this._draw(camera, true);
  99622. };
  99623. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99624. this._draw(camera, false);
  99625. };
  99626. return LayerSceneComponent;
  99627. }());
  99628. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99629. })(BABYLON || (BABYLON = {}));
  99630. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99631. var BABYLON;
  99632. (function (BABYLON) {
  99633. var Layer = /** @class */ (function () {
  99634. function Layer(name, imgUrl, scene, isBackground, color) {
  99635. this.name = name;
  99636. this.scale = new BABYLON.Vector2(1, 1);
  99637. this.offset = new BABYLON.Vector2(0, 0);
  99638. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99639. this.layerMask = 0x0FFFFFFF;
  99640. this._vertexBuffers = {};
  99641. // Events
  99642. /**
  99643. * An event triggered when the layer is disposed.
  99644. */
  99645. this.onDisposeObservable = new BABYLON.Observable();
  99646. /**
  99647. * An event triggered before rendering the scene
  99648. */
  99649. this.onBeforeRenderObservable = new BABYLON.Observable();
  99650. /**
  99651. * An event triggered after rendering the scene
  99652. */
  99653. this.onAfterRenderObservable = new BABYLON.Observable();
  99654. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99655. this.isBackground = isBackground === undefined ? true : isBackground;
  99656. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99657. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99658. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99659. if (!layerComponent) {
  99660. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99661. this._scene._addComponent(layerComponent);
  99662. }
  99663. this._scene.layers.push(this);
  99664. var engine = this._scene.getEngine();
  99665. // VBO
  99666. var vertices = [];
  99667. vertices.push(1, 1);
  99668. vertices.push(-1, 1);
  99669. vertices.push(-1, -1);
  99670. vertices.push(1, -1);
  99671. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99673. this._createIndexBuffer();
  99674. // Effects
  99675. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99676. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99677. }
  99678. Object.defineProperty(Layer.prototype, "onDispose", {
  99679. set: function (callback) {
  99680. if (this._onDisposeObserver) {
  99681. this.onDisposeObservable.remove(this._onDisposeObserver);
  99682. }
  99683. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99684. },
  99685. enumerable: true,
  99686. configurable: true
  99687. });
  99688. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99689. set: function (callback) {
  99690. if (this._onBeforeRenderObserver) {
  99691. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99692. }
  99693. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99694. },
  99695. enumerable: true,
  99696. configurable: true
  99697. });
  99698. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99699. set: function (callback) {
  99700. if (this._onAfterRenderObserver) {
  99701. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99702. }
  99703. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99704. },
  99705. enumerable: true,
  99706. configurable: true
  99707. });
  99708. Layer.prototype._createIndexBuffer = function () {
  99709. var engine = this._scene.getEngine();
  99710. // Indices
  99711. var indices = [];
  99712. indices.push(0);
  99713. indices.push(1);
  99714. indices.push(2);
  99715. indices.push(0);
  99716. indices.push(2);
  99717. indices.push(3);
  99718. this._indexBuffer = engine.createIndexBuffer(indices);
  99719. };
  99720. Layer.prototype._rebuild = function () {
  99721. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99722. if (vb) {
  99723. vb._rebuild();
  99724. }
  99725. this._createIndexBuffer();
  99726. };
  99727. Layer.prototype.render = function () {
  99728. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99729. // Check
  99730. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99731. return;
  99732. var engine = this._scene.getEngine();
  99733. this.onBeforeRenderObservable.notifyObservers(this);
  99734. // Render
  99735. engine.enableEffect(currentEffect);
  99736. engine.setState(false);
  99737. // Texture
  99738. currentEffect.setTexture("textureSampler", this.texture);
  99739. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99740. // Color
  99741. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99742. // Scale / offset
  99743. currentEffect.setVector2("offset", this.offset);
  99744. currentEffect.setVector2("scale", this.scale);
  99745. // VBOs
  99746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99747. // Draw order
  99748. if (!this.alphaTest) {
  99749. engine.setAlphaMode(this.alphaBlendingMode);
  99750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99752. }
  99753. else {
  99754. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99755. }
  99756. this.onAfterRenderObservable.notifyObservers(this);
  99757. };
  99758. Layer.prototype.dispose = function () {
  99759. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99760. if (vertexBuffer) {
  99761. vertexBuffer.dispose();
  99762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99763. }
  99764. if (this._indexBuffer) {
  99765. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99766. this._indexBuffer = null;
  99767. }
  99768. if (this.texture) {
  99769. this.texture.dispose();
  99770. this.texture = null;
  99771. }
  99772. // Remove from scene
  99773. var index = this._scene.layers.indexOf(this);
  99774. this._scene.layers.splice(index, 1);
  99775. // Callback
  99776. this.onDisposeObservable.notifyObservers(this);
  99777. this.onDisposeObservable.clear();
  99778. this.onAfterRenderObservable.clear();
  99779. this.onBeforeRenderObservable.clear();
  99780. };
  99781. return Layer;
  99782. }());
  99783. BABYLON.Layer = Layer;
  99784. })(BABYLON || (BABYLON = {}));
  99785. //# sourceMappingURL=babylon.layer.js.map
  99786. var BABYLON;
  99787. (function (BABYLON) {
  99788. var TextureTools = /** @class */ (function () {
  99789. function TextureTools() {
  99790. }
  99791. /**
  99792. * Uses the GPU to create a copy texture rescaled at a given size
  99793. * @param texture Texture to copy from
  99794. * @param width Desired width
  99795. * @param height Desired height
  99796. * @return Generated texture
  99797. */
  99798. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99799. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99800. var scene = texture.getScene();
  99801. var engine = scene.getEngine();
  99802. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99803. rtt.wrapU = texture.wrapU;
  99804. rtt.wrapV = texture.wrapV;
  99805. rtt.uOffset = texture.uOffset;
  99806. rtt.vOffset = texture.vOffset;
  99807. rtt.uScale = texture.uScale;
  99808. rtt.vScale = texture.vScale;
  99809. rtt.uAng = texture.uAng;
  99810. rtt.vAng = texture.vAng;
  99811. rtt.wAng = texture.wAng;
  99812. rtt.coordinatesIndex = texture.coordinatesIndex;
  99813. rtt.level = texture.level;
  99814. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99815. rtt._texture.isReady = false;
  99816. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99817. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99818. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99819. passPostProcess.getEffect().executeWhenCompiled(function () {
  99820. passPostProcess.onApply = function (effect) {
  99821. effect.setTexture("textureSampler", texture);
  99822. };
  99823. var internalTexture = rtt.getInternalTexture();
  99824. if (internalTexture) {
  99825. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99826. engine.unBindFramebuffer(internalTexture);
  99827. rtt.disposeFramebufferObjects();
  99828. passPostProcess.dispose();
  99829. internalTexture.isReady = true;
  99830. }
  99831. });
  99832. return rtt;
  99833. };
  99834. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99835. if (!scene._environmentBRDFTexture) {
  99836. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99837. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99838. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99839. scene._environmentBRDFTexture = texture;
  99840. }
  99841. return scene._environmentBRDFTexture;
  99842. };
  99843. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4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y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  99844. return TextureTools;
  99845. }());
  99846. BABYLON.TextureTools = TextureTools;
  99847. })(BABYLON || (BABYLON = {}));
  99848. //# sourceMappingURL=babylon.textureTools.js.map
  99849. var BABYLON;
  99850. (function (BABYLON) {
  99851. var FramingBehavior = /** @class */ (function () {
  99852. function FramingBehavior() {
  99853. this._mode = FramingBehavior.FitFrustumSidesMode;
  99854. this._radiusScale = 1.0;
  99855. this._positionScale = 0.5;
  99856. this._defaultElevation = 0.3;
  99857. this._elevationReturnTime = 1500;
  99858. this._elevationReturnWaitTime = 1000;
  99859. this._zoomStopsAnimation = false;
  99860. this._framingTime = 1500;
  99861. this._isPointerDown = false;
  99862. this._lastInteractionTime = -Infinity;
  99863. // Framing control
  99864. this._animatables = new Array();
  99865. this._betaIsAnimating = false;
  99866. }
  99867. Object.defineProperty(FramingBehavior.prototype, "name", {
  99868. get: function () {
  99869. return "Framing";
  99870. },
  99871. enumerable: true,
  99872. configurable: true
  99873. });
  99874. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99875. /**
  99876. * Gets current mode used by the behavior.
  99877. */
  99878. get: function () {
  99879. return this._mode;
  99880. },
  99881. /**
  99882. * Sets the current mode used by the behavior
  99883. */
  99884. set: function (mode) {
  99885. this._mode = mode;
  99886. },
  99887. enumerable: true,
  99888. configurable: true
  99889. });
  99890. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99891. /**
  99892. * Gets the scale applied to the radius
  99893. */
  99894. get: function () {
  99895. return this._radiusScale;
  99896. },
  99897. /**
  99898. * Sets the scale applied to the radius (1 by default)
  99899. */
  99900. set: function (radius) {
  99901. this._radiusScale = radius;
  99902. },
  99903. enumerable: true,
  99904. configurable: true
  99905. });
  99906. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99907. /**
  99908. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99909. */
  99910. get: function () {
  99911. return this._positionScale;
  99912. },
  99913. /**
  99914. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99915. */
  99916. set: function (scale) {
  99917. this._positionScale = scale;
  99918. },
  99919. enumerable: true,
  99920. configurable: true
  99921. });
  99922. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99923. /**
  99924. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99925. * behaviour is triggered, in radians.
  99926. */
  99927. get: function () {
  99928. return this._defaultElevation;
  99929. },
  99930. /**
  99931. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99932. * behaviour is triggered, in radians.
  99933. */
  99934. set: function (elevation) {
  99935. this._defaultElevation = elevation;
  99936. },
  99937. enumerable: true,
  99938. configurable: true
  99939. });
  99940. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99941. /**
  99942. * Gets the time (in milliseconds) taken to return to the default beta position.
  99943. * Negative value indicates camera should not return to default.
  99944. */
  99945. get: function () {
  99946. return this._elevationReturnTime;
  99947. },
  99948. /**
  99949. * Sets the time (in milliseconds) taken to return to the default beta position.
  99950. * Negative value indicates camera should not return to default.
  99951. */
  99952. set: function (speed) {
  99953. this._elevationReturnTime = speed;
  99954. },
  99955. enumerable: true,
  99956. configurable: true
  99957. });
  99958. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99959. /**
  99960. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99961. */
  99962. get: function () {
  99963. return this._elevationReturnWaitTime;
  99964. },
  99965. /**
  99966. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99967. */
  99968. set: function (time) {
  99969. this._elevationReturnWaitTime = time;
  99970. },
  99971. enumerable: true,
  99972. configurable: true
  99973. });
  99974. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99975. /**
  99976. * Gets the flag that indicates if user zooming should stop animation.
  99977. */
  99978. get: function () {
  99979. return this._zoomStopsAnimation;
  99980. },
  99981. /**
  99982. * Sets the flag that indicates if user zooming should stop animation.
  99983. */
  99984. set: function (flag) {
  99985. this._zoomStopsAnimation = flag;
  99986. },
  99987. enumerable: true,
  99988. configurable: true
  99989. });
  99990. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99991. /**
  99992. * Gets the transition time when framing the mesh, in milliseconds
  99993. */
  99994. get: function () {
  99995. return this._framingTime;
  99996. },
  99997. /**
  99998. * Sets the transition time when framing the mesh, in milliseconds
  99999. */
  100000. set: function (time) {
  100001. this._framingTime = time;
  100002. },
  100003. enumerable: true,
  100004. configurable: true
  100005. });
  100006. FramingBehavior.prototype.init = function () {
  100007. // Do notihng
  100008. };
  100009. FramingBehavior.prototype.attach = function (camera) {
  100010. var _this = this;
  100011. this._attachedCamera = camera;
  100012. var scene = this._attachedCamera.getScene();
  100013. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100014. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100015. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100016. _this._isPointerDown = true;
  100017. return;
  100018. }
  100019. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100020. _this._isPointerDown = false;
  100021. }
  100022. });
  100023. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100024. if (mesh) {
  100025. _this.zoomOnMesh(mesh);
  100026. }
  100027. });
  100028. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100029. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100030. _this._applyUserInteraction();
  100031. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100032. // back to the default position after a given timeout
  100033. _this._maintainCameraAboveGround();
  100034. });
  100035. };
  100036. FramingBehavior.prototype.detach = function () {
  100037. if (!this._attachedCamera) {
  100038. return;
  100039. }
  100040. var scene = this._attachedCamera.getScene();
  100041. if (this._onPrePointerObservableObserver) {
  100042. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100043. }
  100044. if (this._onAfterCheckInputsObserver) {
  100045. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100046. }
  100047. if (this._onMeshTargetChangedObserver) {
  100048. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100049. }
  100050. this._attachedCamera = null;
  100051. };
  100052. /**
  100053. * Targets the given mesh and updates zoom level accordingly.
  100054. * @param mesh The mesh to target.
  100055. * @param radius Optional. If a cached radius position already exists, overrides default.
  100056. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100057. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100058. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100059. */
  100060. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100061. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100062. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100063. mesh.computeWorldMatrix(true);
  100064. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100065. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100066. };
  100067. /**
  100068. * Targets the given mesh with its children and updates zoom level accordingly.
  100069. * @param mesh The mesh to target.
  100070. * @param radius Optional. If a cached radius position already exists, overrides default.
  100071. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100072. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100073. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100074. */
  100075. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100076. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100077. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100078. mesh.computeWorldMatrix(true);
  100079. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100080. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100081. };
  100082. /**
  100083. * Targets the given meshes with their children and updates zoom level accordingly.
  100084. * @param meshes The mesh to target.
  100085. * @param radius Optional. If a cached radius position already exists, overrides default.
  100086. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100087. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100088. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100089. */
  100090. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100091. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100092. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100093. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100094. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100095. for (var i = 0; i < meshes.length; i++) {
  100096. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100097. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100098. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100099. }
  100100. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100101. };
  100102. /**
  100103. * Targets the given mesh and updates zoom level accordingly.
  100104. * @param mesh The mesh to target.
  100105. * @param radius Optional. If a cached radius position already exists, overrides default.
  100106. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100107. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100108. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100109. */
  100110. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100111. var _this = this;
  100112. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100113. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100114. var zoomTarget;
  100115. if (!this._attachedCamera) {
  100116. return;
  100117. }
  100118. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100119. var bottom = minimumWorld.y;
  100120. var top = maximumWorld.y;
  100121. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100122. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100123. if (focusOnOriginXZ) {
  100124. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100125. }
  100126. else {
  100127. var centerWorld = minimumWorld.add(radiusWorld);
  100128. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100129. }
  100130. if (!this._vectorTransition) {
  100131. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100132. }
  100133. this._betaIsAnimating = true;
  100134. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100135. if (animatable) {
  100136. this._animatables.push(animatable);
  100137. }
  100138. // sets the radius and lower radius bounds
  100139. // Small delta ensures camera is not always at lower zoom limit.
  100140. var radius = 0;
  100141. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100142. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100143. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100144. radius = position;
  100145. }
  100146. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100147. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100148. if (this._attachedCamera.lowerRadiusLimit === null) {
  100149. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100150. }
  100151. }
  100152. // Set sensibilities
  100153. var extend = maximumWorld.subtract(minimumWorld).length();
  100154. this._attachedCamera.panningSensibility = 5000 / extend;
  100155. this._attachedCamera.wheelPrecision = 100 / radius;
  100156. // transition to new radius
  100157. if (!this._radiusTransition) {
  100158. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100159. }
  100160. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100161. _this.stopAllAnimations();
  100162. if (onAnimationEnd) {
  100163. onAnimationEnd();
  100164. }
  100165. if (_this._attachedCamera) {
  100166. _this._attachedCamera.storeState();
  100167. }
  100168. });
  100169. if (animatable) {
  100170. this._animatables.push(animatable);
  100171. }
  100172. };
  100173. /**
  100174. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100175. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100176. * frustum width.
  100177. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100178. * to fully enclose the mesh in the viewing frustum.
  100179. */
  100180. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100181. var size = maximumWorld.subtract(minimumWorld);
  100182. var boxVectorGlobalDiagonal = size.length();
  100183. var frustumSlope = this._getFrustumSlope();
  100184. // Formula for setting distance
  100185. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100186. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100187. // Horizon distance
  100188. var radius = radiusWithoutFraming * this._radiusScale;
  100189. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100190. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100191. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100192. var camera = this._attachedCamera;
  100193. if (!camera) {
  100194. return 0;
  100195. }
  100196. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100197. // Don't exceed the requested limit
  100198. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100199. }
  100200. // Don't exceed the upper radius limit
  100201. if (camera.upperRadiusLimit) {
  100202. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100203. }
  100204. return distance;
  100205. };
  100206. /**
  100207. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100208. * is automatically returned to its default position (expected to be above ground plane).
  100209. */
  100210. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100211. var _this = this;
  100212. if (this._elevationReturnTime < 0) {
  100213. return;
  100214. }
  100215. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100216. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100217. var limitBeta = Math.PI * 0.5;
  100218. // Bring the camera back up if below the ground plane
  100219. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100220. this._betaIsAnimating = true;
  100221. //Transition to new position
  100222. this.stopAllAnimations();
  100223. if (!this._betaTransition) {
  100224. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100225. }
  100226. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100227. _this._clearAnimationLocks();
  100228. _this.stopAllAnimations();
  100229. });
  100230. if (animatabe) {
  100231. this._animatables.push(animatabe);
  100232. }
  100233. }
  100234. };
  100235. /**
  100236. * Returns the frustum slope based on the canvas ratio and camera FOV
  100237. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100238. */
  100239. FramingBehavior.prototype._getFrustumSlope = function () {
  100240. // Calculate the viewport ratio
  100241. // Aspect Ratio is Height/Width.
  100242. var camera = this._attachedCamera;
  100243. if (!camera) {
  100244. return BABYLON.Vector2.Zero();
  100245. }
  100246. var engine = camera.getScene().getEngine();
  100247. var aspectRatio = engine.getAspectRatio(camera);
  100248. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100249. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100250. var frustumSlopeY = Math.tan(camera.fov / 2);
  100251. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100252. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100253. // along the forward vector.
  100254. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100255. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100256. };
  100257. /**
  100258. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100259. */
  100260. FramingBehavior.prototype._clearAnimationLocks = function () {
  100261. this._betaIsAnimating = false;
  100262. };
  100263. /**
  100264. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100265. */
  100266. FramingBehavior.prototype._applyUserInteraction = function () {
  100267. if (this.isUserIsMoving) {
  100268. this._lastInteractionTime = BABYLON.Tools.Now;
  100269. this.stopAllAnimations();
  100270. this._clearAnimationLocks();
  100271. }
  100272. };
  100273. /**
  100274. * Stops and removes all animations that have been applied to the camera
  100275. */
  100276. FramingBehavior.prototype.stopAllAnimations = function () {
  100277. if (this._attachedCamera) {
  100278. this._attachedCamera.animations = [];
  100279. }
  100280. while (this._animatables.length) {
  100281. if (this._animatables[0]) {
  100282. this._animatables[0].onAnimationEnd = null;
  100283. this._animatables[0].stop();
  100284. }
  100285. this._animatables.shift();
  100286. }
  100287. };
  100288. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100289. /**
  100290. * Gets a value indicating if the user is moving the camera
  100291. */
  100292. get: function () {
  100293. if (!this._attachedCamera) {
  100294. return false;
  100295. }
  100296. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100297. this._attachedCamera.inertialBetaOffset !== 0 ||
  100298. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100299. this._attachedCamera.inertialPanningX !== 0 ||
  100300. this._attachedCamera.inertialPanningY !== 0 ||
  100301. this._isPointerDown;
  100302. },
  100303. enumerable: true,
  100304. configurable: true
  100305. });
  100306. /**
  100307. * The easing function used by animations
  100308. */
  100309. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100310. /**
  100311. * The easing mode used by animations
  100312. */
  100313. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100314. // Statics
  100315. /**
  100316. * The camera can move all the way towards the mesh.
  100317. */
  100318. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100319. /**
  100320. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100321. */
  100322. FramingBehavior.FitFrustumSidesMode = 1;
  100323. return FramingBehavior;
  100324. }());
  100325. BABYLON.FramingBehavior = FramingBehavior;
  100326. })(BABYLON || (BABYLON = {}));
  100327. //# sourceMappingURL=babylon.framingBehavior.js.map
  100328. var BABYLON;
  100329. (function (BABYLON) {
  100330. /**
  100331. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100332. */
  100333. var BouncingBehavior = /** @class */ (function () {
  100334. function BouncingBehavior() {
  100335. /**
  100336. * The duration of the animation, in milliseconds
  100337. */
  100338. this.transitionDuration = 450;
  100339. /**
  100340. * Length of the distance animated by the transition when lower radius is reached
  100341. */
  100342. this.lowerRadiusTransitionRange = 2;
  100343. /**
  100344. * Length of the distance animated by the transition when upper radius is reached
  100345. */
  100346. this.upperRadiusTransitionRange = -2;
  100347. this._autoTransitionRange = false;
  100348. // Animations
  100349. this._radiusIsAnimating = false;
  100350. this._radiusBounceTransition = null;
  100351. this._animatables = new Array();
  100352. }
  100353. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100354. get: function () {
  100355. return "Bouncing";
  100356. },
  100357. enumerable: true,
  100358. configurable: true
  100359. });
  100360. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100361. /**
  100362. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100363. */
  100364. get: function () {
  100365. return this._autoTransitionRange;
  100366. },
  100367. /**
  100368. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100369. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100370. */
  100371. set: function (value) {
  100372. var _this = this;
  100373. if (this._autoTransitionRange === value) {
  100374. return;
  100375. }
  100376. this._autoTransitionRange = value;
  100377. var camera = this._attachedCamera;
  100378. if (!camera) {
  100379. return;
  100380. }
  100381. if (value) {
  100382. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100383. if (!mesh) {
  100384. return;
  100385. }
  100386. mesh.computeWorldMatrix(true);
  100387. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100388. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100389. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100390. });
  100391. }
  100392. else if (this._onMeshTargetChangedObserver) {
  100393. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100394. }
  100395. },
  100396. enumerable: true,
  100397. configurable: true
  100398. });
  100399. BouncingBehavior.prototype.init = function () {
  100400. // Do notihng
  100401. };
  100402. BouncingBehavior.prototype.attach = function (camera) {
  100403. var _this = this;
  100404. this._attachedCamera = camera;
  100405. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100406. if (!_this._attachedCamera) {
  100407. return;
  100408. }
  100409. // Add the bounce animation to the lower radius limit
  100410. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100411. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100412. }
  100413. // Add the bounce animation to the upper radius limit
  100414. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100415. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100416. }
  100417. });
  100418. };
  100419. BouncingBehavior.prototype.detach = function () {
  100420. if (!this._attachedCamera) {
  100421. return;
  100422. }
  100423. if (this._onAfterCheckInputsObserver) {
  100424. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100425. }
  100426. if (this._onMeshTargetChangedObserver) {
  100427. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100428. }
  100429. this._attachedCamera = null;
  100430. };
  100431. /**
  100432. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100433. * @param radiusLimit The limit to check against.
  100434. * @return Bool to indicate if at limit.
  100435. */
  100436. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100437. if (!this._attachedCamera) {
  100438. return false;
  100439. }
  100440. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100441. return true;
  100442. }
  100443. return false;
  100444. };
  100445. /**
  100446. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100447. * @param radiusDelta The delta by which to animate to. Can be negative.
  100448. */
  100449. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100450. var _this = this;
  100451. if (!this._attachedCamera) {
  100452. return;
  100453. }
  100454. if (!this._radiusBounceTransition) {
  100455. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100456. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100457. }
  100458. // Prevent zoom until bounce has completed
  100459. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100460. this._attachedCamera.wheelPrecision = Infinity;
  100461. this._attachedCamera.inertialRadiusOffset = 0;
  100462. // Animate to the radius limit
  100463. this.stopAllAnimations();
  100464. this._radiusIsAnimating = true;
  100465. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100466. if (animatable) {
  100467. this._animatables.push(animatable);
  100468. }
  100469. };
  100470. /**
  100471. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100472. */
  100473. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100474. this._radiusIsAnimating = false;
  100475. if (this._attachedCamera) {
  100476. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100477. }
  100478. };
  100479. /**
  100480. * Stops and removes all animations that have been applied to the camera
  100481. */
  100482. BouncingBehavior.prototype.stopAllAnimations = function () {
  100483. if (this._attachedCamera) {
  100484. this._attachedCamera.animations = [];
  100485. }
  100486. while (this._animatables.length) {
  100487. this._animatables[0].onAnimationEnd = null;
  100488. this._animatables[0].stop();
  100489. this._animatables.shift();
  100490. }
  100491. };
  100492. /**
  100493. * The easing function used by animations
  100494. */
  100495. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100496. /**
  100497. * The easing mode used by animations
  100498. */
  100499. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100500. return BouncingBehavior;
  100501. }());
  100502. BABYLON.BouncingBehavior = BouncingBehavior;
  100503. })(BABYLON || (BABYLON = {}));
  100504. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100505. var BABYLON;
  100506. (function (BABYLON) {
  100507. var AutoRotationBehavior = /** @class */ (function () {
  100508. function AutoRotationBehavior() {
  100509. this._zoomStopsAnimation = false;
  100510. this._idleRotationSpeed = 0.05;
  100511. this._idleRotationWaitTime = 2000;
  100512. this._idleRotationSpinupTime = 2000;
  100513. this._isPointerDown = false;
  100514. this._lastFrameTime = null;
  100515. this._lastInteractionTime = -Infinity;
  100516. this._cameraRotationSpeed = 0;
  100517. this._lastFrameRadius = 0;
  100518. }
  100519. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100520. get: function () {
  100521. return "AutoRotation";
  100522. },
  100523. enumerable: true,
  100524. configurable: true
  100525. });
  100526. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100527. /**
  100528. * Gets the flag that indicates if user zooming should stop animation.
  100529. */
  100530. get: function () {
  100531. return this._zoomStopsAnimation;
  100532. },
  100533. /**
  100534. * Sets the flag that indicates if user zooming should stop animation.
  100535. */
  100536. set: function (flag) {
  100537. this._zoomStopsAnimation = flag;
  100538. },
  100539. enumerable: true,
  100540. configurable: true
  100541. });
  100542. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100543. /**
  100544. * Gets the default speed at which the camera rotates around the model.
  100545. */
  100546. get: function () {
  100547. return this._idleRotationSpeed;
  100548. },
  100549. /**
  100550. * Sets the default speed at which the camera rotates around the model.
  100551. */
  100552. set: function (speed) {
  100553. this._idleRotationSpeed = speed;
  100554. },
  100555. enumerable: true,
  100556. configurable: true
  100557. });
  100558. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100559. /**
  100560. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100561. */
  100562. get: function () {
  100563. return this._idleRotationWaitTime;
  100564. },
  100565. /**
  100566. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100567. */
  100568. set: function (time) {
  100569. this._idleRotationWaitTime = time;
  100570. },
  100571. enumerable: true,
  100572. configurable: true
  100573. });
  100574. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100575. /**
  100576. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100577. */
  100578. get: function () {
  100579. return this._idleRotationSpinupTime;
  100580. },
  100581. /**
  100582. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100583. */
  100584. set: function (time) {
  100585. this._idleRotationSpinupTime = time;
  100586. },
  100587. enumerable: true,
  100588. configurable: true
  100589. });
  100590. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100591. /**
  100592. * Gets a value indicating if the camera is currently rotating because of this behavior
  100593. */
  100594. get: function () {
  100595. return Math.abs(this._cameraRotationSpeed) > 0;
  100596. },
  100597. enumerable: true,
  100598. configurable: true
  100599. });
  100600. AutoRotationBehavior.prototype.init = function () {
  100601. // Do notihng
  100602. };
  100603. AutoRotationBehavior.prototype.attach = function (camera) {
  100604. var _this = this;
  100605. this._attachedCamera = camera;
  100606. var scene = this._attachedCamera.getScene();
  100607. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100608. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100609. _this._isPointerDown = true;
  100610. return;
  100611. }
  100612. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100613. _this._isPointerDown = false;
  100614. }
  100615. });
  100616. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100617. var now = BABYLON.Tools.Now;
  100618. var dt = 0;
  100619. if (_this._lastFrameTime != null) {
  100620. dt = now - _this._lastFrameTime;
  100621. }
  100622. _this._lastFrameTime = now;
  100623. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100624. _this._applyUserInteraction();
  100625. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100626. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100627. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100628. // Step camera rotation by rotation speed
  100629. if (_this._attachedCamera) {
  100630. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100631. }
  100632. });
  100633. };
  100634. AutoRotationBehavior.prototype.detach = function () {
  100635. if (!this._attachedCamera) {
  100636. return;
  100637. }
  100638. var scene = this._attachedCamera.getScene();
  100639. if (this._onPrePointerObservableObserver) {
  100640. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100641. }
  100642. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100643. this._attachedCamera = null;
  100644. };
  100645. /**
  100646. * Returns true if user is scrolling.
  100647. * @return true if user is scrolling.
  100648. */
  100649. AutoRotationBehavior.prototype._userIsZooming = function () {
  100650. if (!this._attachedCamera) {
  100651. return false;
  100652. }
  100653. return this._attachedCamera.inertialRadiusOffset !== 0;
  100654. };
  100655. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100656. if (!this._attachedCamera) {
  100657. return false;
  100658. }
  100659. var zoomHasHitLimit = false;
  100660. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100661. zoomHasHitLimit = true;
  100662. }
  100663. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100664. this._lastFrameRadius = this._attachedCamera.radius;
  100665. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100666. };
  100667. /**
  100668. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100669. */
  100670. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100671. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100672. this._lastInteractionTime = BABYLON.Tools.Now;
  100673. }
  100674. };
  100675. // Tools
  100676. AutoRotationBehavior.prototype._userIsMoving = function () {
  100677. if (!this._attachedCamera) {
  100678. return false;
  100679. }
  100680. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100681. this._attachedCamera.inertialBetaOffset !== 0 ||
  100682. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100683. this._attachedCamera.inertialPanningX !== 0 ||
  100684. this._attachedCamera.inertialPanningY !== 0 ||
  100685. this._isPointerDown;
  100686. };
  100687. return AutoRotationBehavior;
  100688. }());
  100689. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100690. })(BABYLON || (BABYLON = {}));
  100691. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100692. var BABYLON;
  100693. (function (BABYLON) {
  100694. var NullEngineOptions = /** @class */ (function () {
  100695. function NullEngineOptions() {
  100696. this.renderWidth = 512;
  100697. this.renderHeight = 256;
  100698. this.textureSize = 512;
  100699. this.deterministicLockstep = false;
  100700. this.lockstepMaxSteps = 4;
  100701. }
  100702. return NullEngineOptions;
  100703. }());
  100704. BABYLON.NullEngineOptions = NullEngineOptions;
  100705. /**
  100706. * The null engine class provides support for headless version of babylon.js.
  100707. * This can be used in server side scenario or for testing purposes
  100708. */
  100709. var NullEngine = /** @class */ (function (_super) {
  100710. __extends(NullEngine, _super);
  100711. function NullEngine(options) {
  100712. if (options === void 0) { options = new NullEngineOptions(); }
  100713. var _this = _super.call(this, null) || this;
  100714. if (options.deterministicLockstep === undefined) {
  100715. options.deterministicLockstep = false;
  100716. }
  100717. if (options.lockstepMaxSteps === undefined) {
  100718. options.lockstepMaxSteps = 4;
  100719. }
  100720. _this._options = options;
  100721. // Init caps
  100722. // We consider we are on a webgl1 capable device
  100723. _this._caps = new BABYLON.EngineCapabilities();
  100724. _this._caps.maxTexturesImageUnits = 16;
  100725. _this._caps.maxVertexTextureImageUnits = 16;
  100726. _this._caps.maxTextureSize = 512;
  100727. _this._caps.maxCubemapTextureSize = 512;
  100728. _this._caps.maxRenderTextureSize = 512;
  100729. _this._caps.maxVertexAttribs = 16;
  100730. _this._caps.maxVaryingVectors = 16;
  100731. _this._caps.maxFragmentUniformVectors = 16;
  100732. _this._caps.maxVertexUniformVectors = 16;
  100733. // Extensions
  100734. _this._caps.standardDerivatives = false;
  100735. _this._caps.astc = null;
  100736. _this._caps.s3tc = null;
  100737. _this._caps.pvrtc = null;
  100738. _this._caps.etc1 = null;
  100739. _this._caps.etc2 = null;
  100740. _this._caps.textureAnisotropicFilterExtension = null;
  100741. _this._caps.maxAnisotropy = 0;
  100742. _this._caps.uintIndices = false;
  100743. _this._caps.fragmentDepthSupported = false;
  100744. _this._caps.highPrecisionShaderSupported = true;
  100745. _this._caps.colorBufferFloat = false;
  100746. _this._caps.textureFloat = false;
  100747. _this._caps.textureFloatLinearFiltering = false;
  100748. _this._caps.textureFloatRender = false;
  100749. _this._caps.textureHalfFloat = false;
  100750. _this._caps.textureHalfFloatLinearFiltering = false;
  100751. _this._caps.textureHalfFloatRender = false;
  100752. _this._caps.textureLOD = false;
  100753. _this._caps.drawBuffersExtension = false;
  100754. _this._caps.depthTextureExtension = false;
  100755. _this._caps.vertexArrayObject = false;
  100756. _this._caps.instancedArrays = false;
  100757. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100758. // Wrappers
  100759. if (typeof URL === "undefined") {
  100760. URL = {
  100761. createObjectURL: function () { },
  100762. revokeObjectURL: function () { }
  100763. };
  100764. }
  100765. if (typeof Blob === "undefined") {
  100766. Blob = function () { };
  100767. }
  100768. return _this;
  100769. }
  100770. NullEngine.prototype.isDeterministicLockStep = function () {
  100771. return this._options.deterministicLockstep;
  100772. };
  100773. NullEngine.prototype.getLockstepMaxSteps = function () {
  100774. return this._options.lockstepMaxSteps;
  100775. };
  100776. NullEngine.prototype.getHardwareScalingLevel = function () {
  100777. return 1.0;
  100778. };
  100779. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100780. return {
  100781. capacity: 0,
  100782. references: 1,
  100783. is32Bits: false
  100784. };
  100785. };
  100786. NullEngine.prototype.createIndexBuffer = function (indices) {
  100787. return {
  100788. capacity: 0,
  100789. references: 1,
  100790. is32Bits: false
  100791. };
  100792. };
  100793. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100794. if (stencil === void 0) { stencil = false; }
  100795. };
  100796. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100797. if (useScreen === void 0) { useScreen = false; }
  100798. if (!useScreen && this._currentRenderTarget) {
  100799. return this._currentRenderTarget.width;
  100800. }
  100801. return this._options.renderWidth;
  100802. };
  100803. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100804. if (useScreen === void 0) { useScreen = false; }
  100805. if (!useScreen && this._currentRenderTarget) {
  100806. return this._currentRenderTarget.height;
  100807. }
  100808. return this._options.renderHeight;
  100809. };
  100810. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100811. this._cachedViewport = viewport;
  100812. };
  100813. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100814. return {
  100815. transformFeedback: null,
  100816. __SPECTOR_rebuildProgram: null
  100817. };
  100818. };
  100819. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100820. return [];
  100821. };
  100822. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100823. return [];
  100824. };
  100825. NullEngine.prototype.bindSamplers = function (effect) {
  100826. this._currentEffect = null;
  100827. };
  100828. NullEngine.prototype.enableEffect = function (effect) {
  100829. this._currentEffect = effect;
  100830. if (effect.onBind) {
  100831. effect.onBind(effect);
  100832. }
  100833. effect.onBindObservable.notifyObservers(effect);
  100834. };
  100835. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100836. if (zOffset === void 0) { zOffset = 0; }
  100837. if (reverseSide === void 0) { reverseSide = false; }
  100838. };
  100839. NullEngine.prototype.setIntArray = function (uniform, array) {
  100840. };
  100841. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100842. };
  100843. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100844. };
  100845. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100846. };
  100847. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100848. };
  100849. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100850. };
  100851. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100852. };
  100853. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100854. };
  100855. NullEngine.prototype.setArray = function (uniform, array) {
  100856. };
  100857. NullEngine.prototype.setArray2 = function (uniform, array) {
  100858. };
  100859. NullEngine.prototype.setArray3 = function (uniform, array) {
  100860. };
  100861. NullEngine.prototype.setArray4 = function (uniform, array) {
  100862. };
  100863. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100864. };
  100865. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100866. };
  100867. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100868. };
  100869. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100870. };
  100871. NullEngine.prototype.setFloat = function (uniform, value) {
  100872. };
  100873. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100874. };
  100875. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100876. };
  100877. NullEngine.prototype.setBool = function (uniform, bool) {
  100878. };
  100879. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100880. };
  100881. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100882. };
  100883. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100884. };
  100885. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100886. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100887. if (this._alphaMode === mode) {
  100888. return;
  100889. }
  100890. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100891. if (!noDepthWriteChange) {
  100892. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100893. }
  100894. this._alphaMode = mode;
  100895. };
  100896. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100897. };
  100898. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100899. if (this.preventCacheWipeBetweenFrames) {
  100900. return;
  100901. }
  100902. this.resetTextureCache();
  100903. this._currentEffect = null;
  100904. if (bruteForce) {
  100905. this._currentProgram = null;
  100906. this._stencilState.reset();
  100907. this._depthCullingState.reset();
  100908. this._alphaState.reset();
  100909. }
  100910. this._cachedVertexBuffers = null;
  100911. this._cachedIndexBuffer = null;
  100912. this._cachedEffectForVertexBuffers = null;
  100913. };
  100914. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100915. };
  100916. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100917. };
  100918. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100919. };
  100920. NullEngine.prototype._createTexture = function () {
  100921. return {};
  100922. };
  100923. NullEngine.prototype._releaseTexture = function (texture) {
  100924. };
  100925. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100927. if (onLoad === void 0) { onLoad = null; }
  100928. if (onError === void 0) { onError = null; }
  100929. if (buffer === void 0) { buffer = null; }
  100930. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100931. var url = String(urlArg);
  100932. texture.url = url;
  100933. texture.generateMipMaps = !noMipmap;
  100934. texture.samplingMode = samplingMode;
  100935. texture.invertY = invertY;
  100936. texture.baseWidth = this._options.textureSize;
  100937. texture.baseHeight = this._options.textureSize;
  100938. texture.width = this._options.textureSize;
  100939. texture.height = this._options.textureSize;
  100940. if (format) {
  100941. texture.format = format;
  100942. }
  100943. texture.isReady = true;
  100944. if (onLoad) {
  100945. onLoad();
  100946. }
  100947. this._internalTexturesCache.push(texture);
  100948. return texture;
  100949. };
  100950. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100951. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100952. if (options !== undefined && typeof options === "object") {
  100953. fullOptions.generateMipMaps = options.generateMipMaps;
  100954. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100955. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100956. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100957. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100958. }
  100959. else {
  100960. fullOptions.generateMipMaps = options;
  100961. fullOptions.generateDepthBuffer = true;
  100962. fullOptions.generateStencilBuffer = false;
  100963. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100964. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100965. }
  100966. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100967. var width = size.width || size;
  100968. var height = size.height || size;
  100969. texture._depthStencilBuffer = {};
  100970. texture._framebuffer = {};
  100971. texture.baseWidth = width;
  100972. texture.baseHeight = height;
  100973. texture.width = width;
  100974. texture.height = height;
  100975. texture.isReady = true;
  100976. texture.samples = 1;
  100977. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100978. texture.samplingMode = fullOptions.samplingMode;
  100979. texture.type = fullOptions.type;
  100980. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100981. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100982. this._internalTexturesCache.push(texture);
  100983. return texture;
  100984. };
  100985. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100986. texture.samplingMode = samplingMode;
  100987. };
  100988. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100989. if (this._currentRenderTarget) {
  100990. this.unBindFramebuffer(this._currentRenderTarget);
  100991. }
  100992. this._currentRenderTarget = texture;
  100993. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100994. if (this._cachedViewport && !forceFullscreenViewport) {
  100995. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100996. }
  100997. };
  100998. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100999. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101000. this._currentRenderTarget = null;
  101001. if (onBeforeUnbind) {
  101002. if (texture._MSAAFramebuffer) {
  101003. this._currentFramebuffer = texture._framebuffer;
  101004. }
  101005. onBeforeUnbind();
  101006. }
  101007. this._currentFramebuffer = null;
  101008. };
  101009. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101010. var vbo = {
  101011. capacity: 1,
  101012. references: 1,
  101013. is32Bits: false
  101014. };
  101015. return vbo;
  101016. };
  101017. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101018. if (premulAlpha === void 0) { premulAlpha = false; }
  101019. };
  101020. /**
  101021. * Get the current error code of the webGL context
  101022. * @returns the error code
  101023. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101024. */
  101025. NullEngine.prototype.getError = function () {
  101026. return 0;
  101027. };
  101028. /** @hidden */
  101029. NullEngine.prototype._getUnpackAlignement = function () {
  101030. return 1;
  101031. };
  101032. /** @hidden */
  101033. NullEngine.prototype._unpackFlipY = function (value) {
  101034. };
  101035. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101036. if (offset === void 0) { offset = 0; }
  101037. };
  101038. /**
  101039. * Updates a dynamic vertex buffer.
  101040. * @param vertexBuffer the vertex buffer to update
  101041. * @param data the data used to update the vertex buffer
  101042. * @param byteOffset the byte offset of the data (optional)
  101043. * @param byteLength the byte length of the data (optional)
  101044. */
  101045. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101046. };
  101047. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101048. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101049. this._boundTexturesCache[this._activeChannel] = texture;
  101050. return true;
  101051. }
  101052. return false;
  101053. };
  101054. NullEngine.prototype._bindTexture = function (channel, texture) {
  101055. if (channel < 0) {
  101056. return;
  101057. }
  101058. this._bindTextureDirectly(0, texture);
  101059. };
  101060. NullEngine.prototype._releaseBuffer = function (buffer) {
  101061. buffer.references--;
  101062. if (buffer.references === 0) {
  101063. return true;
  101064. }
  101065. return false;
  101066. };
  101067. NullEngine.prototype.releaseEffects = function () {
  101068. };
  101069. NullEngine.prototype.displayLoadingUI = function () {
  101070. };
  101071. NullEngine.prototype.hideLoadingUI = function () {
  101072. };
  101073. /** @hidden */
  101074. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101075. if (faceIndex === void 0) { faceIndex = 0; }
  101076. if (lod === void 0) { lod = 0; }
  101077. };
  101078. /** @hidden */
  101079. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101080. if (faceIndex === void 0) { faceIndex = 0; }
  101081. if (lod === void 0) { lod = 0; }
  101082. };
  101083. /** @hidden */
  101084. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101085. if (faceIndex === void 0) { faceIndex = 0; }
  101086. if (lod === void 0) { lod = 0; }
  101087. };
  101088. /** @hidden */
  101089. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101090. if (faceIndex === void 0) { faceIndex = 0; }
  101091. if (lod === void 0) { lod = 0; }
  101092. };
  101093. return NullEngine;
  101094. }(BABYLON.Engine));
  101095. BABYLON.NullEngine = NullEngine;
  101096. })(BABYLON || (BABYLON = {}));
  101097. //# sourceMappingURL=babylon.nullEngine.js.map
  101098. var BABYLON;
  101099. (function (BABYLON) {
  101100. /**
  101101. * This class can be used to get instrumentation data from a Babylon engine
  101102. */
  101103. var EngineInstrumentation = /** @class */ (function () {
  101104. function EngineInstrumentation(engine) {
  101105. this.engine = engine;
  101106. this._captureGPUFrameTime = false;
  101107. this._gpuFrameTime = new BABYLON.PerfCounter();
  101108. this._captureShaderCompilationTime = false;
  101109. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101110. // Observers
  101111. this._onBeginFrameObserver = null;
  101112. this._onEndFrameObserver = null;
  101113. this._onBeforeShaderCompilationObserver = null;
  101114. this._onAfterShaderCompilationObserver = null;
  101115. }
  101116. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101117. // Properties
  101118. /**
  101119. * Gets the perf counter used for GPU frame time
  101120. */
  101121. get: function () {
  101122. return this._gpuFrameTime;
  101123. },
  101124. enumerable: true,
  101125. configurable: true
  101126. });
  101127. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101128. /**
  101129. * Gets the GPU frame time capture status
  101130. */
  101131. get: function () {
  101132. return this._captureGPUFrameTime;
  101133. },
  101134. /**
  101135. * Enable or disable the GPU frame time capture
  101136. */
  101137. set: function (value) {
  101138. var _this = this;
  101139. if (value === this._captureGPUFrameTime) {
  101140. return;
  101141. }
  101142. this._captureGPUFrameTime = value;
  101143. if (value) {
  101144. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101145. if (!_this._gpuFrameTimeToken) {
  101146. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101147. }
  101148. });
  101149. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101150. if (!_this._gpuFrameTimeToken) {
  101151. return;
  101152. }
  101153. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101154. if (time > -1) {
  101155. _this._gpuFrameTimeToken = null;
  101156. _this._gpuFrameTime.fetchNewFrame();
  101157. _this._gpuFrameTime.addCount(time, true);
  101158. }
  101159. });
  101160. }
  101161. else {
  101162. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101163. this._onBeginFrameObserver = null;
  101164. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101165. this._onEndFrameObserver = null;
  101166. }
  101167. },
  101168. enumerable: true,
  101169. configurable: true
  101170. });
  101171. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101172. /**
  101173. * Gets the perf counter used for shader compilation time
  101174. */
  101175. get: function () {
  101176. return this._shaderCompilationTime;
  101177. },
  101178. enumerable: true,
  101179. configurable: true
  101180. });
  101181. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101182. /**
  101183. * Gets the shader compilation time capture status
  101184. */
  101185. get: function () {
  101186. return this._captureShaderCompilationTime;
  101187. },
  101188. /**
  101189. * Enable or disable the shader compilation time capture
  101190. */
  101191. set: function (value) {
  101192. var _this = this;
  101193. if (value === this._captureShaderCompilationTime) {
  101194. return;
  101195. }
  101196. this._captureShaderCompilationTime = value;
  101197. if (value) {
  101198. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101199. _this._shaderCompilationTime.fetchNewFrame();
  101200. _this._shaderCompilationTime.beginMonitoring();
  101201. });
  101202. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101203. _this._shaderCompilationTime.endMonitoring();
  101204. });
  101205. }
  101206. else {
  101207. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101208. this._onBeforeShaderCompilationObserver = null;
  101209. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101210. this._onAfterShaderCompilationObserver = null;
  101211. }
  101212. },
  101213. enumerable: true,
  101214. configurable: true
  101215. });
  101216. EngineInstrumentation.prototype.dispose = function () {
  101217. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101218. this._onBeginFrameObserver = null;
  101219. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101220. this._onEndFrameObserver = null;
  101221. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101222. this._onBeforeShaderCompilationObserver = null;
  101223. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101224. this._onAfterShaderCompilationObserver = null;
  101225. this.engine = null;
  101226. };
  101227. return EngineInstrumentation;
  101228. }());
  101229. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101230. })(BABYLON || (BABYLON = {}));
  101231. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101232. var BABYLON;
  101233. (function (BABYLON) {
  101234. /**
  101235. * This class can be used to get instrumentation data from a Babylon engine
  101236. */
  101237. var SceneInstrumentation = /** @class */ (function () {
  101238. function SceneInstrumentation(scene) {
  101239. var _this = this;
  101240. this.scene = scene;
  101241. this._captureActiveMeshesEvaluationTime = false;
  101242. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101243. this._captureRenderTargetsRenderTime = false;
  101244. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101245. this._captureFrameTime = false;
  101246. this._frameTime = new BABYLON.PerfCounter();
  101247. this._captureRenderTime = false;
  101248. this._renderTime = new BABYLON.PerfCounter();
  101249. this._captureInterFrameTime = false;
  101250. this._interFrameTime = new BABYLON.PerfCounter();
  101251. this._captureParticlesRenderTime = false;
  101252. this._particlesRenderTime = new BABYLON.PerfCounter();
  101253. this._captureSpritesRenderTime = false;
  101254. this._spritesRenderTime = new BABYLON.PerfCounter();
  101255. this._capturePhysicsTime = false;
  101256. this._physicsTime = new BABYLON.PerfCounter();
  101257. this._captureAnimationsTime = false;
  101258. this._animationsTime = new BABYLON.PerfCounter();
  101259. this._captureCameraRenderTime = false;
  101260. this._cameraRenderTime = new BABYLON.PerfCounter();
  101261. // Observers
  101262. this._onBeforeActiveMeshesEvaluationObserver = null;
  101263. this._onAfterActiveMeshesEvaluationObserver = null;
  101264. this._onBeforeRenderTargetsRenderObserver = null;
  101265. this._onAfterRenderTargetsRenderObserver = null;
  101266. this._onAfterRenderObserver = null;
  101267. this._onBeforeDrawPhaseObserver = null;
  101268. this._onAfterDrawPhaseObserver = null;
  101269. this._onBeforeAnimationsObserver = null;
  101270. this._onBeforeParticlesRenderingObserver = null;
  101271. this._onAfterParticlesRenderingObserver = null;
  101272. this._onBeforeSpritesRenderingObserver = null;
  101273. this._onAfterSpritesRenderingObserver = null;
  101274. this._onBeforePhysicsObserver = null;
  101275. this._onAfterPhysicsObserver = null;
  101276. this._onAfterAnimationsObserver = null;
  101277. this._onBeforeCameraRenderObserver = null;
  101278. this._onAfterCameraRenderObserver = null;
  101279. // Before render
  101280. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101281. if (_this._captureActiveMeshesEvaluationTime) {
  101282. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101283. }
  101284. if (_this._captureRenderTargetsRenderTime) {
  101285. _this._renderTargetsRenderTime.fetchNewFrame();
  101286. }
  101287. if (_this._captureFrameTime) {
  101288. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101289. _this._frameTime.beginMonitoring();
  101290. }
  101291. if (_this._captureInterFrameTime) {
  101292. _this._interFrameTime.endMonitoring();
  101293. }
  101294. if (_this._captureParticlesRenderTime) {
  101295. _this._particlesRenderTime.fetchNewFrame();
  101296. }
  101297. if (_this._captureSpritesRenderTime) {
  101298. _this._spritesRenderTime.fetchNewFrame();
  101299. }
  101300. if (_this._captureAnimationsTime) {
  101301. _this._animationsTime.beginMonitoring();
  101302. }
  101303. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101304. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101305. });
  101306. // After render
  101307. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101308. if (_this._captureFrameTime) {
  101309. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101310. _this._frameTime.endMonitoring();
  101311. }
  101312. if (_this._captureRenderTime) {
  101313. _this._renderTime.endMonitoring(false);
  101314. }
  101315. if (_this._captureInterFrameTime) {
  101316. _this._interFrameTime.beginMonitoring();
  101317. }
  101318. });
  101319. }
  101320. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101321. // Properties
  101322. /**
  101323. * Gets the perf counter used for active meshes evaluation time
  101324. */
  101325. get: function () {
  101326. return this._activeMeshesEvaluationTime;
  101327. },
  101328. enumerable: true,
  101329. configurable: true
  101330. });
  101331. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101332. /**
  101333. * Gets the active meshes evaluation time capture status
  101334. */
  101335. get: function () {
  101336. return this._captureActiveMeshesEvaluationTime;
  101337. },
  101338. /**
  101339. * Enable or disable the active meshes evaluation time capture
  101340. */
  101341. set: function (value) {
  101342. var _this = this;
  101343. if (value === this._captureActiveMeshesEvaluationTime) {
  101344. return;
  101345. }
  101346. this._captureActiveMeshesEvaluationTime = value;
  101347. if (value) {
  101348. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101349. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101350. _this._activeMeshesEvaluationTime.beginMonitoring();
  101351. });
  101352. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101353. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101354. _this._activeMeshesEvaluationTime.endMonitoring();
  101355. });
  101356. }
  101357. else {
  101358. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101359. this._onBeforeActiveMeshesEvaluationObserver = null;
  101360. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101361. this._onAfterActiveMeshesEvaluationObserver = null;
  101362. }
  101363. },
  101364. enumerable: true,
  101365. configurable: true
  101366. });
  101367. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101368. /**
  101369. * Gets the perf counter used for render targets render time
  101370. */
  101371. get: function () {
  101372. return this._renderTargetsRenderTime;
  101373. },
  101374. enumerable: true,
  101375. configurable: true
  101376. });
  101377. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101378. /**
  101379. * Gets the render targets render time capture status
  101380. */
  101381. get: function () {
  101382. return this._captureRenderTargetsRenderTime;
  101383. },
  101384. /**
  101385. * Enable or disable the render targets render time capture
  101386. */
  101387. set: function (value) {
  101388. var _this = this;
  101389. if (value === this._captureRenderTargetsRenderTime) {
  101390. return;
  101391. }
  101392. this._captureRenderTargetsRenderTime = value;
  101393. if (value) {
  101394. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101395. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101396. _this._renderTargetsRenderTime.beginMonitoring();
  101397. });
  101398. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101399. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101400. _this._renderTargetsRenderTime.endMonitoring(false);
  101401. });
  101402. }
  101403. else {
  101404. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101405. this._onBeforeRenderTargetsRenderObserver = null;
  101406. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101407. this._onAfterRenderTargetsRenderObserver = null;
  101408. }
  101409. },
  101410. enumerable: true,
  101411. configurable: true
  101412. });
  101413. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101414. /**
  101415. * Gets the perf counter used for particles render time
  101416. */
  101417. get: function () {
  101418. return this._particlesRenderTime;
  101419. },
  101420. enumerable: true,
  101421. configurable: true
  101422. });
  101423. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101424. /**
  101425. * Gets the particles render time capture status
  101426. */
  101427. get: function () {
  101428. return this._captureParticlesRenderTime;
  101429. },
  101430. /**
  101431. * Enable or disable the particles render time capture
  101432. */
  101433. set: function (value) {
  101434. var _this = this;
  101435. if (value === this._captureParticlesRenderTime) {
  101436. return;
  101437. }
  101438. this._captureParticlesRenderTime = value;
  101439. if (value) {
  101440. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101441. BABYLON.Tools.StartPerformanceCounter("Particles");
  101442. _this._particlesRenderTime.beginMonitoring();
  101443. });
  101444. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101445. BABYLON.Tools.EndPerformanceCounter("Particles");
  101446. _this._particlesRenderTime.endMonitoring(false);
  101447. });
  101448. }
  101449. else {
  101450. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101451. this._onBeforeParticlesRenderingObserver = null;
  101452. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101453. this._onAfterParticlesRenderingObserver = null;
  101454. }
  101455. },
  101456. enumerable: true,
  101457. configurable: true
  101458. });
  101459. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101460. /**
  101461. * Gets the perf counter used for sprites render time
  101462. */
  101463. get: function () {
  101464. return this._spritesRenderTime;
  101465. },
  101466. enumerable: true,
  101467. configurable: true
  101468. });
  101469. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101470. /**
  101471. * Gets the sprites render time capture status
  101472. */
  101473. get: function () {
  101474. return this._captureSpritesRenderTime;
  101475. },
  101476. /**
  101477. * Enable or disable the sprites render time capture
  101478. */
  101479. set: function (value) {
  101480. var _this = this;
  101481. if (value === this._captureSpritesRenderTime) {
  101482. return;
  101483. }
  101484. this._captureSpritesRenderTime = value;
  101485. if (value) {
  101486. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101487. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101488. _this._spritesRenderTime.beginMonitoring();
  101489. });
  101490. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101491. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101492. _this._spritesRenderTime.endMonitoring(false);
  101493. });
  101494. }
  101495. else {
  101496. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101497. this._onBeforeSpritesRenderingObserver = null;
  101498. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101499. this._onAfterSpritesRenderingObserver = null;
  101500. }
  101501. },
  101502. enumerable: true,
  101503. configurable: true
  101504. });
  101505. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101506. /**
  101507. * Gets the perf counter used for physics time
  101508. */
  101509. get: function () {
  101510. return this._physicsTime;
  101511. },
  101512. enumerable: true,
  101513. configurable: true
  101514. });
  101515. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101516. /**
  101517. * Gets the physics time capture status
  101518. */
  101519. get: function () {
  101520. return this._capturePhysicsTime;
  101521. },
  101522. /**
  101523. * Enable or disable the physics time capture
  101524. */
  101525. set: function (value) {
  101526. var _this = this;
  101527. if (value === this._capturePhysicsTime) {
  101528. return;
  101529. }
  101530. this._capturePhysicsTime = value;
  101531. if (value) {
  101532. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101533. BABYLON.Tools.StartPerformanceCounter("Physics");
  101534. _this._physicsTime.beginMonitoring();
  101535. });
  101536. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101537. BABYLON.Tools.EndPerformanceCounter("Physics");
  101538. _this._physicsTime.endMonitoring();
  101539. });
  101540. }
  101541. else {
  101542. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101543. this._onBeforePhysicsObserver = null;
  101544. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101545. this._onAfterPhysicsObserver = null;
  101546. }
  101547. },
  101548. enumerable: true,
  101549. configurable: true
  101550. });
  101551. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101552. /**
  101553. * Gets the perf counter used for animations time
  101554. */
  101555. get: function () {
  101556. return this._animationsTime;
  101557. },
  101558. enumerable: true,
  101559. configurable: true
  101560. });
  101561. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101562. /**
  101563. * Gets the animations time capture status
  101564. */
  101565. get: function () {
  101566. return this._captureAnimationsTime;
  101567. },
  101568. /**
  101569. * Enable or disable the animations time capture
  101570. */
  101571. set: function (value) {
  101572. var _this = this;
  101573. if (value === this._captureAnimationsTime) {
  101574. return;
  101575. }
  101576. this._captureAnimationsTime = value;
  101577. if (value) {
  101578. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101579. _this._animationsTime.endMonitoring();
  101580. });
  101581. }
  101582. else {
  101583. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101584. this._onAfterAnimationsObserver = null;
  101585. }
  101586. },
  101587. enumerable: true,
  101588. configurable: true
  101589. });
  101590. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101591. /**
  101592. * Gets the perf counter used for frame time capture
  101593. */
  101594. get: function () {
  101595. return this._frameTime;
  101596. },
  101597. enumerable: true,
  101598. configurable: true
  101599. });
  101600. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101601. /**
  101602. * Gets the frame time capture status
  101603. */
  101604. get: function () {
  101605. return this._captureFrameTime;
  101606. },
  101607. /**
  101608. * Enable or disable the frame time capture
  101609. */
  101610. set: function (value) {
  101611. this._captureFrameTime = value;
  101612. },
  101613. enumerable: true,
  101614. configurable: true
  101615. });
  101616. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101617. /**
  101618. * Gets the perf counter used for inter-frames time capture
  101619. */
  101620. get: function () {
  101621. return this._interFrameTime;
  101622. },
  101623. enumerable: true,
  101624. configurable: true
  101625. });
  101626. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101627. /**
  101628. * Gets the inter-frames time capture status
  101629. */
  101630. get: function () {
  101631. return this._captureInterFrameTime;
  101632. },
  101633. /**
  101634. * Enable or disable the inter-frames time capture
  101635. */
  101636. set: function (value) {
  101637. this._captureInterFrameTime = value;
  101638. },
  101639. enumerable: true,
  101640. configurable: true
  101641. });
  101642. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101643. /**
  101644. * Gets the perf counter used for render time capture
  101645. */
  101646. get: function () {
  101647. return this._renderTime;
  101648. },
  101649. enumerable: true,
  101650. configurable: true
  101651. });
  101652. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101653. /**
  101654. * Gets the render time capture status
  101655. */
  101656. get: function () {
  101657. return this._captureRenderTime;
  101658. },
  101659. /**
  101660. * Enable or disable the render time capture
  101661. */
  101662. set: function (value) {
  101663. var _this = this;
  101664. if (value === this._captureRenderTime) {
  101665. return;
  101666. }
  101667. this._captureRenderTime = value;
  101668. if (value) {
  101669. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101670. _this._renderTime.beginMonitoring();
  101671. BABYLON.Tools.StartPerformanceCounter("Main render");
  101672. });
  101673. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101674. _this._renderTime.endMonitoring(false);
  101675. BABYLON.Tools.EndPerformanceCounter("Main render");
  101676. });
  101677. }
  101678. else {
  101679. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101680. this._onBeforeDrawPhaseObserver = null;
  101681. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101682. this._onAfterDrawPhaseObserver = null;
  101683. }
  101684. },
  101685. enumerable: true,
  101686. configurable: true
  101687. });
  101688. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101689. /**
  101690. * Gets the perf counter used for camera render time capture
  101691. */
  101692. get: function () {
  101693. return this._cameraRenderTime;
  101694. },
  101695. enumerable: true,
  101696. configurable: true
  101697. });
  101698. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101699. /**
  101700. * Gets the camera render time capture status
  101701. */
  101702. get: function () {
  101703. return this._captureCameraRenderTime;
  101704. },
  101705. /**
  101706. * Enable or disable the camera render time capture
  101707. */
  101708. set: function (value) {
  101709. var _this = this;
  101710. if (value === this._captureCameraRenderTime) {
  101711. return;
  101712. }
  101713. this._captureCameraRenderTime = value;
  101714. if (value) {
  101715. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101716. _this._cameraRenderTime.beginMonitoring();
  101717. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101718. });
  101719. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101720. _this._cameraRenderTime.endMonitoring(false);
  101721. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101722. });
  101723. }
  101724. else {
  101725. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101726. this._onBeforeCameraRenderObserver = null;
  101727. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101728. this._onAfterCameraRenderObserver = null;
  101729. }
  101730. },
  101731. enumerable: true,
  101732. configurable: true
  101733. });
  101734. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101735. /**
  101736. * Gets the perf counter used for draw calls
  101737. */
  101738. get: function () {
  101739. return this.scene.getEngine()._drawCalls;
  101740. },
  101741. enumerable: true,
  101742. configurable: true
  101743. });
  101744. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101745. /**
  101746. * Gets the perf counter used for texture collisions
  101747. */
  101748. get: function () {
  101749. return this.scene.getEngine()._textureCollisions;
  101750. },
  101751. enumerable: true,
  101752. configurable: true
  101753. });
  101754. SceneInstrumentation.prototype.dispose = function () {
  101755. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101756. this._onAfterRenderObserver = null;
  101757. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101758. this._onBeforeActiveMeshesEvaluationObserver = null;
  101759. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101760. this._onAfterActiveMeshesEvaluationObserver = null;
  101761. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101762. this._onBeforeRenderTargetsRenderObserver = null;
  101763. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101764. this._onAfterRenderTargetsRenderObserver = null;
  101765. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101766. this._onBeforeAnimationsObserver = null;
  101767. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101768. this._onBeforeParticlesRenderingObserver = null;
  101769. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101770. this._onAfterParticlesRenderingObserver = null;
  101771. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101772. this._onBeforeSpritesRenderingObserver = null;
  101773. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101774. this._onAfterSpritesRenderingObserver = null;
  101775. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101776. this._onBeforeDrawPhaseObserver = null;
  101777. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101778. this._onAfterDrawPhaseObserver = null;
  101779. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101780. this._onBeforePhysicsObserver = null;
  101781. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101782. this._onAfterPhysicsObserver = null;
  101783. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101784. this._onAfterAnimationsObserver = null;
  101785. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101786. this._onBeforeCameraRenderObserver = null;
  101787. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101788. this._onAfterCameraRenderObserver = null;
  101789. this.scene = null;
  101790. };
  101791. return SceneInstrumentation;
  101792. }());
  101793. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101794. })(BABYLON || (BABYLON = {}));
  101795. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101796. var BABYLON;
  101797. (function (BABYLON) {
  101798. /**
  101799. * @hidden
  101800. **/
  101801. var _TimeToken = /** @class */ (function () {
  101802. function _TimeToken() {
  101803. this._timeElapsedQueryEnded = false;
  101804. }
  101805. return _TimeToken;
  101806. }());
  101807. BABYLON._TimeToken = _TimeToken;
  101808. })(BABYLON || (BABYLON = {}));
  101809. //# sourceMappingURL=babylon.timeToken.js.map
  101810. var BABYLON;
  101811. (function (BABYLON) {
  101812. /**
  101813. * Background material defines definition.
  101814. * @hidden Mainly internal Use
  101815. */
  101816. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101817. __extends(BackgroundMaterialDefines, _super);
  101818. /**
  101819. * Constructor of the defines.
  101820. */
  101821. function BackgroundMaterialDefines() {
  101822. var _this = _super.call(this) || this;
  101823. /**
  101824. * True if the diffuse texture is in use.
  101825. */
  101826. _this.DIFFUSE = false;
  101827. /**
  101828. * The direct UV channel to use.
  101829. */
  101830. _this.DIFFUSEDIRECTUV = 0;
  101831. /**
  101832. * True if the diffuse texture is in gamma space.
  101833. */
  101834. _this.GAMMADIFFUSE = false;
  101835. /**
  101836. * True if the diffuse texture has opacity in the alpha channel.
  101837. */
  101838. _this.DIFFUSEHASALPHA = false;
  101839. /**
  101840. * True if you want the material to fade to transparent at grazing angle.
  101841. */
  101842. _this.OPACITYFRESNEL = false;
  101843. /**
  101844. * True if an extra blur needs to be added in the reflection.
  101845. */
  101846. _this.REFLECTIONBLUR = false;
  101847. /**
  101848. * True if you want the material to fade to reflection at grazing angle.
  101849. */
  101850. _this.REFLECTIONFRESNEL = false;
  101851. /**
  101852. * True if you want the material to falloff as far as you move away from the scene center.
  101853. */
  101854. _this.REFLECTIONFALLOFF = false;
  101855. /**
  101856. * False if the current Webgl implementation does not support the texture lod extension.
  101857. */
  101858. _this.TEXTURELODSUPPORT = false;
  101859. /**
  101860. * True to ensure the data are premultiplied.
  101861. */
  101862. _this.PREMULTIPLYALPHA = false;
  101863. /**
  101864. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101865. */
  101866. _this.USERGBCOLOR = false;
  101867. /**
  101868. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101869. * stays aligned with the desired configuration.
  101870. */
  101871. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101872. /**
  101873. * True to add noise in order to reduce the banding effect.
  101874. */
  101875. _this.NOISE = false;
  101876. /**
  101877. * is the reflection texture in BGR color scheme?
  101878. * Mainly used to solve a bug in ios10 video tag
  101879. */
  101880. _this.REFLECTIONBGR = false;
  101881. _this.IMAGEPROCESSING = false;
  101882. _this.VIGNETTE = false;
  101883. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101884. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101885. _this.TONEMAPPING = false;
  101886. _this.CONTRAST = false;
  101887. _this.COLORCURVES = false;
  101888. _this.COLORGRADING = false;
  101889. _this.COLORGRADING3D = false;
  101890. _this.SAMPLER3DGREENDEPTH = false;
  101891. _this.SAMPLER3DBGRMAP = false;
  101892. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101893. _this.EXPOSURE = false;
  101894. // Reflection.
  101895. _this.REFLECTION = false;
  101896. _this.REFLECTIONMAP_3D = false;
  101897. _this.REFLECTIONMAP_SPHERICAL = false;
  101898. _this.REFLECTIONMAP_PLANAR = false;
  101899. _this.REFLECTIONMAP_CUBIC = false;
  101900. _this.REFLECTIONMAP_PROJECTION = false;
  101901. _this.REFLECTIONMAP_SKYBOX = false;
  101902. _this.REFLECTIONMAP_EXPLICIT = false;
  101903. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101904. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101905. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101906. _this.INVERTCUBICMAP = false;
  101907. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101908. _this.LODINREFLECTIONALPHA = false;
  101909. _this.GAMMAREFLECTION = false;
  101910. _this.RGBDREFLECTION = false;
  101911. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101912. // Default BJS.
  101913. _this.MAINUV1 = false;
  101914. _this.MAINUV2 = false;
  101915. _this.UV1 = false;
  101916. _this.UV2 = false;
  101917. _this.CLIPPLANE = false;
  101918. _this.POINTSIZE = false;
  101919. _this.FOG = false;
  101920. _this.NORMAL = false;
  101921. _this.NUM_BONE_INFLUENCERS = 0;
  101922. _this.BonesPerMesh = 0;
  101923. _this.INSTANCES = false;
  101924. _this.SHADOWFLOAT = false;
  101925. _this.rebuild();
  101926. return _this;
  101927. }
  101928. return BackgroundMaterialDefines;
  101929. }(BABYLON.MaterialDefines));
  101930. /**
  101931. * Background material used to create an efficient environement around your scene.
  101932. */
  101933. var BackgroundMaterial = /** @class */ (function (_super) {
  101934. __extends(BackgroundMaterial, _super);
  101935. /**
  101936. * Instantiates a Background Material in the given scene
  101937. * @param name The friendly name of the material
  101938. * @param scene The scene to add the material to
  101939. */
  101940. function BackgroundMaterial(name, scene) {
  101941. var _this = _super.call(this, name, scene) || this;
  101942. /**
  101943. * Key light Color (multiply against the environement texture)
  101944. */
  101945. _this.primaryColor = BABYLON.Color3.White();
  101946. _this._primaryColorShadowLevel = 0;
  101947. _this._primaryColorHighlightLevel = 0;
  101948. /**
  101949. * Reflection Texture used in the material.
  101950. * Should be author in a specific way for the best result (refer to the documentation).
  101951. */
  101952. _this.reflectionTexture = null;
  101953. /**
  101954. * Reflection Texture level of blur.
  101955. *
  101956. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101957. * texture twice.
  101958. */
  101959. _this.reflectionBlur = 0;
  101960. /**
  101961. * Diffuse Texture used in the material.
  101962. * Should be author in a specific way for the best result (refer to the documentation).
  101963. */
  101964. _this.diffuseTexture = null;
  101965. _this._shadowLights = null;
  101966. /**
  101967. * Specify the list of lights casting shadow on the material.
  101968. * All scene shadow lights will be included if null.
  101969. */
  101970. _this.shadowLights = null;
  101971. /**
  101972. * Helps adjusting the shadow to a softer level if required.
  101973. * 0 means black shadows and 1 means no shadows.
  101974. */
  101975. _this.shadowLevel = 0;
  101976. /**
  101977. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101978. * It is usually zero but might be interesting to modify according to your setup.
  101979. */
  101980. _this.sceneCenter = BABYLON.Vector3.Zero();
  101981. /**
  101982. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101983. * This helps ensuring a nice transition when the camera goes under the ground.
  101984. */
  101985. _this.opacityFresnel = true;
  101986. /**
  101987. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101988. * This helps adding a mirror texture on the ground.
  101989. */
  101990. _this.reflectionFresnel = false;
  101991. /**
  101992. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101993. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101994. */
  101995. _this.reflectionFalloffDistance = 0.0;
  101996. /**
  101997. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101998. */
  101999. _this.reflectionAmount = 1.0;
  102000. /**
  102001. * This specifies the weight of the reflection at grazing angle.
  102002. */
  102003. _this.reflectionReflectance0 = 0.05;
  102004. /**
  102005. * This specifies the weight of the reflection at a perpendicular point of view.
  102006. */
  102007. _this.reflectionReflectance90 = 0.5;
  102008. /**
  102009. * Helps to directly use the maps channels instead of their level.
  102010. */
  102011. _this.useRGBColor = true;
  102012. /**
  102013. * This helps reducing the banding effect that could occur on the background.
  102014. */
  102015. _this.enableNoise = false;
  102016. _this._fovMultiplier = 1.0;
  102017. /**
  102018. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102019. */
  102020. _this.useEquirectangularFOV = false;
  102021. _this._maxSimultaneousLights = 4;
  102022. /**
  102023. * Number of Simultaneous lights allowed on the material.
  102024. */
  102025. _this.maxSimultaneousLights = 4;
  102026. /**
  102027. * Keep track of the image processing observer to allow dispose and replace.
  102028. */
  102029. _this._imageProcessingObserver = null;
  102030. /**
  102031. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102032. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102033. */
  102034. _this.switchToBGR = false;
  102035. // Temp values kept as cache in the material.
  102036. _this._renderTargets = new BABYLON.SmartArray(16);
  102037. _this._reflectionControls = BABYLON.Vector4.Zero();
  102038. _this._white = BABYLON.Color3.White();
  102039. _this._primaryShadowColor = BABYLON.Color3.Black();
  102040. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102041. // Setup the default processing configuration to the scene.
  102042. _this._attachImageProcessingConfiguration(null);
  102043. _this.getRenderTargetTextures = function () {
  102044. _this._renderTargets.reset();
  102045. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102046. _this._renderTargets.push(_this._diffuseTexture);
  102047. }
  102048. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102049. _this._renderTargets.push(_this._reflectionTexture);
  102050. }
  102051. return _this._renderTargets;
  102052. };
  102053. return _this;
  102054. }
  102055. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102056. /**
  102057. * Experimental Internal Use Only.
  102058. *
  102059. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102060. * This acts as a helper to set the primary color to a more "human friendly" value.
  102061. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102062. * output color as close as possible from the chosen value.
  102063. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102064. * part of lighting setup.)
  102065. */
  102066. get: function () {
  102067. return this.__perceptualColor;
  102068. },
  102069. set: function (value) {
  102070. this.__perceptualColor = value;
  102071. this._computePrimaryColorFromPerceptualColor();
  102072. this._markAllSubMeshesAsLightsDirty();
  102073. },
  102074. enumerable: true,
  102075. configurable: true
  102076. });
  102077. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102078. /**
  102079. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102080. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102081. */
  102082. get: function () {
  102083. return this._primaryColorShadowLevel;
  102084. },
  102085. set: function (value) {
  102086. this._primaryColorShadowLevel = value;
  102087. this._computePrimaryColors();
  102088. this._markAllSubMeshesAsLightsDirty();
  102089. },
  102090. enumerable: true,
  102091. configurable: true
  102092. });
  102093. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102094. /**
  102095. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102096. * The primary color is used at the level chosen to define what the white area would look.
  102097. */
  102098. get: function () {
  102099. return this._primaryColorHighlightLevel;
  102100. },
  102101. set: function (value) {
  102102. this._primaryColorHighlightLevel = value;
  102103. this._computePrimaryColors();
  102104. this._markAllSubMeshesAsLightsDirty();
  102105. },
  102106. enumerable: true,
  102107. configurable: true
  102108. });
  102109. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102110. /**
  102111. * Sets the reflection reflectance fresnel values according to the default standard
  102112. * empirically know to work well :-)
  102113. */
  102114. set: function (value) {
  102115. var reflectionWeight = value;
  102116. if (reflectionWeight < 0.5) {
  102117. reflectionWeight = reflectionWeight * 2.0;
  102118. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102119. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102120. }
  102121. else {
  102122. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102123. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102124. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102125. }
  102126. },
  102127. enumerable: true,
  102128. configurable: true
  102129. });
  102130. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102131. /**
  102132. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102133. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102134. * Recommended to be keep at 1.0 except for special cases.
  102135. */
  102136. get: function () {
  102137. return this._fovMultiplier;
  102138. },
  102139. set: function (value) {
  102140. if (isNaN(value)) {
  102141. value = 1.0;
  102142. }
  102143. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102144. },
  102145. enumerable: true,
  102146. configurable: true
  102147. });
  102148. /**
  102149. * Attaches a new image processing configuration to the PBR Material.
  102150. * @param configuration (if null the scene configuration will be use)
  102151. */
  102152. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102153. var _this = this;
  102154. if (configuration === this._imageProcessingConfiguration) {
  102155. return;
  102156. }
  102157. // Detaches observer.
  102158. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102159. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102160. }
  102161. // Pick the scene configuration if needed.
  102162. if (!configuration) {
  102163. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102164. }
  102165. else {
  102166. this._imageProcessingConfiguration = configuration;
  102167. }
  102168. // Attaches observer.
  102169. if (this._imageProcessingConfiguration) {
  102170. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102171. _this._computePrimaryColorFromPerceptualColor();
  102172. _this._markAllSubMeshesAsImageProcessingDirty();
  102173. });
  102174. }
  102175. };
  102176. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102177. /**
  102178. * Gets the image processing configuration used either in this material.
  102179. */
  102180. get: function () {
  102181. return this._imageProcessingConfiguration;
  102182. },
  102183. /**
  102184. * Sets the Default image processing configuration used either in the this material.
  102185. *
  102186. * If sets to null, the scene one is in use.
  102187. */
  102188. set: function (value) {
  102189. this._attachImageProcessingConfiguration(value);
  102190. // Ensure the effect will be rebuilt.
  102191. this._markAllSubMeshesAsTexturesDirty();
  102192. },
  102193. enumerable: true,
  102194. configurable: true
  102195. });
  102196. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102197. /**
  102198. * Gets wether the color curves effect is enabled.
  102199. */
  102200. get: function () {
  102201. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102202. },
  102203. /**
  102204. * Sets wether the color curves effect is enabled.
  102205. */
  102206. set: function (value) {
  102207. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102208. },
  102209. enumerable: true,
  102210. configurable: true
  102211. });
  102212. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102213. /**
  102214. * Gets wether the color grading effect is enabled.
  102215. */
  102216. get: function () {
  102217. return this.imageProcessingConfiguration.colorGradingEnabled;
  102218. },
  102219. /**
  102220. * Gets wether the color grading effect is enabled.
  102221. */
  102222. set: function (value) {
  102223. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102224. },
  102225. enumerable: true,
  102226. configurable: true
  102227. });
  102228. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102229. /**
  102230. * Gets wether tonemapping is enabled or not.
  102231. */
  102232. get: function () {
  102233. return this._imageProcessingConfiguration.toneMappingEnabled;
  102234. },
  102235. /**
  102236. * Sets wether tonemapping is enabled or not
  102237. */
  102238. set: function (value) {
  102239. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102240. },
  102241. enumerable: true,
  102242. configurable: true
  102243. });
  102244. ;
  102245. ;
  102246. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102247. /**
  102248. * The camera exposure used on this material.
  102249. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102250. * This corresponds to a photographic exposure.
  102251. */
  102252. get: function () {
  102253. return this._imageProcessingConfiguration.exposure;
  102254. },
  102255. /**
  102256. * The camera exposure used on this material.
  102257. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102258. * This corresponds to a photographic exposure.
  102259. */
  102260. set: function (value) {
  102261. this._imageProcessingConfiguration.exposure = value;
  102262. },
  102263. enumerable: true,
  102264. configurable: true
  102265. });
  102266. ;
  102267. ;
  102268. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102269. /**
  102270. * Gets The camera contrast used on this material.
  102271. */
  102272. get: function () {
  102273. return this._imageProcessingConfiguration.contrast;
  102274. },
  102275. /**
  102276. * Sets The camera contrast used on this material.
  102277. */
  102278. set: function (value) {
  102279. this._imageProcessingConfiguration.contrast = value;
  102280. },
  102281. enumerable: true,
  102282. configurable: true
  102283. });
  102284. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102285. /**
  102286. * Gets the Color Grading 2D Lookup Texture.
  102287. */
  102288. get: function () {
  102289. return this._imageProcessingConfiguration.colorGradingTexture;
  102290. },
  102291. /**
  102292. * Sets the Color Grading 2D Lookup Texture.
  102293. */
  102294. set: function (value) {
  102295. this.imageProcessingConfiguration.colorGradingTexture = value;
  102296. },
  102297. enumerable: true,
  102298. configurable: true
  102299. });
  102300. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102301. /**
  102302. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102303. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102304. * 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;
  102305. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102306. */
  102307. get: function () {
  102308. return this.imageProcessingConfiguration.colorCurves;
  102309. },
  102310. /**
  102311. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102312. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102313. * 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;
  102314. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102315. */
  102316. set: function (value) {
  102317. this.imageProcessingConfiguration.colorCurves = value;
  102318. },
  102319. enumerable: true,
  102320. configurable: true
  102321. });
  102322. /**
  102323. * The entire material has been created in order to prevent overdraw.
  102324. * @returns false
  102325. */
  102326. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102327. return true;
  102328. };
  102329. /**
  102330. * The entire material has been created in order to prevent overdraw.
  102331. * @returns true if blending is enable
  102332. */
  102333. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102334. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102335. };
  102336. /**
  102337. * Checks wether the material is ready to be rendered for a given mesh.
  102338. * @param mesh The mesh to render
  102339. * @param subMesh The submesh to check against
  102340. * @param useInstances Specify wether or not the material is used with instances
  102341. * @returns true if all the dependencies are ready (Textures, Effects...)
  102342. */
  102343. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102344. var _this = this;
  102345. if (useInstances === void 0) { useInstances = false; }
  102346. if (subMesh.effect && this.isFrozen) {
  102347. if (this._wasPreviouslyReady) {
  102348. return true;
  102349. }
  102350. }
  102351. if (!subMesh._materialDefines) {
  102352. subMesh._materialDefines = new BackgroundMaterialDefines();
  102353. }
  102354. var scene = this.getScene();
  102355. var defines = subMesh._materialDefines;
  102356. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102357. if (defines._renderId === scene.getRenderId()) {
  102358. return true;
  102359. }
  102360. }
  102361. var engine = scene.getEngine();
  102362. // Lights
  102363. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102364. defines._needNormals = true;
  102365. // Textures
  102366. if (defines._areTexturesDirty) {
  102367. defines._needUVs = false;
  102368. if (scene.texturesEnabled) {
  102369. if (scene.getEngine().getCaps().textureLOD) {
  102370. defines.TEXTURELODSUPPORT = true;
  102371. }
  102372. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102373. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102374. return false;
  102375. }
  102376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102377. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102378. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102379. defines.OPACITYFRESNEL = this._opacityFresnel;
  102380. }
  102381. else {
  102382. defines.DIFFUSE = false;
  102383. defines.DIFFUSEHASALPHA = false;
  102384. defines.GAMMADIFFUSE = false;
  102385. defines.OPACITYFRESNEL = false;
  102386. }
  102387. var reflectionTexture = this._reflectionTexture;
  102388. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102389. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102390. return false;
  102391. }
  102392. defines.REFLECTION = true;
  102393. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102394. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102395. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102396. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102397. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102398. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102399. defines.REFLECTIONBGR = this.switchToBGR;
  102400. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102401. defines.INVERTCUBICMAP = true;
  102402. }
  102403. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102404. switch (reflectionTexture.coordinatesMode) {
  102405. case BABYLON.Texture.EXPLICIT_MODE:
  102406. defines.REFLECTIONMAP_EXPLICIT = true;
  102407. break;
  102408. case BABYLON.Texture.PLANAR_MODE:
  102409. defines.REFLECTIONMAP_PLANAR = true;
  102410. break;
  102411. case BABYLON.Texture.PROJECTION_MODE:
  102412. defines.REFLECTIONMAP_PROJECTION = true;
  102413. break;
  102414. case BABYLON.Texture.SKYBOX_MODE:
  102415. defines.REFLECTIONMAP_SKYBOX = true;
  102416. break;
  102417. case BABYLON.Texture.SPHERICAL_MODE:
  102418. defines.REFLECTIONMAP_SPHERICAL = true;
  102419. break;
  102420. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102421. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102422. break;
  102423. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102424. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102425. break;
  102426. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102427. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102428. break;
  102429. case BABYLON.Texture.CUBIC_MODE:
  102430. case BABYLON.Texture.INVCUBIC_MODE:
  102431. default:
  102432. defines.REFLECTIONMAP_CUBIC = true;
  102433. break;
  102434. }
  102435. if (this.reflectionFresnel) {
  102436. defines.REFLECTIONFRESNEL = true;
  102437. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102438. this._reflectionControls.x = this.reflectionAmount;
  102439. this._reflectionControls.y = this.reflectionReflectance0;
  102440. this._reflectionControls.z = this.reflectionReflectance90;
  102441. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102442. }
  102443. else {
  102444. defines.REFLECTIONFRESNEL = false;
  102445. defines.REFLECTIONFALLOFF = false;
  102446. }
  102447. }
  102448. else {
  102449. defines.REFLECTION = false;
  102450. defines.REFLECTIONFRESNEL = false;
  102451. defines.REFLECTIONFALLOFF = false;
  102452. defines.REFLECTIONBLUR = false;
  102453. defines.REFLECTIONMAP_3D = false;
  102454. defines.REFLECTIONMAP_SPHERICAL = false;
  102455. defines.REFLECTIONMAP_PLANAR = false;
  102456. defines.REFLECTIONMAP_CUBIC = false;
  102457. defines.REFLECTIONMAP_PROJECTION = false;
  102458. defines.REFLECTIONMAP_SKYBOX = false;
  102459. defines.REFLECTIONMAP_EXPLICIT = false;
  102460. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102461. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102462. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102463. defines.INVERTCUBICMAP = false;
  102464. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102465. defines.LODINREFLECTIONALPHA = false;
  102466. defines.GAMMAREFLECTION = false;
  102467. defines.RGBDREFLECTION = false;
  102468. }
  102469. }
  102470. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102471. defines.USERGBCOLOR = this._useRGBColor;
  102472. defines.NOISE = this._enableNoise;
  102473. }
  102474. if (defines._areLightsDirty) {
  102475. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102476. }
  102477. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102478. if (!this._imageProcessingConfiguration.isReady()) {
  102479. return false;
  102480. }
  102481. this._imageProcessingConfiguration.prepareDefines(defines);
  102482. }
  102483. // Misc.
  102484. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102485. // Values that need to be evaluated on every frame
  102486. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102487. // Attribs
  102488. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102489. if (mesh) {
  102490. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102491. mesh.createNormals(true);
  102492. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102493. }
  102494. }
  102495. }
  102496. // Get correct effect
  102497. if (defines.isDirty) {
  102498. defines.markAsProcessed();
  102499. scene.resetCachedMaterial();
  102500. // Fallbacks
  102501. var fallbacks = new BABYLON.EffectFallbacks();
  102502. if (defines.FOG) {
  102503. fallbacks.addFallback(0, "FOG");
  102504. }
  102505. if (defines.POINTSIZE) {
  102506. fallbacks.addFallback(1, "POINTSIZE");
  102507. }
  102508. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102509. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102510. fallbacks.addCPUSkinningFallback(0, mesh);
  102511. }
  102512. //Attributes
  102513. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102514. if (defines.NORMAL) {
  102515. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102516. }
  102517. if (defines.UV1) {
  102518. attribs.push(BABYLON.VertexBuffer.UVKind);
  102519. }
  102520. if (defines.UV2) {
  102521. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102522. }
  102523. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102524. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102525. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102526. "vFogInfos", "vFogColor", "pointSize",
  102527. "vClipPlane", "mBones",
  102528. "vPrimaryColor", "vPrimaryColorShadow",
  102529. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102530. "shadowLevel", "alpha",
  102531. "vBackgroundCenter", "vReflectionControl",
  102532. "vDiffuseInfos", "diffuseMatrix",
  102533. ];
  102534. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102535. var uniformBuffers = ["Material", "Scene"];
  102536. if (BABYLON.ImageProcessingConfiguration) {
  102537. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102538. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102539. }
  102540. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102541. uniformsNames: uniforms,
  102542. uniformBuffersNames: uniformBuffers,
  102543. samplers: samplers,
  102544. defines: defines,
  102545. maxSimultaneousLights: this._maxSimultaneousLights
  102546. });
  102547. var onCompiled = function (effect) {
  102548. if (_this.onCompiled) {
  102549. _this.onCompiled(effect);
  102550. }
  102551. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102552. };
  102553. var join = defines.toString();
  102554. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102555. attributes: attribs,
  102556. uniformsNames: uniforms,
  102557. uniformBuffersNames: uniformBuffers,
  102558. samplers: samplers,
  102559. defines: join,
  102560. fallbacks: fallbacks,
  102561. onCompiled: onCompiled,
  102562. onError: this.onError,
  102563. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102564. }, engine), defines);
  102565. this.buildUniformLayout();
  102566. }
  102567. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102568. return false;
  102569. }
  102570. defines._renderId = scene.getRenderId();
  102571. this._wasPreviouslyReady = true;
  102572. return true;
  102573. };
  102574. /**
  102575. * Compute the primary color according to the chosen perceptual color.
  102576. */
  102577. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102578. if (!this.__perceptualColor) {
  102579. return;
  102580. }
  102581. this._primaryColor.copyFrom(this.__perceptualColor);
  102582. // Revert gamma space.
  102583. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102584. // Revert image processing configuration.
  102585. if (this._imageProcessingConfiguration) {
  102586. // Revert Exposure.
  102587. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102588. }
  102589. this._computePrimaryColors();
  102590. };
  102591. /**
  102592. * Compute the highlights and shadow colors according to their chosen levels.
  102593. */
  102594. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102595. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102596. return;
  102597. }
  102598. // Find the highlight color based on the configuration.
  102599. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102600. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102601. // Find the shadow color based on the configuration.
  102602. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102603. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102604. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102605. };
  102606. /**
  102607. * Build the uniform buffer used in the material.
  102608. */
  102609. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102610. // Order is important !
  102611. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102612. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102613. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102614. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102615. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102616. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102617. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102618. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102619. this._uniformBuffer.addUniform("pointSize", 1);
  102620. this._uniformBuffer.addUniform("shadowLevel", 1);
  102621. this._uniformBuffer.addUniform("alpha", 1);
  102622. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102623. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102624. this._uniformBuffer.create();
  102625. };
  102626. /**
  102627. * Unbind the material.
  102628. */
  102629. BackgroundMaterial.prototype.unbind = function () {
  102630. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102631. this._uniformBuffer.setTexture("diffuseSampler", null);
  102632. }
  102633. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102634. this._uniformBuffer.setTexture("reflectionSampler", null);
  102635. }
  102636. _super.prototype.unbind.call(this);
  102637. };
  102638. /**
  102639. * Bind only the world matrix to the material.
  102640. * @param world The world matrix to bind.
  102641. */
  102642. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102643. this._activeEffect.setMatrix("world", world);
  102644. };
  102645. /**
  102646. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102647. * @param world The world matrix to bind.
  102648. * @param subMesh The submesh to bind for.
  102649. */
  102650. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102651. var scene = this.getScene();
  102652. var defines = subMesh._materialDefines;
  102653. if (!defines) {
  102654. return;
  102655. }
  102656. var effect = subMesh.effect;
  102657. if (!effect) {
  102658. return;
  102659. }
  102660. this._activeEffect = effect;
  102661. // Matrices
  102662. this.bindOnlyWorldMatrix(world);
  102663. // Bones
  102664. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102665. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102666. if (mustRebind) {
  102667. this._uniformBuffer.bindToEffect(effect, "Material");
  102668. this.bindViewProjection(effect);
  102669. var reflectionTexture = this._reflectionTexture;
  102670. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102671. // Texture uniforms
  102672. if (scene.texturesEnabled) {
  102673. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102674. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102675. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102676. }
  102677. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102678. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102679. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102680. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102681. }
  102682. }
  102683. if (this.shadowLevel > 0) {
  102684. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102685. }
  102686. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102687. // Point size
  102688. if (this.pointsCloud) {
  102689. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102690. }
  102691. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102692. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102693. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102694. }
  102695. else {
  102696. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102697. }
  102698. }
  102699. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102700. // Textures
  102701. if (scene.texturesEnabled) {
  102702. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102703. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102704. }
  102705. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102706. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102707. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102708. }
  102709. else if (!defines.REFLECTIONBLUR) {
  102710. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102711. }
  102712. else {
  102713. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102714. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102715. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102716. }
  102717. if (defines.REFLECTIONFRESNEL) {
  102718. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102719. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102720. }
  102721. }
  102722. }
  102723. // Clip plane
  102724. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102725. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102726. }
  102727. if (mustRebind || !this.isFrozen) {
  102728. if (scene.lightsEnabled) {
  102729. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102730. }
  102731. // View
  102732. this.bindView(effect);
  102733. // Fog
  102734. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102735. // image processing
  102736. if (this._imageProcessingConfiguration) {
  102737. this._imageProcessingConfiguration.bind(this._activeEffect);
  102738. }
  102739. }
  102740. this._uniformBuffer.update();
  102741. this._afterBind(mesh, this._activeEffect);
  102742. };
  102743. /**
  102744. * Dispose the material.
  102745. * @param forceDisposeEffect Force disposal of the associated effect.
  102746. * @param forceDisposeTextures Force disposal of the associated textures.
  102747. */
  102748. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102749. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102750. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102751. if (forceDisposeTextures) {
  102752. if (this.diffuseTexture) {
  102753. this.diffuseTexture.dispose();
  102754. }
  102755. if (this.reflectionTexture) {
  102756. this.reflectionTexture.dispose();
  102757. }
  102758. }
  102759. this._renderTargets.dispose();
  102760. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102761. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102762. }
  102763. _super.prototype.dispose.call(this, forceDisposeEffect);
  102764. };
  102765. /**
  102766. * Clones the material.
  102767. * @param name The cloned name.
  102768. * @returns The cloned material.
  102769. */
  102770. BackgroundMaterial.prototype.clone = function (name) {
  102771. var _this = this;
  102772. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102773. };
  102774. /**
  102775. * Serializes the current material to its JSON representation.
  102776. * @returns The JSON representation.
  102777. */
  102778. BackgroundMaterial.prototype.serialize = function () {
  102779. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102780. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102781. return serializationObject;
  102782. };
  102783. /**
  102784. * Gets the class name of the material
  102785. * @returns "BackgroundMaterial"
  102786. */
  102787. BackgroundMaterial.prototype.getClassName = function () {
  102788. return "BackgroundMaterial";
  102789. };
  102790. /**
  102791. * Parse a JSON input to create back a background material.
  102792. * @param source The JSON data to parse
  102793. * @param scene The scene to create the parsed material in
  102794. * @param rootUrl The root url of the assets the material depends upon
  102795. * @returns the instantiated BackgroundMaterial.
  102796. */
  102797. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102798. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102799. };
  102800. /**
  102801. * Standard reflectance value at parallel view angle.
  102802. */
  102803. BackgroundMaterial.StandardReflectance0 = 0.05;
  102804. /**
  102805. * Standard reflectance value at grazing angle.
  102806. */
  102807. BackgroundMaterial.StandardReflectance90 = 0.5;
  102808. __decorate([
  102809. BABYLON.serializeAsColor3()
  102810. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102811. __decorate([
  102812. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102813. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102814. __decorate([
  102815. BABYLON.serializeAsColor3()
  102816. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102817. __decorate([
  102818. BABYLON.serialize()
  102819. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102820. __decorate([
  102821. BABYLON.serialize()
  102822. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102823. __decorate([
  102824. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102825. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102826. __decorate([
  102827. BABYLON.serializeAsTexture()
  102828. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102829. __decorate([
  102830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102831. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102832. __decorate([
  102833. BABYLON.serialize()
  102834. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102835. __decorate([
  102836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102837. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102838. __decorate([
  102839. BABYLON.serializeAsTexture()
  102840. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102841. __decorate([
  102842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102843. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102844. __decorate([
  102845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102846. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102847. __decorate([
  102848. BABYLON.serialize()
  102849. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102850. __decorate([
  102851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102852. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102853. __decorate([
  102854. BABYLON.serializeAsVector3()
  102855. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102856. __decorate([
  102857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102858. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102859. __decorate([
  102860. BABYLON.serialize()
  102861. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102862. __decorate([
  102863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102864. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102865. __decorate([
  102866. BABYLON.serialize()
  102867. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102868. __decorate([
  102869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102870. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102871. __decorate([
  102872. BABYLON.serialize()
  102873. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102874. __decorate([
  102875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102876. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102877. __decorate([
  102878. BABYLON.serialize()
  102879. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102880. __decorate([
  102881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102882. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102883. __decorate([
  102884. BABYLON.serialize()
  102885. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102886. __decorate([
  102887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102888. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102889. __decorate([
  102890. BABYLON.serialize()
  102891. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102892. __decorate([
  102893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102894. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102895. __decorate([
  102896. BABYLON.serialize()
  102897. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102898. __decorate([
  102899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102900. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102901. __decorate([
  102902. BABYLON.serialize()
  102903. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102904. __decorate([
  102905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102906. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102907. __decorate([
  102908. BABYLON.serialize()
  102909. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102910. __decorate([
  102911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102912. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102913. __decorate([
  102914. BABYLON.serializeAsImageProcessingConfiguration()
  102915. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102916. return BackgroundMaterial;
  102917. }(BABYLON.PushMaterial));
  102918. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102919. })(BABYLON || (BABYLON = {}));
  102920. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102921. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102922. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102923. s = arguments[i];
  102924. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102925. t[p] = s[p];
  102926. }
  102927. return t;
  102928. };
  102929. var BABYLON;
  102930. (function (BABYLON) {
  102931. /**
  102932. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102933. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102934. * It also helps with the default setup of your imageProcessing configuration.
  102935. */
  102936. var EnvironmentHelper = /** @class */ (function () {
  102937. /**
  102938. * constructor
  102939. * @param options
  102940. * @param scene The scene to add the material to
  102941. */
  102942. function EnvironmentHelper(options, scene) {
  102943. var _this = this;
  102944. this._errorHandler = function (message, exception) {
  102945. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102946. };
  102947. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102948. this._scene = scene;
  102949. this.onErrorObservable = new BABYLON.Observable();
  102950. this._setupBackground();
  102951. this._setupImageProcessing();
  102952. }
  102953. /**
  102954. * Creates the default options for the helper.
  102955. */
  102956. EnvironmentHelper._getDefaultOptions = function () {
  102957. return {
  102958. createGround: true,
  102959. groundSize: 15,
  102960. groundTexture: this._groundTextureCDNUrl,
  102961. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102962. groundOpacity: 0.9,
  102963. enableGroundShadow: true,
  102964. groundShadowLevel: 0.5,
  102965. enableGroundMirror: false,
  102966. groundMirrorSizeRatio: 0.3,
  102967. groundMirrorBlurKernel: 64,
  102968. groundMirrorAmount: 1,
  102969. groundMirrorFresnelWeight: 1,
  102970. groundMirrorFallOffDistance: 0,
  102971. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102972. groundYBias: 0.00001,
  102973. createSkybox: true,
  102974. skyboxSize: 20,
  102975. skyboxTexture: this._skyboxTextureCDNUrl,
  102976. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102977. backgroundYRotation: 0,
  102978. sizeAuto: true,
  102979. rootPosition: BABYLON.Vector3.Zero(),
  102980. setupImageProcessing: true,
  102981. environmentTexture: this._environmentTextureCDNUrl,
  102982. cameraExposure: 0.8,
  102983. cameraContrast: 1.2,
  102984. toneMappingEnabled: true,
  102985. };
  102986. };
  102987. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102988. /**
  102989. * Gets the root mesh created by the helper.
  102990. */
  102991. get: function () {
  102992. return this._rootMesh;
  102993. },
  102994. enumerable: true,
  102995. configurable: true
  102996. });
  102997. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102998. /**
  102999. * Gets the skybox created by the helper.
  103000. */
  103001. get: function () {
  103002. return this._skybox;
  103003. },
  103004. enumerable: true,
  103005. configurable: true
  103006. });
  103007. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103008. /**
  103009. * Gets the skybox texture created by the helper.
  103010. */
  103011. get: function () {
  103012. return this._skyboxTexture;
  103013. },
  103014. enumerable: true,
  103015. configurable: true
  103016. });
  103017. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103018. /**
  103019. * Gets the skybox material created by the helper.
  103020. */
  103021. get: function () {
  103022. return this._skyboxMaterial;
  103023. },
  103024. enumerable: true,
  103025. configurable: true
  103026. });
  103027. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103028. /**
  103029. * Gets the ground mesh created by the helper.
  103030. */
  103031. get: function () {
  103032. return this._ground;
  103033. },
  103034. enumerable: true,
  103035. configurable: true
  103036. });
  103037. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103038. /**
  103039. * Gets the ground texture created by the helper.
  103040. */
  103041. get: function () {
  103042. return this._groundTexture;
  103043. },
  103044. enumerable: true,
  103045. configurable: true
  103046. });
  103047. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103048. /**
  103049. * Gets the ground mirror created by the helper.
  103050. */
  103051. get: function () {
  103052. return this._groundMirror;
  103053. },
  103054. enumerable: true,
  103055. configurable: true
  103056. });
  103057. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103058. /**
  103059. * Gets the ground mirror render list to helps pushing the meshes
  103060. * you wish in the ground reflection.
  103061. */
  103062. get: function () {
  103063. if (this._groundMirror) {
  103064. return this._groundMirror.renderList;
  103065. }
  103066. return null;
  103067. },
  103068. enumerable: true,
  103069. configurable: true
  103070. });
  103071. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103072. /**
  103073. * Gets the ground material created by the helper.
  103074. */
  103075. get: function () {
  103076. return this._groundMaterial;
  103077. },
  103078. enumerable: true,
  103079. configurable: true
  103080. });
  103081. /**
  103082. * Updates the background according to the new options
  103083. * @param options
  103084. */
  103085. EnvironmentHelper.prototype.updateOptions = function (options) {
  103086. var newOptions = __assign({}, this._options, options);
  103087. if (this._ground && !newOptions.createGround) {
  103088. this._ground.dispose();
  103089. this._ground = null;
  103090. }
  103091. if (this._groundMaterial && !newOptions.createGround) {
  103092. this._groundMaterial.dispose();
  103093. this._groundMaterial = null;
  103094. }
  103095. if (this._groundTexture) {
  103096. if (this._options.groundTexture != newOptions.groundTexture) {
  103097. this._groundTexture.dispose();
  103098. this._groundTexture = null;
  103099. }
  103100. }
  103101. if (this._skybox && !newOptions.createSkybox) {
  103102. this._skybox.dispose();
  103103. this._skybox = null;
  103104. }
  103105. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103106. this._skyboxMaterial.dispose();
  103107. this._skyboxMaterial = null;
  103108. }
  103109. if (this._skyboxTexture) {
  103110. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103111. this._skyboxTexture.dispose();
  103112. this._skyboxTexture = null;
  103113. }
  103114. }
  103115. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103116. this._groundMirror.dispose();
  103117. this._groundMirror = null;
  103118. }
  103119. if (this._scene.environmentTexture) {
  103120. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103121. this._scene.environmentTexture.dispose();
  103122. }
  103123. }
  103124. this._options = newOptions;
  103125. this._setupBackground();
  103126. this._setupImageProcessing();
  103127. };
  103128. /**
  103129. * Sets the primary color of all the available elements.
  103130. * @param color the main color to affect to the ground and the background
  103131. */
  103132. EnvironmentHelper.prototype.setMainColor = function (color) {
  103133. if (this.groundMaterial) {
  103134. this.groundMaterial.primaryColor = color;
  103135. }
  103136. if (this.skyboxMaterial) {
  103137. this.skyboxMaterial.primaryColor = color;
  103138. }
  103139. if (this.groundMirror) {
  103140. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103141. }
  103142. };
  103143. /**
  103144. * Setup the image processing according to the specified options.
  103145. */
  103146. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103147. if (this._options.setupImageProcessing) {
  103148. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103149. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103150. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103151. this._setupEnvironmentTexture();
  103152. }
  103153. };
  103154. /**
  103155. * Setup the environment texture according to the specified options.
  103156. */
  103157. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103158. if (this._scene.environmentTexture) {
  103159. return;
  103160. }
  103161. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103162. this._scene.environmentTexture = this._options.environmentTexture;
  103163. return;
  103164. }
  103165. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103166. this._scene.environmentTexture = environmentTexture;
  103167. };
  103168. /**
  103169. * Setup the background according to the specified options.
  103170. */
  103171. EnvironmentHelper.prototype._setupBackground = function () {
  103172. if (!this._rootMesh) {
  103173. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103174. }
  103175. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103176. var sceneSize = this._getSceneSize();
  103177. if (this._options.createGround) {
  103178. this._setupGround(sceneSize);
  103179. this._setupGroundMaterial();
  103180. this._setupGroundDiffuseTexture();
  103181. if (this._options.enableGroundMirror) {
  103182. this._setupGroundMirrorTexture(sceneSize);
  103183. }
  103184. this._setupMirrorInGroundMaterial();
  103185. }
  103186. if (this._options.createSkybox) {
  103187. this._setupSkybox(sceneSize);
  103188. this._setupSkyboxMaterial();
  103189. this._setupSkyboxReflectionTexture();
  103190. }
  103191. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103192. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103193. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103194. };
  103195. /**
  103196. * Get the scene sizes according to the setup.
  103197. */
  103198. EnvironmentHelper.prototype._getSceneSize = function () {
  103199. var _this = this;
  103200. var groundSize = this._options.groundSize;
  103201. var skyboxSize = this._options.skyboxSize;
  103202. var rootPosition = this._options.rootPosition;
  103203. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103204. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103205. }
  103206. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103207. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103208. });
  103209. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103210. if (this._options.sizeAuto) {
  103211. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103212. this._scene.activeCamera.upperRadiusLimit) {
  103213. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103214. skyboxSize = groundSize;
  103215. }
  103216. var sceneDiagonalLenght = sceneDiagonal.length();
  103217. if (sceneDiagonalLenght > groundSize) {
  103218. groundSize = sceneDiagonalLenght * 2;
  103219. skyboxSize = groundSize;
  103220. }
  103221. // 10 % bigger.
  103222. groundSize *= 1.1;
  103223. skyboxSize *= 1.5;
  103224. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103225. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103226. }
  103227. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103228. };
  103229. /**
  103230. * Setup the ground according to the specified options.
  103231. */
  103232. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103233. var _this = this;
  103234. if (!this._ground || this._ground.isDisposed()) {
  103235. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103236. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103237. this._ground.parent = this._rootMesh;
  103238. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103239. }
  103240. this._ground.receiveShadows = this._options.enableGroundShadow;
  103241. };
  103242. /**
  103243. * Setup the ground material according to the specified options.
  103244. */
  103245. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103246. if (!this._groundMaterial) {
  103247. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103248. }
  103249. this._groundMaterial.alpha = this._options.groundOpacity;
  103250. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103251. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103252. this._groundMaterial.primaryColor = this._options.groundColor;
  103253. this._groundMaterial.useRGBColor = false;
  103254. this._groundMaterial.enableNoise = true;
  103255. if (this._ground) {
  103256. this._ground.material = this._groundMaterial;
  103257. }
  103258. };
  103259. /**
  103260. * Setup the ground diffuse texture according to the specified options.
  103261. */
  103262. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103263. if (!this._groundMaterial) {
  103264. return;
  103265. }
  103266. if (this._groundTexture) {
  103267. return;
  103268. }
  103269. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103270. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103271. return;
  103272. }
  103273. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103274. diffuseTexture.gammaSpace = false;
  103275. diffuseTexture.hasAlpha = true;
  103276. this._groundMaterial.diffuseTexture = diffuseTexture;
  103277. };
  103278. /**
  103279. * Setup the ground mirror texture according to the specified options.
  103280. */
  103281. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103282. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103283. if (!this._groundMirror) {
  103284. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103285. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103286. this._groundMirror.anisotropicFilteringLevel = 1;
  103287. this._groundMirror.wrapU = wrapping;
  103288. this._groundMirror.wrapV = wrapping;
  103289. this._groundMirror.gammaSpace = false;
  103290. if (this._groundMirror.renderList) {
  103291. for (var i = 0; i < this._scene.meshes.length; i++) {
  103292. var mesh = this._scene.meshes[i];
  103293. if (mesh !== this._ground &&
  103294. mesh !== this._skybox &&
  103295. mesh !== this._rootMesh) {
  103296. this._groundMirror.renderList.push(mesh);
  103297. }
  103298. }
  103299. }
  103300. }
  103301. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103302. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103303. };
  103304. /**
  103305. * Setup the ground to receive the mirror texture.
  103306. */
  103307. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103308. if (this._groundMaterial) {
  103309. this._groundMaterial.reflectionTexture = this._groundMirror;
  103310. this._groundMaterial.reflectionFresnel = true;
  103311. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103312. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103313. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103314. }
  103315. };
  103316. /**
  103317. * Setup the skybox according to the specified options.
  103318. */
  103319. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103320. var _this = this;
  103321. if (!this._skybox || this._skybox.isDisposed()) {
  103322. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103323. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103324. }
  103325. this._skybox.parent = this._rootMesh;
  103326. };
  103327. /**
  103328. * Setup the skybox material according to the specified options.
  103329. */
  103330. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103331. if (!this._skybox) {
  103332. return;
  103333. }
  103334. if (!this._skyboxMaterial) {
  103335. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103336. }
  103337. this._skyboxMaterial.useRGBColor = false;
  103338. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103339. this._skyboxMaterial.enableNoise = true;
  103340. this._skybox.material = this._skyboxMaterial;
  103341. };
  103342. /**
  103343. * Setup the skybox reflection texture according to the specified options.
  103344. */
  103345. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103346. if (!this._skyboxMaterial) {
  103347. return;
  103348. }
  103349. if (this._skyboxTexture) {
  103350. return;
  103351. }
  103352. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103353. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103354. return;
  103355. }
  103356. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103357. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103358. this._skyboxTexture.gammaSpace = false;
  103359. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103360. };
  103361. /**
  103362. * Dispose all the elements created by the Helper.
  103363. */
  103364. EnvironmentHelper.prototype.dispose = function () {
  103365. if (this._groundMaterial) {
  103366. this._groundMaterial.dispose(true, true);
  103367. }
  103368. if (this._skyboxMaterial) {
  103369. this._skyboxMaterial.dispose(true, true);
  103370. }
  103371. this._rootMesh.dispose(false);
  103372. };
  103373. /**
  103374. * Default ground texture URL.
  103375. */
  103376. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103377. /**
  103378. * Default skybox texture URL.
  103379. */
  103380. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103381. /**
  103382. * Default environment texture URL.
  103383. */
  103384. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103385. return EnvironmentHelper;
  103386. }());
  103387. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103388. })(BABYLON || (BABYLON = {}));
  103389. //# sourceMappingURL=babylon.environmentHelper.js.map
  103390. var BABYLON;
  103391. (function (BABYLON) {
  103392. /** Internal class used to store shapes for emitters */
  103393. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103394. function ParticleSystemSetEmitterCreationOptions() {
  103395. }
  103396. return ParticleSystemSetEmitterCreationOptions;
  103397. }());
  103398. /**
  103399. * Represents a set of particle systems working together to create a specific effect
  103400. */
  103401. var ParticleSystemSet = /** @class */ (function () {
  103402. function ParticleSystemSet() {
  103403. /**
  103404. * Gets the particle system list
  103405. */
  103406. this.systems = new Array();
  103407. }
  103408. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103409. /**
  103410. * Gets the emitter node used with this set
  103411. */
  103412. get: function () {
  103413. return this._emitterNode;
  103414. },
  103415. enumerable: true,
  103416. configurable: true
  103417. });
  103418. /**
  103419. * Creates a new emitter mesh as a sphere
  103420. * @param options defines the options used to create the sphere
  103421. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103422. * @param scene defines the hosting scene
  103423. */
  103424. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103425. if (this._emitterNode) {
  103426. this._emitterNode.dispose();
  103427. }
  103428. this._emitterCreationOptions = {
  103429. kind: "Sphere",
  103430. options: options,
  103431. renderingGroupId: renderingGroupId
  103432. };
  103433. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103434. emitterMesh.renderingGroupId = renderingGroupId;
  103435. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103436. material.emissiveColor = options.color;
  103437. emitterMesh.material = material;
  103438. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103439. var system = _a[_i];
  103440. system.emitter = emitterMesh;
  103441. }
  103442. this._emitterNode = emitterMesh;
  103443. };
  103444. /**
  103445. * Starts all particle systems of the set
  103446. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103447. */
  103448. ParticleSystemSet.prototype.start = function (emitter) {
  103449. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103450. var system = _a[_i];
  103451. if (emitter) {
  103452. system.emitter = emitter;
  103453. }
  103454. system.start();
  103455. }
  103456. };
  103457. /**
  103458. * Release all associated resources
  103459. */
  103460. ParticleSystemSet.prototype.dispose = function () {
  103461. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103462. var system = _a[_i];
  103463. system.dispose();
  103464. }
  103465. this.systems = [];
  103466. if (this._emitterNode) {
  103467. this._emitterNode.dispose();
  103468. this._emitterNode = null;
  103469. }
  103470. };
  103471. /**
  103472. * Serialize the set into a JSON compatible object
  103473. * @returns a JSON compatible representation of the set
  103474. */
  103475. ParticleSystemSet.prototype.serialize = function () {
  103476. var result = {};
  103477. result.systems = [];
  103478. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103479. var system = _a[_i];
  103480. result.systems.push(system.serialize());
  103481. }
  103482. if (this._emitterNode) {
  103483. result.emitter = this._emitterCreationOptions;
  103484. }
  103485. return result;
  103486. };
  103487. /**
  103488. * Parse a new ParticleSystemSet from a serialized source
  103489. * @param data defines a JSON compatible representation of the set
  103490. * @param scene defines the hosting scene
  103491. * @param gpu defines if we want GPU particles or CPU particles
  103492. * @returns a new ParticleSystemSet
  103493. */
  103494. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103495. if (gpu === void 0) { gpu = false; }
  103496. var result = new ParticleSystemSet();
  103497. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103498. scene = scene || BABYLON.Engine.LastCreatedScene;
  103499. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103500. var system = _a[_i];
  103501. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103502. }
  103503. if (data.emitter) {
  103504. var options = data.emitter.options;
  103505. switch (data.emitter.kind) {
  103506. case "Sphere":
  103507. result.setEmitterAsSphere({
  103508. diameter: options.diameter,
  103509. segments: options.segments,
  103510. color: BABYLON.Color3.FromArray(options.color)
  103511. }, data.emitter.renderingGroupId, scene);
  103512. break;
  103513. }
  103514. }
  103515. return result;
  103516. };
  103517. return ParticleSystemSet;
  103518. }());
  103519. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103520. })(BABYLON || (BABYLON = {}));
  103521. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103522. var BABYLON;
  103523. (function (BABYLON) {
  103524. /**
  103525. * This class is made for on one-liner static method to help creating particle system set.
  103526. */
  103527. var ParticleHelper = /** @class */ (function () {
  103528. function ParticleHelper() {
  103529. }
  103530. /**
  103531. * This is the main static method (one-liner) of this helper to create different particle systems
  103532. * @param type This string represents the type to the particle system to create
  103533. * @param scene The scene where the particle system should live
  103534. * @param gpu If the system will use gpu
  103535. * @returns the ParticleSystemSet created
  103536. */
  103537. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103538. if (gpu === void 0) { gpu = false; }
  103539. if (!scene) {
  103540. scene = BABYLON.Engine.LastCreatedScene;
  103541. ;
  103542. }
  103543. var token = {};
  103544. scene._addPendingData(token);
  103545. return new Promise(function (resolve, reject) {
  103546. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103547. scene._removePendingData(token);
  103548. return reject("Particle system with GPU is not supported.");
  103549. }
  103550. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103551. scene._removePendingData(token);
  103552. var newData = JSON.parse(data.toString());
  103553. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103554. }, undefined, undefined, undefined, function (req, exception) {
  103555. scene._removePendingData(token);
  103556. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103557. });
  103558. });
  103559. };
  103560. /**
  103561. * Static function used to export a particle system to a ParticleSystemSet variable.
  103562. * Please note that the emitter shape is not exported
  103563. * @param system defines the particle systems to export
  103564. */
  103565. ParticleHelper.ExportSet = function (systems) {
  103566. var set = new BABYLON.ParticleSystemSet();
  103567. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103568. var system = systems_1[_i];
  103569. set.systems.push(system);
  103570. }
  103571. return set;
  103572. };
  103573. /**
  103574. * Gets or sets base Assets URL
  103575. */
  103576. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103577. return ParticleHelper;
  103578. }());
  103579. BABYLON.ParticleHelper = ParticleHelper;
  103580. })(BABYLON || (BABYLON = {}));
  103581. //# sourceMappingURL=babylon.particleHelper.js.map
  103582. var BABYLON;
  103583. (function (BABYLON) {
  103584. /**
  103585. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103586. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103587. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103588. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103589. */
  103590. var VideoDome = /** @class */ (function (_super) {
  103591. __extends(VideoDome, _super);
  103592. /**
  103593. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103594. * @param name Element's name, child elements will append suffixes for their own names.
  103595. * @param urlsOrVideo defines the url(s) or the video element to use
  103596. * @param options An object containing optional or exposed sub element properties
  103597. */
  103598. function VideoDome(name, urlsOrVideo, options, scene) {
  103599. var _this = _super.call(this, name, scene) || this;
  103600. _this._useDirectMapping = false;
  103601. // set defaults and manage values
  103602. name = name || "videoDome";
  103603. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103604. options.clickToPlay = Boolean(options.clickToPlay);
  103605. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103606. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103607. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103608. if (options.useDirectMapping === undefined) {
  103609. _this._useDirectMapping = true;
  103610. }
  103611. else {
  103612. _this._useDirectMapping = options.useDirectMapping;
  103613. }
  103614. // create
  103615. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103616. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103617. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103618. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103619. // configure material
  103620. material.useEquirectangularFOV = true;
  103621. material.fovMultiplier = 1.0;
  103622. material.opacityFresnel = false;
  103623. if (_this._useDirectMapping) {
  103624. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103625. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103626. material.diffuseTexture = texture;
  103627. }
  103628. else {
  103629. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103630. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103631. material.reflectionTexture = texture;
  103632. }
  103633. // configure mesh
  103634. _this._mesh.material = material;
  103635. _this._mesh.parent = _this;
  103636. // optional configuration
  103637. if (options.clickToPlay) {
  103638. scene.onPointerUp = function () {
  103639. _this._videoTexture.video.play();
  103640. };
  103641. }
  103642. return _this;
  103643. }
  103644. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103645. /**
  103646. * Gets the video texture being displayed on the sphere
  103647. */
  103648. get: function () {
  103649. return this._videoTexture;
  103650. },
  103651. enumerable: true,
  103652. configurable: true
  103653. });
  103654. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103655. /**
  103656. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103657. * Also see the options.resolution property.
  103658. */
  103659. get: function () {
  103660. return this._material.fovMultiplier;
  103661. },
  103662. set: function (value) {
  103663. this._material.fovMultiplier = value;
  103664. },
  103665. enumerable: true,
  103666. configurable: true
  103667. });
  103668. /**
  103669. * Releases resources associated with this node.
  103670. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103671. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103672. */
  103673. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103674. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103675. this._videoTexture.dispose();
  103676. this._mesh.dispose();
  103677. this._material.dispose();
  103678. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103679. };
  103680. return VideoDome;
  103681. }(BABYLON.Node));
  103682. BABYLON.VideoDome = VideoDome;
  103683. })(BABYLON || (BABYLON = {}));
  103684. //# sourceMappingURL=babylon.videoDome.js.map
  103685. var BABYLON;
  103686. (function (BABYLON) {
  103687. /**
  103688. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103689. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103690. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103691. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103692. */
  103693. var PhotoDome = /** @class */ (function (_super) {
  103694. __extends(PhotoDome, _super);
  103695. /**
  103696. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103697. * @param name Element's name, child elements will append suffixes for their own names.
  103698. * @param urlsOfPhoto define the url of the photo to display
  103699. * @param options An object containing optional or exposed sub element properties
  103700. */
  103701. function PhotoDome(name, urlOfPhoto, options, scene) {
  103702. var _this = _super.call(this, name, scene) || this;
  103703. _this._useDirectMapping = false;
  103704. // set defaults and manage values
  103705. name = name || "photoDome";
  103706. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103707. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103708. if (options.useDirectMapping === undefined) {
  103709. _this._useDirectMapping = true;
  103710. }
  103711. else {
  103712. _this._useDirectMapping = options.useDirectMapping;
  103713. }
  103714. // create
  103715. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103716. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103717. // configure material
  103718. material.opacityFresnel = false;
  103719. material.useEquirectangularFOV = true;
  103720. material.fovMultiplier = 1.0;
  103721. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103722. // configure mesh
  103723. _this._mesh.material = material;
  103724. _this._mesh.parent = _this;
  103725. return _this;
  103726. }
  103727. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103728. /**
  103729. * Gets or sets the texture being displayed on the sphere
  103730. */
  103731. get: function () {
  103732. return this._photoTexture;
  103733. },
  103734. set: function (value) {
  103735. if (this._photoTexture === value) {
  103736. return;
  103737. }
  103738. this._photoTexture = value;
  103739. if (this._useDirectMapping) {
  103740. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103741. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103742. this._material.diffuseTexture = this._photoTexture;
  103743. }
  103744. else {
  103745. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103746. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103747. this._material.reflectionTexture = this._photoTexture;
  103748. }
  103749. },
  103750. enumerable: true,
  103751. configurable: true
  103752. });
  103753. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103754. /**
  103755. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103756. * Also see the options.resolution property.
  103757. */
  103758. get: function () {
  103759. return this._material.fovMultiplier;
  103760. },
  103761. set: function (value) {
  103762. this._material.fovMultiplier = value;
  103763. },
  103764. enumerable: true,
  103765. configurable: true
  103766. });
  103767. /**
  103768. * Releases resources associated with this node.
  103769. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103770. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103771. */
  103772. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103773. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103774. this._photoTexture.dispose();
  103775. this._mesh.dispose();
  103776. this._material.dispose();
  103777. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103778. };
  103779. return PhotoDome;
  103780. }(BABYLON.Node));
  103781. BABYLON.PhotoDome = PhotoDome;
  103782. })(BABYLON || (BABYLON = {}));
  103783. //# sourceMappingURL=babylon.photoDome.js.map
  103784. var BABYLON;
  103785. (function (BABYLON) {
  103786. BABYLON.Engine.prototype.createQuery = function () {
  103787. return this._gl.createQuery();
  103788. };
  103789. BABYLON.Engine.prototype.deleteQuery = function (query) {
  103790. this._gl.deleteQuery(query);
  103791. return this;
  103792. };
  103793. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  103794. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  103795. };
  103796. BABYLON.Engine.prototype.getQueryResult = function (query) {
  103797. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  103798. };
  103799. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  103800. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103801. this._gl.beginQuery(glAlgorithm, query);
  103802. return this;
  103803. };
  103804. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  103805. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103806. this._gl.endQuery(glAlgorithm);
  103807. return this;
  103808. };
  103809. BABYLON.Engine.prototype._createTimeQuery = function () {
  103810. var timerQuery = this.getCaps().timerQuery;
  103811. if (timerQuery.createQueryEXT) {
  103812. return timerQuery.createQueryEXT();
  103813. }
  103814. return this.createQuery();
  103815. };
  103816. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  103817. var timerQuery = this.getCaps().timerQuery;
  103818. if (timerQuery.deleteQueryEXT) {
  103819. timerQuery.deleteQueryEXT(query);
  103820. return;
  103821. }
  103822. this.deleteQuery(query);
  103823. };
  103824. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  103825. var timerQuery = this.getCaps().timerQuery;
  103826. if (timerQuery.getQueryObjectEXT) {
  103827. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  103828. }
  103829. return this.getQueryResult(query);
  103830. };
  103831. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  103832. var timerQuery = this.getCaps().timerQuery;
  103833. if (timerQuery.getQueryObjectEXT) {
  103834. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  103835. }
  103836. return this.isQueryResultAvailable(query);
  103837. };
  103838. BABYLON.Engine.prototype.startTimeQuery = function () {
  103839. var caps = this.getCaps();
  103840. var timerQuery = caps.timerQuery;
  103841. if (!timerQuery) {
  103842. return null;
  103843. }
  103844. var token = new BABYLON._TimeToken();
  103845. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103846. if (caps.canUseTimestampForTimerQuery) {
  103847. token._startTimeQuery = this._createTimeQuery();
  103848. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  103849. }
  103850. else {
  103851. if (this._currentNonTimestampToken) {
  103852. return this._currentNonTimestampToken;
  103853. }
  103854. token._timeElapsedQuery = this._createTimeQuery();
  103855. if (timerQuery.beginQueryEXT) {
  103856. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103857. }
  103858. else {
  103859. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103860. }
  103861. this._currentNonTimestampToken = token;
  103862. }
  103863. return token;
  103864. };
  103865. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  103866. var caps = this.getCaps();
  103867. var timerQuery = caps.timerQuery;
  103868. if (!timerQuery || !token) {
  103869. return -1;
  103870. }
  103871. if (caps.canUseTimestampForTimerQuery) {
  103872. if (!token._startTimeQuery) {
  103873. return -1;
  103874. }
  103875. if (!token._endTimeQuery) {
  103876. token._endTimeQuery = this._createTimeQuery();
  103877. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  103878. }
  103879. }
  103880. else if (!token._timeElapsedQueryEnded) {
  103881. if (!token._timeElapsedQuery) {
  103882. return -1;
  103883. }
  103884. if (timerQuery.endQueryEXT) {
  103885. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  103886. }
  103887. else {
  103888. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  103889. }
  103890. token._timeElapsedQueryEnded = true;
  103891. }
  103892. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103893. var available = false;
  103894. if (token._endTimeQuery) {
  103895. available = this._getTimeQueryAvailability(token._endTimeQuery);
  103896. }
  103897. else if (token._timeElapsedQuery) {
  103898. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  103899. }
  103900. if (available && !disjoint) {
  103901. var result = 0;
  103902. if (caps.canUseTimestampForTimerQuery) {
  103903. if (!token._startTimeQuery || !token._endTimeQuery) {
  103904. return -1;
  103905. }
  103906. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  103907. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  103908. result = timeEnd - timeStart;
  103909. this._deleteTimeQuery(token._startTimeQuery);
  103910. this._deleteTimeQuery(token._endTimeQuery);
  103911. token._startTimeQuery = null;
  103912. token._endTimeQuery = null;
  103913. }
  103914. else {
  103915. if (!token._timeElapsedQuery) {
  103916. return -1;
  103917. }
  103918. result = this._getTimeQueryResult(token._timeElapsedQuery);
  103919. this._deleteTimeQuery(token._timeElapsedQuery);
  103920. token._timeElapsedQuery = null;
  103921. token._timeElapsedQueryEnded = false;
  103922. this._currentNonTimestampToken = null;
  103923. }
  103924. return result;
  103925. }
  103926. return -1;
  103927. };
  103928. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  103929. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  103930. };
  103931. // We also need to update AbstractMesh as there is a portion of the code there
  103932. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  103933. var engine = this.getEngine();
  103934. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  103935. this._isOccluded = false;
  103936. return;
  103937. }
  103938. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  103939. this._isOccluded = false;
  103940. return;
  103941. }
  103942. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  103943. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  103944. if (isOcclusionQueryAvailable) {
  103945. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  103946. this._isOcclusionQueryInProgress = false;
  103947. this._occlusionInternalRetryCounter = 0;
  103948. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  103949. }
  103950. else {
  103951. this._occlusionInternalRetryCounter++;
  103952. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  103953. this._isOcclusionQueryInProgress = false;
  103954. this._occlusionInternalRetryCounter = 0;
  103955. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  103956. // if strict continue the last state of the object.
  103957. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  103958. }
  103959. else {
  103960. return;
  103961. }
  103962. }
  103963. }
  103964. var scene = this.getScene();
  103965. if (scene.getBoundingBoxRenderer) {
  103966. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  103967. if (!this._occlusionQuery) {
  103968. this._occlusionQuery = engine.createQuery();
  103969. }
  103970. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  103971. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  103972. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  103973. this._isOcclusionQueryInProgress = true;
  103974. }
  103975. };
  103976. })(BABYLON || (BABYLON = {}));
  103977. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  103978. 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}","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}","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 float 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)-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.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\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)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\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\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\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\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\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\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \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(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\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","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"};
  103979. 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};"};
  103980. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103981. globalObject["BABYLON"] = BABYLON;
  103982. //backwards compatibility
  103983. if(typeof earcut !== 'undefined') {
  103984. globalObject["Earcut"] = {
  103985. earcut: earcut
  103986. };
  103987. }
  103988. return BABYLON;
  103989. });
  103990. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21)))
  103991. /***/ }),
  103992. /* 1 */
  103993. /***/ (function(module, exports, __webpack_require__) {
  103994. "use strict";
  103995. Object.defineProperty(exports, "__esModule", { value: true });
  103996. var deepmerge = __webpack_require__(25);
  103997. var expDm = deepmerge['default'];
  103998. exports.deepmerge = expDm;
  103999. /**
  104000. * Is the provided string a URL?
  104001. *
  104002. * @param urlToCheck the url to inspect
  104003. */
  104004. function isUrl(urlToCheck) {
  104005. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  104006. return true;
  104007. }
  104008. return false;
  104009. }
  104010. exports.isUrl = isUrl;
  104011. /**
  104012. * Convert a string from kebab-case to camelCase
  104013. * @param s string to convert
  104014. */
  104015. function kebabToCamel(s) {
  104016. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  104017. }
  104018. exports.kebabToCamel = kebabToCamel;
  104019. //https://gist.github.com/youssman/745578062609e8acac9f
  104020. /**
  104021. * Convert a string from camelCase to kebab-case
  104022. * @param str string to convert
  104023. */
  104024. function camelToKebab(str) {
  104025. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  104026. }
  104027. exports.camelToKebab = camelToKebab;
  104028. /**
  104029. * This will extend an object with configuration values.
  104030. * What it practically does it take the keys from the configuration and set them on the object.
  104031. * I the configuration is a tree, it will traverse into the tree.
  104032. * @param object the object to extend
  104033. * @param config the configuration object that will extend the object
  104034. */
  104035. function extendClassWithConfig(object, config) {
  104036. if (!config || typeof config !== 'object')
  104037. return;
  104038. Object.keys(config).forEach(function (key) {
  104039. if (key in object && typeof object[key] !== 'function') {
  104040. // if (typeof object[key] === 'function') return;
  104041. // if it is an object, iterate internally until reaching basic types
  104042. if (typeof object[key] === 'object') {
  104043. extendClassWithConfig(object[key], config[key]);
  104044. }
  104045. else {
  104046. if (config[key] !== undefined) {
  104047. object[key] = config[key];
  104048. }
  104049. }
  104050. }
  104051. });
  104052. }
  104053. exports.extendClassWithConfig = extendClassWithConfig;
  104054. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ3hJLE9BQU8sSUFBSSxDQUFDO0tBQ2Y7SUFDRCxPQUFPLEtBQU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0FBQyxFQUFFLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO2FBQ25EO2lCQUFNO2dCQUNILElBQUksTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFNBQVMsRUFBRTtvQkFDM0IsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztpQkFDN0I7YUFDSjtTQUNKO0lBQ0wsQ0FBQyxDQUFDLENBQUM7QUFDUCxDQUFDO0FBZkQsc0RBZUMifQ==
  104055. /***/ }),
  104056. /* 2 */
  104057. /***/ (function(module, exports, __webpack_require__) {
  104058. "use strict";
  104059. function __export(m) {
  104060. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  104061. }
  104062. Object.defineProperty(exports, "__esModule", { value: true });
  104063. __export(__webpack_require__(30));
  104064. __export(__webpack_require__(32));
  104065. __export(__webpack_require__(38));
  104066. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  104067. /***/ }),
  104068. /* 3 */
  104069. /***/ (function(module, exports, __webpack_require__) {
  104070. "use strict";
  104071. Object.defineProperty(exports, "__esModule", { value: true });
  104072. var babylonjs_1 = __webpack_require__(0);
  104073. var _1 = __webpack_require__(1);
  104074. /**
  104075. * This is a simple HTML mapper.
  104076. * This mapper parses a single HTML element and returns the configuration from its attributes.
  104077. * it parses numbers and boolean values to the corresponding variable types.
  104078. * The following HTML element:
  104079. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  104080. *
  104081. * {
  104082. * test: 1, //a number!
  104083. * randomFlag: boolean, //camelCase and boolean
  104084. * a: {
  104085. * string: {
  104086. * object: "test" //dot-separated object levels
  104087. * }
  104088. * }
  104089. * }
  104090. */
  104091. var HTMLMapper = /** @class */ (function () {
  104092. function HTMLMapper() {
  104093. }
  104094. /**
  104095. * Map a specific element and get configuration from it
  104096. * @param element the HTML element to analyze.
  104097. */
  104098. HTMLMapper.prototype.map = function (element) {
  104099. var config = {};
  104100. var _loop_1 = function (attrIdx) {
  104101. var attr = element.attributes.item(attrIdx);
  104102. if (!attr) {
  104103. return "continue";
  104104. }
  104105. // map "object.property" to the right configuration place.
  104106. var split = attr.nodeName.split('.');
  104107. split.reduce(function (currentConfig, key, idx) {
  104108. //convert html-style to json-style
  104109. var camelKey = _1.kebabToCamel(key);
  104110. if (idx === split.length - 1) {
  104111. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  104112. if (val === "true") {
  104113. val = true;
  104114. }
  104115. else if (val === "false") {
  104116. val = false;
  104117. }
  104118. else if (val === "undefined") {
  104119. val = undefined;
  104120. }
  104121. else if (val === "null") {
  104122. val = null;
  104123. }
  104124. else {
  104125. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  104126. if (isnum) {
  104127. var number = parseFloat(val);
  104128. if (!isNaN(number)) {
  104129. val = number;
  104130. }
  104131. }
  104132. }
  104133. currentConfig[camelKey] = val;
  104134. }
  104135. else {
  104136. currentConfig[camelKey] = currentConfig[camelKey] || {};
  104137. }
  104138. return currentConfig[camelKey];
  104139. }, config);
  104140. };
  104141. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  104142. _loop_1(attrIdx);
  104143. }
  104144. return config;
  104145. };
  104146. return HTMLMapper;
  104147. }());
  104148. /**
  104149. * A simple string-to-JSON mapper.
  104150. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  104151. */
  104152. var JSONMapper = /** @class */ (function () {
  104153. function JSONMapper() {
  104154. }
  104155. JSONMapper.prototype.map = function (rawSource) {
  104156. return JSON.parse(rawSource);
  104157. };
  104158. return JSONMapper;
  104159. }());
  104160. /**
  104161. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  104162. * DOM elements and attributes.
  104163. */
  104164. var DOMMapper = /** @class */ (function () {
  104165. function DOMMapper() {
  104166. }
  104167. /**
  104168. * The mapping function that will convert HTML data to a viewer configuration object
  104169. * @param baseElement the baseElement from which to start traversing
  104170. * @returns a ViewerCOnfiguration object from the provided HTML Element
  104171. */
  104172. DOMMapper.prototype.map = function (baseElement) {
  104173. var htmlMapper = new HTMLMapper();
  104174. var config = htmlMapper.map(baseElement);
  104175. var traverseChildren = function (element, partConfig) {
  104176. var children = element.children;
  104177. if (children.length) {
  104178. for (var i = 0; i < children.length; ++i) {
  104179. var item = children.item(i);
  104180. // use the HTML Mapper to read configuration from a single element
  104181. var configMapped = htmlMapper.map(item);
  104182. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  104183. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  104184. partConfig[key] = [];
  104185. }
  104186. else {
  104187. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  104188. partConfig.push(configMapped);
  104189. }
  104190. else if (partConfig[key]) {
  104191. //exists already! probably an array
  104192. element.setAttribute('array', 'true');
  104193. var oldItem = partConfig[key];
  104194. partConfig = [oldItem, configMapped];
  104195. }
  104196. else {
  104197. partConfig[key] = configMapped;
  104198. }
  104199. }
  104200. traverseChildren(item, partConfig[key] || configMapped);
  104201. }
  104202. }
  104203. return partConfig;
  104204. };
  104205. traverseChildren(baseElement, config);
  104206. return config;
  104207. };
  104208. return DOMMapper;
  104209. }());
  104210. /**
  104211. * The MapperManager manages the different implemented mappers.
  104212. * It allows the user to register new mappers as well and use them to parse their own configuration data
  104213. */
  104214. var MapperManager = /** @class */ (function () {
  104215. function MapperManager() {
  104216. this._mappers = {
  104217. "html": new HTMLMapper(),
  104218. "json": new JSONMapper(),
  104219. "dom": new DOMMapper()
  104220. };
  104221. }
  104222. /**
  104223. * Get a specific configuration mapper.
  104224. *
  104225. * @param type the name of the mapper to load
  104226. */
  104227. MapperManager.prototype.getMapper = function (type) {
  104228. if (!this._mappers[type]) {
  104229. babylonjs_1.Tools.Error("No mapper defined for " + type);
  104230. }
  104231. return this._mappers[type];
  104232. };
  104233. /**
  104234. * Use this functio to register your own configuration mapper.
  104235. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  104236. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  104237. * @param mapper The implemented mapper
  104238. */
  104239. MapperManager.prototype.registerMapper = function (type, mapper) {
  104240. this._mappers[type] = mapper;
  104241. };
  104242. /**
  104243. * Dispose the mapper manager and all of its mappers.
  104244. */
  104245. MapperManager.prototype.dispose = function () {
  104246. this._mappers = {};
  104247. };
  104248. /**
  104249. * The default mapper is the JSON mapper.
  104250. */
  104251. MapperManager.DefaultMapper = 'json';
  104252. return MapperManager;
  104253. }());
  104254. exports.MapperManager = MapperManager;
  104255. /**
  104256. * mapperManager is a singleton of the type MapperManager.
  104257. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  104258. * or indirectly with using BabylonViewer.disposeAll()
  104259. */
  104260. exports.mapperManager = new MapperManager();
  104261. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQWdEQSxDQUFDO0lBOUNHOzs7T0FHRztJQUNILHdCQUFHLEdBQUgsVUFBSSxPQUFvQjtRQUVwQixJ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SxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  104262. /***/ }),
  104263. /* 4 */
  104264. /***/ (function(module, exports, __webpack_require__) {
  104265. "use strict";
  104266. Object.defineProperty(exports, "__esModule", { value: true });
  104267. var babylonjs_1 = __webpack_require__(0);
  104268. var ViewerGlobals = /** @class */ (function () {
  104269. function ViewerGlobals() {
  104270. this.disableInit = false;
  104271. this.disableWebGL2Support = false;
  104272. }
  104273. Object.defineProperty(ViewerGlobals.prototype, "version", {
  104274. get: function () {
  104275. return babylonjs_1.Engine.Version;
  104276. },
  104277. enumerable: true,
  104278. configurable: true
  104279. });
  104280. return ViewerGlobals;
  104281. }());
  104282. exports.ViewerGlobals = ViewerGlobals;
  104283. exports.viewerGlobals = new ViewerGlobals();
  104284. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  104285. /***/ }),
  104286. /* 5 */
  104287. /***/ (function(module, exports, __webpack_require__) {
  104288. "use strict";
  104289. Object.defineProperty(exports, "__esModule", { value: true });
  104290. var babylonjs_1 = __webpack_require__(0);
  104291. var modelAnimation_1 = __webpack_require__(52);
  104292. var _1 = __webpack_require__(1);
  104293. /**
  104294. * The current state of the model
  104295. */
  104296. var ModelState;
  104297. (function (ModelState) {
  104298. ModelState[ModelState["INIT"] = 0] = "INIT";
  104299. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  104300. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  104301. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  104302. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  104303. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  104304. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  104305. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  104306. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  104307. /**
  104308. * The viewer model is a container for all assets representing a sngle loaded model.
  104309. */
  104310. var ViewerModel = /** @class */ (function () {
  104311. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  104312. var _this = this;
  104313. this._observablesManager = _observablesManager;
  104314. this._configurationContainer = _configurationContainer;
  104315. /**
  104316. * the list of meshes that are a part of this model
  104317. */
  104318. this._meshes = [];
  104319. /**
  104320. * ParticleSystems connected to this model
  104321. */
  104322. this.particleSystems = [];
  104323. /**
  104324. * Skeletons defined in this model
  104325. */
  104326. this.skeletons = [];
  104327. this._loaderDone = false;
  104328. this._animatables = [];
  104329. this._frameRate = 60;
  104330. this._shadowsRenderedAfterLoad = false;
  104331. this.onLoadedObservable = new babylonjs_1.Observable();
  104332. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104333. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104334. this.onCompleteObservable = new babylonjs_1.Observable();
  104335. this.onAfterConfigure = new babylonjs_1.Observable();
  104336. this.state = ModelState.INIT;
  104337. var scene = this._configurationContainer && this._configurationContainer.scene;
  104338. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  104339. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  104340. this._pivotMesh.parent = this.rootMesh;
  104341. // rotate 180, gltf fun
  104342. this._pivotMesh.rotation.y += Math.PI;
  104343. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104344. this._animations = [];
  104345. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  104346. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  104347. if (this._observablesManager) {
  104348. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  104349. }
  104350. if (this._modelConfiguration.entryAnimation) {
  104351. this.rootMesh.setEnabled(false);
  104352. }
  104353. this.onLoadedObservable.add(function () {
  104354. _this.updateConfiguration(_this._modelConfiguration);
  104355. if (_this._observablesManager) {
  104356. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  104357. }
  104358. _this._initAnimations();
  104359. });
  104360. this.onCompleteObservable.add(function () {
  104361. _this.state = ModelState.COMPLETE;
  104362. });
  104363. }
  104364. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  104365. get: function () {
  104366. return this._shadowsRenderedAfterLoad;
  104367. },
  104368. set: function (rendered) {
  104369. if (!rendered) {
  104370. throw new Error("can only be enabled");
  104371. }
  104372. else {
  104373. this._shadowsRenderedAfterLoad = rendered;
  104374. }
  104375. },
  104376. enumerable: true,
  104377. configurable: true
  104378. });
  104379. ViewerModel.prototype.getViewerId = function () {
  104380. return this._configurationContainer && this._configurationContainer.viewerId;
  104381. };
  104382. Object.defineProperty(ViewerModel.prototype, "enabled", {
  104383. /**
  104384. * Is this model enabled?
  104385. */
  104386. get: function () {
  104387. return this.rootMesh.isEnabled();
  104388. },
  104389. /**
  104390. * Set whether this model is enabled or not.
  104391. */
  104392. set: function (enable) {
  104393. this.rootMesh.setEnabled(enable);
  104394. },
  104395. enumerable: true,
  104396. configurable: true
  104397. });
  104398. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  104399. set: function (done) {
  104400. this._loaderDone = done;
  104401. this._checkCompleteState();
  104402. },
  104403. enumerable: true,
  104404. configurable: true
  104405. });
  104406. ViewerModel.prototype._checkCompleteState = function () {
  104407. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  104408. this._modelComplete();
  104409. }
  104410. };
  104411. /**
  104412. * Add a mesh to this model.
  104413. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  104414. *
  104415. * @param mesh the new mesh to add
  104416. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  104417. */
  104418. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  104419. if (!mesh.parent) {
  104420. mesh.parent = this._pivotMesh;
  104421. }
  104422. mesh.receiveShadows = !!this.configuration.receiveShadows;
  104423. this._meshes.push(mesh);
  104424. if (triggerLoaded) {
  104425. return this.onLoadedObservable.notifyObserversWithPromise(this);
  104426. }
  104427. };
  104428. Object.defineProperty(ViewerModel.prototype, "meshes", {
  104429. /**
  104430. * get the list of meshes (excluding the root mesh)
  104431. */
  104432. get: function () {
  104433. return this._meshes;
  104434. },
  104435. enumerable: true,
  104436. configurable: true
  104437. });
  104438. Object.defineProperty(ViewerModel.prototype, "configuration", {
  104439. /**
  104440. * Get the model's configuration
  104441. */
  104442. get: function () {
  104443. return this._modelConfiguration;
  104444. },
  104445. /**
  104446. * (Re-)set the model's entire configuration
  104447. * @param newConfiguration the new configuration to replace the new one
  104448. */
  104449. set: function (newConfiguration) {
  104450. this._modelConfiguration = newConfiguration;
  104451. this._configureModel();
  104452. },
  104453. enumerable: true,
  104454. configurable: true
  104455. });
  104456. /**
  104457. * Update the current configuration with new values.
  104458. * Configuration will not be overwritten, but merged with the new configuration.
  104459. * Priority is to the new configuration
  104460. * @param newConfiguration the configuration to be merged into the current configuration;
  104461. */
  104462. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  104463. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  104464. this._configureModel();
  104465. };
  104466. ViewerModel.prototype._initAnimations = function () {
  104467. var _this = this;
  104468. // check if this is not a gltf loader and init the animations
  104469. if (this.skeletons.length) {
  104470. this.skeletons.forEach(function (skeleton, idx) {
  104471. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  104472. var add = false;
  104473. skeleton.getAnimatables().forEach(function (a) {
  104474. if (a.animations[0]) {
  104475. ag.addTargetedAnimation(a.animations[0], a);
  104476. add = true;
  104477. }
  104478. });
  104479. if (add) {
  104480. _this.addAnimationGroup(ag);
  104481. }
  104482. });
  104483. }
  104484. var completeCallback = function () {
  104485. };
  104486. if (this._modelConfiguration.animation) {
  104487. if (this._modelConfiguration.animation.playOnce) {
  104488. this._animations.forEach(function (a) {
  104489. a.playMode = 0 /* ONCE */;
  104490. });
  104491. }
  104492. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  104493. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  104494. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  104495. completeCallback = function () {
  104496. _this.playAnimation(animationName_1);
  104497. };
  104498. }
  104499. }
  104500. this._enterScene(completeCallback);
  104501. };
  104502. /**
  104503. * Animates the model from the current position to the default position
  104504. * @param completeCallback A function to call when the animation has completed
  104505. */
  104506. ViewerModel.prototype._enterScene = function (completeCallback) {
  104507. var _this = this;
  104508. var scene = this.rootMesh.getScene();
  104509. var previousValue = scene.animationPropertiesOverride.enableBlending;
  104510. var callback = function () {
  104511. _this.state = ModelState.ENTRYDONE;
  104512. scene.animationPropertiesOverride.enableBlending = previousValue;
  104513. _this._checkCompleteState();
  104514. if (completeCallback)
  104515. completeCallback();
  104516. };
  104517. if (!this._entryAnimation) {
  104518. callback();
  104519. return;
  104520. }
  104521. this.rootMesh.setEnabled(true);
  104522. // disable blending for the sake of the entry animation;
  104523. scene.animationPropertiesOverride.enableBlending = false;
  104524. this._applyAnimation(this._entryAnimation, true, callback);
  104525. };
  104526. /**
  104527. * Animates the model from the current position to the exit-screen position
  104528. * @param completeCallback A function to call when the animation has completed
  104529. */
  104530. ViewerModel.prototype._exitScene = function (completeCallback) {
  104531. if (!this._exitAnimation) {
  104532. completeCallback();
  104533. return;
  104534. }
  104535. this._applyAnimation(this._exitAnimation, false, completeCallback);
  104536. };
  104537. ViewerModel.prototype._modelComplete = function () {
  104538. var _this = this;
  104539. //reapply material defines to be sure:
  104540. var meshes = this._pivotMesh.getChildMeshes(false);
  104541. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  104542. _this._applyModelMaterialConfiguration(mesh.material);
  104543. });
  104544. this.state = ModelState.COMPLETE;
  104545. this.onCompleteObservable.notifyObservers(this);
  104546. };
  104547. /**
  104548. * Add a new animation group to this model.
  104549. * @param animationGroup the new animation group to be added
  104550. */
  104551. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  104552. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  104553. };
  104554. /**
  104555. * Get the ModelAnimation array
  104556. */
  104557. ViewerModel.prototype.getAnimations = function () {
  104558. return this._animations;
  104559. };
  104560. /**
  104561. * Get the animations' names. Using the names you can play a specific animation.
  104562. */
  104563. ViewerModel.prototype.getAnimationNames = function () {
  104564. return this._animations.map(function (a) { return a.name; });
  104565. };
  104566. /**
  104567. * Get an animation by the provided name. Used mainly when playing n animation.
  104568. * @param name the name of the animation to find
  104569. */
  104570. ViewerModel.prototype._getAnimationByName = function (name) {
  104571. // can't use .find, noe available on IE
  104572. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104573. // what the next line means - if two animations have the same name, they will not be returned!
  104574. if (filtered.length === 1) {
  104575. return filtered[0];
  104576. }
  104577. else {
  104578. return null;
  104579. }
  104580. };
  104581. /**
  104582. * Choose an initialized animation using its name and start playing it
  104583. * @param name the name of the animation to play
  104584. * @returns The model aniamtion to be played.
  104585. */
  104586. ViewerModel.prototype.playAnimation = function (name) {
  104587. var animation = this.setCurrentAnimationByName(name);
  104588. if (animation) {
  104589. animation.start();
  104590. }
  104591. return animation;
  104592. };
  104593. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  104594. var animation = this._getAnimationByName(name);
  104595. if (animation) {
  104596. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  104597. this.currentAnimation.stop();
  104598. }
  104599. this.currentAnimation = animation;
  104600. return animation;
  104601. }
  104602. else {
  104603. throw new Error("animation not found - " + name);
  104604. }
  104605. };
  104606. ViewerModel.prototype._configureModel = function () {
  104607. var _this = this;
  104608. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  104609. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  104610. var updateMeshesWithNoParent = function (variable, value, param) {
  104611. meshesWithNoParent.forEach(function (mesh) {
  104612. if (param) {
  104613. mesh[variable][param] = value;
  104614. }
  104615. else {
  104616. mesh[variable] = value;
  104617. }
  104618. });
  104619. };
  104620. var updateXYZ = function (variable, configValues) {
  104621. if (configValues.x !== undefined) {
  104622. updateMeshesWithNoParent(variable, configValues.x, 'x');
  104623. }
  104624. if (configValues.y !== undefined) {
  104625. updateMeshesWithNoParent(variable, configValues.y, 'y');
  104626. }
  104627. if (configValues.z !== undefined) {
  104628. updateMeshesWithNoParent(variable, configValues.z, 'z');
  104629. }
  104630. if (configValues.w !== undefined) {
  104631. updateMeshesWithNoParent(variable, configValues.w, 'w');
  104632. }
  104633. };
  104634. if (this._modelConfiguration.normalize) {
  104635. var center = false;
  104636. var unitSize = false;
  104637. var parentIndex = void 0;
  104638. if (this._modelConfiguration.normalize === true) {
  104639. center = true;
  104640. unitSize = true;
  104641. }
  104642. else {
  104643. center = !!this._modelConfiguration.normalize.center;
  104644. unitSize = !!this._modelConfiguration.normalize.unitSize;
  104645. parentIndex = this._modelConfiguration.normalize.parentIndex;
  104646. }
  104647. var meshesToNormalize = [];
  104648. if (parentIndex !== undefined) {
  104649. meshesToNormalize.push(this._meshes[parentIndex]);
  104650. }
  104651. else {
  104652. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  104653. }
  104654. if (unitSize) {
  104655. meshesToNormalize.forEach(function (mesh) {
  104656. mesh.normalizeToUnitCube(true);
  104657. mesh.computeWorldMatrix(true);
  104658. });
  104659. }
  104660. if (center) {
  104661. meshesToNormalize.forEach(function (mesh) {
  104662. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  104663. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  104664. var halfSizeVec = sizeVec.scale(0.5);
  104665. var center = boundingInfo.min.add(halfSizeVec);
  104666. mesh.position = center.scale(-1);
  104667. mesh.position.y += halfSizeVec.y;
  104668. // Recompute Info.
  104669. mesh.computeWorldMatrix(true);
  104670. });
  104671. }
  104672. }
  104673. else {
  104674. // if centered, should be done here
  104675. }
  104676. // position?
  104677. if (this._modelConfiguration.position) {
  104678. updateXYZ('position', this._modelConfiguration.position);
  104679. }
  104680. if (this._modelConfiguration.rotation) {
  104681. //quaternion?
  104682. if (this._modelConfiguration.rotation.w) {
  104683. meshesWithNoParent.forEach(function (mesh) {
  104684. if (!mesh.rotationQuaternion) {
  104685. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  104686. }
  104687. });
  104688. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  104689. }
  104690. else {
  104691. updateXYZ('rotation', this._modelConfiguration.rotation);
  104692. }
  104693. }
  104694. if (this._modelConfiguration.rotationOffsetAxis) {
  104695. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  104696. meshesWithNoParent.forEach(function (m) {
  104697. if (_this._modelConfiguration.rotationOffsetAngle) {
  104698. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  104699. }
  104700. });
  104701. }
  104702. if (this._modelConfiguration.scaling) {
  104703. updateXYZ('scaling', this._modelConfiguration.scaling);
  104704. }
  104705. if (this._modelConfiguration.castShadow) {
  104706. this._meshes.forEach(function (mesh) {
  104707. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  104708. });
  104709. }
  104710. var meshes = this._pivotMesh.getChildMeshes(false);
  104711. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  104712. _this._applyModelMaterialConfiguration(mesh.material);
  104713. });
  104714. if (this._modelConfiguration.entryAnimation) {
  104715. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  104716. }
  104717. if (this._modelConfiguration.exitAnimation) {
  104718. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  104719. }
  104720. this.onAfterConfigure.notifyObservers(this);
  104721. };
  104722. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  104723. var anim = {
  104724. time: 0.5
  104725. };
  104726. if (animConfig.scaling) {
  104727. anim.scaling = babylonjs_1.Vector3.Zero();
  104728. }
  104729. if (animConfig.easingFunction !== undefined) {
  104730. anim.easingFunction = animConfig.easingFunction;
  104731. }
  104732. if (animConfig.easingMode !== undefined) {
  104733. anim.easingMode = animConfig.easingMode;
  104734. }
  104735. _1.extendClassWithConfig(anim, animConfig);
  104736. return anim;
  104737. };
  104738. /**
  104739. * Apply a material configuration to a material
  104740. * @param material Material to apply configuration to
  104741. */
  104742. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  104743. if (!this._modelConfiguration.material)
  104744. return;
  104745. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  104746. if (material instanceof babylonjs_1.PBRMaterial) {
  104747. if (this._modelConfiguration.material.directIntensity !== undefined) {
  104748. material.directIntensity = this._modelConfiguration.material.directIntensity;
  104749. }
  104750. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  104751. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  104752. }
  104753. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  104754. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  104755. }
  104756. if (this._modelConfiguration.material.directEnabled !== undefined) {
  104757. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  104758. }
  104759. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  104760. material.reflectionColor = this._configurationContainer.reflectionColor;
  104761. }
  104762. }
  104763. else if (material instanceof babylonjs_1.MultiMaterial) {
  104764. for (var i = 0; i < material.subMaterials.length; i++) {
  104765. var subMaterial = material.subMaterials[i];
  104766. if (subMaterial) {
  104767. this._applyModelMaterialConfiguration(subMaterial);
  104768. }
  104769. }
  104770. }
  104771. };
  104772. /**
  104773. * Start entry/exit animation given an animation configuration
  104774. * @param animationConfiguration Entry/Exit animation configuration
  104775. * @param isEntry Pass true if the animation is an entry animation
  104776. * @param completeCallback Callback to execute when the animation completes
  104777. */
  104778. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  104779. var animations = [];
  104780. //scale
  104781. if (animationConfiguration.scaling) {
  104782. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  104783. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  104784. if (!scaleStart.equals(scaleEnd)) {
  104785. this.rootMesh.scaling = scaleStart;
  104786. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  104787. animations.push(this._scaleTransition);
  104788. }
  104789. }
  104790. //Start the animation(s)
  104791. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  104792. completeCallback(); });
  104793. };
  104794. /**
  104795. * Begin @animations with the specified @easingFunction
  104796. * @param animations The BABYLON Animations to begin
  104797. * @param duration of transition, in seconds
  104798. * @param easingFunction An easing function to apply
  104799. * @param easingMode A easing mode to apply to the easingFunction
  104800. * @param onAnimationEnd Call back trigger at the end of the animation.
  104801. */
  104802. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  104803. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  104804. if (easingFunction) {
  104805. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104806. var animation = animations_1[_i];
  104807. easingFunction.setEasingMode(easingMode);
  104808. animation.setEasingFunction(easingFunction);
  104809. }
  104810. }
  104811. //Stop any current animations before starting the new one - merging not yet supported.
  104812. this.stopAllAnimations();
  104813. this.rootMesh.animations = animations;
  104814. if (this.rootMesh.getScene().beginAnimation) {
  104815. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  104816. if (onAnimationEnd) {
  104817. onAnimationEnd();
  104818. }
  104819. });
  104820. this._animatables.push(animatable);
  104821. }
  104822. };
  104823. /**
  104824. * Sets key values on an Animation from first to last frame.
  104825. * @param animation The Babylon animation object to set keys on
  104826. * @param startValue The value of the first key
  104827. * @param endValue The value of the last key
  104828. * @param duration The duration of the animation, used to determine the end frame
  104829. */
  104830. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  104831. animation.setKeys([
  104832. {
  104833. frame: 0,
  104834. value: startValue
  104835. },
  104836. {
  104837. frame: this._frameRate * duration,
  104838. value: endValue
  104839. }
  104840. ]);
  104841. };
  104842. /**
  104843. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  104844. * @param easingFunctionID The enum of the easing funtion to create
  104845. * @return The newly created Babylon easing function object
  104846. */
  104847. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  104848. var easingFunction;
  104849. switch (easingFunctionID) {
  104850. case 1 /* CircleEase */:
  104851. easingFunction = new babylonjs_1.CircleEase();
  104852. break;
  104853. case 2 /* BackEase */:
  104854. easingFunction = new babylonjs_1.BackEase(0.3);
  104855. break;
  104856. case 3 /* BounceEase */:
  104857. easingFunction = new babylonjs_1.BounceEase();
  104858. break;
  104859. case 4 /* CubicEase */:
  104860. easingFunction = new babylonjs_1.CubicEase();
  104861. break;
  104862. case 5 /* ElasticEase */:
  104863. easingFunction = new babylonjs_1.ElasticEase();
  104864. break;
  104865. case 6 /* ExponentialEase */:
  104866. easingFunction = new babylonjs_1.ExponentialEase();
  104867. break;
  104868. case 7 /* PowerEase */:
  104869. easingFunction = new babylonjs_1.PowerEase();
  104870. break;
  104871. case 8 /* QuadraticEase */:
  104872. easingFunction = new babylonjs_1.QuadraticEase();
  104873. break;
  104874. case 9 /* QuarticEase */:
  104875. easingFunction = new babylonjs_1.QuarticEase();
  104876. break;
  104877. case 10 /* QuinticEase */:
  104878. easingFunction = new babylonjs_1.QuinticEase();
  104879. break;
  104880. case 11 /* SineEase */:
  104881. easingFunction = new babylonjs_1.SineEase();
  104882. break;
  104883. default:
  104884. babylonjs_1.Tools.Log("No ease function found");
  104885. break;
  104886. }
  104887. return easingFunction;
  104888. };
  104889. /**
  104890. * Stops and removes all animations that have been applied to the model
  104891. */
  104892. ViewerModel.prototype.stopAllAnimations = function () {
  104893. if (this.rootMesh) {
  104894. this.rootMesh.animations = [];
  104895. }
  104896. if (this.currentAnimation) {
  104897. this.currentAnimation.stop();
  104898. }
  104899. while (this._animatables.length) {
  104900. this._animatables[0].onAnimationEnd = null;
  104901. this._animatables[0].stop();
  104902. this._animatables.shift();
  104903. }
  104904. };
  104905. /**
  104906. * Will remove this model from the viewer (but NOT dispose it).
  104907. */
  104908. ViewerModel.prototype.remove = function () {
  104909. this.stopAllAnimations();
  104910. // hide it
  104911. this.rootMesh.isVisible = false;
  104912. if (this._observablesManager) {
  104913. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  104914. }
  104915. };
  104916. /**
  104917. * Dispose this model, including all of its associated assets.
  104918. */
  104919. ViewerModel.prototype.dispose = function () {
  104920. this.remove();
  104921. this.onAfterConfigure.clear();
  104922. this.onLoadedObservable.clear();
  104923. this.onLoadErrorObservable.clear();
  104924. this.onLoadProgressObservable.clear();
  104925. if (this.loader && this.loader.name === "gltf") {
  104926. this.loader.dispose();
  104927. }
  104928. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104929. this.particleSystems.length = 0;
  104930. this.skeletons.forEach(function (s) { return s.dispose(); });
  104931. this.skeletons.length = 0;
  104932. this._animations.forEach(function (ag) { return ag.dispose(); });
  104933. this._animations.length = 0;
  104934. this.rootMesh.dispose(false, true);
  104935. };
  104936. return ViewerModel;
  104937. }());
  104938. exports.ViewerModel = ViewerModel;
  104939. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBdWQ7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UFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  104940. /***/ }),
  104941. /* 6 */
  104942. /***/ (function(module, exports, __webpack_require__) {
  104943. "use strict";
  104944. Object.defineProperty(exports, "__esModule", { value: true });
  104945. var babylonjs_1 = __webpack_require__(0);
  104946. /**
  104947. * Receives Telemetry events and raises events to the API
  104948. */
  104949. var TelemetryManager = /** @class */ (function () {
  104950. function TelemetryManager() {
  104951. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  104952. this._event = this._eventEnabled;
  104953. }
  104954. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  104955. /**
  104956. * Receives a telemetry event
  104957. * @param event The name of the Telemetry event
  104958. * @param details An additional value, or an object containing a list of property/value pairs
  104959. */
  104960. get: function () {
  104961. return this._event;
  104962. },
  104963. enumerable: true,
  104964. configurable: true
  104965. });
  104966. /**
  104967. * Log a Telemetry event for errors raised on the WebGL context.
  104968. * @param engine The Babylon engine with the WebGL context.
  104969. */
  104970. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  104971. if (!engine) {
  104972. return;
  104973. }
  104974. var logErrors = true;
  104975. while (logErrors) {
  104976. var error = engine.getError();
  104977. if (error === 0) {
  104978. logErrors = false;
  104979. }
  104980. else {
  104981. this.broadcast("WebGL Error", viewerId, { error: error });
  104982. }
  104983. }
  104984. };
  104985. Object.defineProperty(TelemetryManager.prototype, "enable", {
  104986. /**
  104987. * Enable or disable telemetry events
  104988. * @param enabled Boolan, true if events are enabled
  104989. */
  104990. set: function (enabled) {
  104991. if (enabled) {
  104992. this._event = this._eventEnabled;
  104993. }
  104994. else {
  104995. this._event = this._eventDisabled;
  104996. }
  104997. },
  104998. enumerable: true,
  104999. configurable: true
  105000. });
  105001. /**
  105002. * Called on event when disabled, typically do nothing here
  105003. */
  105004. TelemetryManager.prototype._eventDisabled = function () {
  105005. // nothing to do
  105006. };
  105007. /**
  105008. * Called on event when enabled
  105009. * @param event - The name of the Telemetry event
  105010. * @param details An additional value, or an object containing a list of property/value pairs
  105011. */
  105012. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  105013. var telemetryData = {
  105014. viewerId: viewerId,
  105015. event: event,
  105016. session: this.session,
  105017. date: new Date(),
  105018. now: window.performance ? window.performance.now() : Date.now(),
  105019. detail: null
  105020. };
  105021. if (typeof details === "object") {
  105022. for (var attr in details) {
  105023. if (details.hasOwnProperty(attr)) {
  105024. telemetryData[attr] = details[attr];
  105025. }
  105026. }
  105027. }
  105028. else if (details) {
  105029. telemetryData.detail = details;
  105030. }
  105031. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  105032. };
  105033. Object.defineProperty(TelemetryManager.prototype, "session", {
  105034. /**
  105035. * Returns the current session ID or creates one if it doesn't exixt
  105036. * @return The current session ID
  105037. */
  105038. get: function () {
  105039. if (!this._currentSessionId) {
  105040. //String + Timestamp + Random Integer
  105041. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  105042. }
  105043. return this._currentSessionId;
  105044. },
  105045. enumerable: true,
  105046. configurable: true
  105047. });
  105048. /**
  105049. * Disposes the telemetry manager
  105050. */
  105051. TelemetryManager.prototype.dispose = function () {
  105052. this.onEventBroadcastedObservable.clear();
  105053. delete this.onEventBroadcastedObservable;
  105054. };
  105055. return TelemetryManager;
  105056. }());
  105057. exports.TelemetryManager = TelemetryManager;
  105058. exports.telemetryManager = new TelemetryManager();
  105059. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0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sR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsR0FBRyxPQUFPLENBQUMsQ0FBQzthQUMxRjtZQUNELE9BQU8sSUFBSSxDQUFDLGlCQUFpQixDQUFDO1FBQ2xDLENBQUM7OztPQUFBO0lBRUQ7O09BRUc7SUFDSSxrQ0FBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLDRCQUE0QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQzFDLE9BQU8sSUFBSSxDQUFDLDRCQUE0QixDQUFDO0lBQzdDLENBQUM7SUFDTCx1QkFBQztBQUFELENBQUMsQUF2R0QsSUF1R0M7QUF2R1ksNENBQWdCO0FBeUdoQixRQUFBLGdCQUFnQixHQUFHLElBQUksZ0JBQWdCLEVBQUUsQ0FBQyJ9
  105060. /***/ }),
  105061. /* 7 */
  105062. /***/ (function(module, exports, __webpack_require__) {
  105063. "use strict";
  105064. Object.defineProperty(exports, "__esModule", { value: true });
  105065. var babylonjs_1 = __webpack_require__(0);
  105066. /**
  105067. * The viewer manager is the container for all viewers currently registered on this page.
  105068. * It is possible to have more than one viewer on a single page.
  105069. */
  105070. var ViewerManager = /** @class */ (function () {
  105071. function ViewerManager() {
  105072. this._viewers = {};
  105073. this.onViewerAddedObservable = new babylonjs_1.Observable();
  105074. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  105075. }
  105076. /**
  105077. * Adding a new viewer to the viewer manager and start tracking it.
  105078. * @param viewer the viewer to add
  105079. */
  105080. ViewerManager.prototype.addViewer = function (viewer) {
  105081. this._viewers[viewer.getBaseId()] = viewer;
  105082. this._onViewerAdded(viewer);
  105083. };
  105084. /**
  105085. * remove a viewer from the viewer manager
  105086. * @param viewer the viewer to remove
  105087. */
  105088. ViewerManager.prototype.removeViewer = function (viewer) {
  105089. var id = viewer.getBaseId();
  105090. delete this._viewers[id];
  105091. this.onViewerRemovedObservable.notifyObservers(id);
  105092. };
  105093. /**
  105094. * 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)
  105095. * @param id the id of the HTMl element (or the viewer's, if none provided)
  105096. */
  105097. ViewerManager.prototype.getViewerById = function (id) {
  105098. return this._viewers[id];
  105099. };
  105100. /**
  105101. * Get a viewer using a container element
  105102. * @param element the HTML element to search viewers associated with
  105103. */
  105104. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  105105. for (var id in this._viewers) {
  105106. if (this._viewers[id].containerElement === element) {
  105107. return this.getViewerById(id);
  105108. }
  105109. }
  105110. };
  105111. /**
  105112. * Get a promise that will fullfil when this viewer was initialized.
  105113. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  105114. * you will get the viewer after everything was already configured.
  105115. * @param id the viewer id to find
  105116. */
  105117. ViewerManager.prototype.getViewerPromiseById = function (id) {
  105118. var _this = this;
  105119. return new Promise(function (resolve, reject) {
  105120. var localViewer = _this.getViewerById(id);
  105121. if (localViewer) {
  105122. return resolve(localViewer);
  105123. }
  105124. var viewerFunction = function (viewer) {
  105125. if (viewer.getBaseId() === id) {
  105126. resolve(viewer);
  105127. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  105128. }
  105129. };
  105130. _this.onViewerAddedObservable.add(viewerFunction);
  105131. });
  105132. };
  105133. ViewerManager.prototype._onViewerAdded = function (viewer) {
  105134. this.onViewerAdded && this.onViewerAdded(viewer);
  105135. this.onViewerAddedObservable.notifyObservers(viewer);
  105136. };
  105137. /**
  105138. * dispose the manager and all of its associated viewers
  105139. */
  105140. ViewerManager.prototype.dispose = function () {
  105141. delete this._onViewerAdded;
  105142. for (var id in this._viewers) {
  105143. this._viewers[id].dispose();
  105144. }
  105145. this.onViewerAddedObservable.clear();
  105146. this.onViewerRemovedObservable.clear();
  105147. };
  105148. return ViewerManager;
  105149. }());
  105150. exports.ViewerManager = ViewerManager;
  105151. exports.viewerManager = new ViewerManager();
  105152. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW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UsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN6RCxDQUFDO0lBRUQ7O09BRUc7SUFDSSwrQkFBTyxHQUFkO1FBQ0ksT0FBTyxJQUFJLENBQUMsY0FBYyxDQUFDO1FBRTNCLEtBQUssSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtZQUMxQixJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  105153. /***/ }),
  105154. /* 8 */
  105155. /***/ (function(module, exports, __webpack_require__) {
  105156. "use strict";
  105157. var __extends = (this && this.__extends) || (function () {
  105158. var extendStatics = Object.setPrototypeOf ||
  105159. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  105160. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  105161. return function (d, b) {
  105162. extendStatics(d, b);
  105163. function __() { this.constructor = d; }
  105164. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105165. };
  105166. })();
  105167. Object.defineProperty(exports, "__esModule", { value: true });
  105168. var viewer_1 = __webpack_require__(9);
  105169. var babylonjs_1 = __webpack_require__(0);
  105170. var hdButtonPlugin_1 = __webpack_require__(65);
  105171. /**
  105172. * The Default viewer is the default implementation of the AbstractViewer.
  105173. * It uses the templating system to render a new canvas and controls.
  105174. */
  105175. var DefaultViewer = /** @class */ (function (_super) {
  105176. __extends(DefaultViewer, _super);
  105177. /**
  105178. * Create a new default viewer
  105179. * @param containerElement the element in which the templates will be rendered
  105180. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  105181. */
  105182. function DefaultViewer(containerElement, initialConfiguration) {
  105183. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  105184. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  105185. _this.containerElement = containerElement;
  105186. _this._registeredPlugins = [];
  105187. _this._handlePointerDown = function (event) {
  105188. var pointerDown = event.event;
  105189. if (pointerDown.button !== 0)
  105190. return;
  105191. var element = event.event.target;
  105192. if (!element) {
  105193. return;
  105194. }
  105195. var parentClasses = element.parentElement.classList;
  105196. var elementClasses = element.classList;
  105197. var elementName = "";
  105198. for (var i = 0; i < elementClasses.length; ++i) {
  105199. var className = elementClasses[i];
  105200. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  105201. elementName = className;
  105202. break;
  105203. }
  105204. }
  105205. switch (elementName) {
  105206. case "speed-button":
  105207. case "types-button":
  105208. if (parentClasses.contains("open")) {
  105209. parentClasses.remove("open");
  105210. }
  105211. else {
  105212. parentClasses.add("open");
  105213. }
  105214. break;
  105215. case "play-pause-button":
  105216. _this._togglePlayPause();
  105217. break;
  105218. case "label-option-button":
  105219. var value = element.dataset["value"];
  105220. var label = element.querySelector("span.animation-label");
  105221. if (label && value) {
  105222. _this._updateAnimationType({ value: value, label: label.innerHTML });
  105223. }
  105224. break;
  105225. case "speed-option-button":
  105226. if (!_this._currentAnimation) {
  105227. return;
  105228. }
  105229. var speed = element.dataset["value"];
  105230. if (speed)
  105231. _this._updateAnimationSpeed(speed);
  105232. break;
  105233. case "progress-wrapper":
  105234. _this._resumePlay = !_this._isAnimationPaused;
  105235. if (_this._resumePlay) {
  105236. _this._togglePlayPause(true);
  105237. }
  105238. break;
  105239. case "fullscreen-button":
  105240. _this.toggleFullscreen();
  105241. break;
  105242. case "vr-button":
  105243. _this.toggleVR();
  105244. break;
  105245. default:
  105246. return;
  105247. }
  105248. };
  105249. /**
  105250. * Plays or Pauses animation
  105251. */
  105252. _this._togglePlayPause = function (noUiUpdate) {
  105253. if (!_this._currentAnimation) {
  105254. return;
  105255. }
  105256. if (_this._isAnimationPaused) {
  105257. _this._currentAnimation.restart();
  105258. }
  105259. else {
  105260. _this._currentAnimation.pause();
  105261. }
  105262. _this._isAnimationPaused = !_this._isAnimationPaused;
  105263. if (noUiUpdate)
  105264. return;
  105265. var navbar = _this.templateManager.getTemplate('navBar');
  105266. if (!navbar)
  105267. return;
  105268. navbar.updateParams({
  105269. paused: _this._isAnimationPaused,
  105270. });
  105271. };
  105272. /**
  105273. * Control progress bar position based on animation current frame
  105274. */
  105275. _this._updateProgressBar = function () {
  105276. var navbar = _this.templateManager.getTemplate('navBar');
  105277. if (!navbar)
  105278. return;
  105279. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  105280. if (progressSlider && _this._currentAnimation) {
  105281. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  105282. var currentValue = progressSlider.valueAsNumber;
  105283. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  105284. progressSlider.value = '' + progress;
  105285. }
  105286. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  105287. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  105288. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  105289. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  105290. }
  105291. }
  105292. else {
  105293. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  105294. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  105295. _this._oldIdleRotationValue = 0;
  105296. }
  105297. }
  105298. }
  105299. };
  105300. /**
  105301. * Update Current Animation Speed
  105302. */
  105303. _this._updateAnimationSpeed = function (speed, paramsObject) {
  105304. var navbar = _this.templateManager.getTemplate('navBar');
  105305. if (!navbar)
  105306. return;
  105307. if (speed && _this._currentAnimation) {
  105308. _this._currentAnimation.speedRatio = parseFloat(speed);
  105309. if (!_this._isAnimationPaused) {
  105310. _this._currentAnimation.restart();
  105311. }
  105312. if (paramsObject) {
  105313. paramsObject.selectedSpeed = speed + "x";
  105314. }
  105315. else {
  105316. navbar.updateParams({
  105317. selectedSpeed: speed + "x",
  105318. });
  105319. }
  105320. }
  105321. };
  105322. /**
  105323. * Update Current Animation Type
  105324. */
  105325. _this._updateAnimationType = function (data, paramsObject) {
  105326. var navbar = _this.templateManager.getTemplate('navBar');
  105327. if (!navbar)
  105328. return;
  105329. if (data) {
  105330. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(data.value);
  105331. }
  105332. if (paramsObject) {
  105333. paramsObject.selectedAnimation = (_this._animationList.indexOf(data.value) + 1);
  105334. paramsObject.selectedAnimationName = data.label;
  105335. }
  105336. else {
  105337. navbar.updateParams({
  105338. selectedAnimation: (_this._animationList.indexOf(data.value) + 1),
  105339. selectedAnimationName: data.label
  105340. });
  105341. }
  105342. _this._updateAnimationSpeed("1.0", paramsObject);
  105343. };
  105344. /**
  105345. * Toggle fullscreen of the entire viewer
  105346. */
  105347. _this.toggleFullscreen = function () {
  105348. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  105349. var viewerElement = viewerTemplate && viewerTemplate.parent;
  105350. var fullscreenElement = _this.fullscreenElement || viewerElement;
  105351. if (fullscreenElement) {
  105352. var currentElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  105353. if (!currentElement) {
  105354. var requestFullScreen = fullscreenElement.requestFullscreen || fullscreenElement.webkitRequestFullscreen || fullscreenElement.msRequestFullscreen || fullscreenElement.mozRequestFullScreen;
  105355. requestFullScreen.call(fullscreenElement);
  105356. if (viewerElement) {
  105357. viewerElement.classList.add("in-fullscreen");
  105358. }
  105359. }
  105360. else {
  105361. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  105362. exitFullscreen.call(document);
  105363. if (viewerElement) {
  105364. viewerElement.classList.remove("in-fullscreen");
  105365. }
  105366. }
  105367. }
  105368. };
  105369. _this._onModelLoaded = function (model) {
  105370. _this._configureTemplate(model);
  105371. // with a short timeout, making sure everything is there already.
  105372. var hideLoadingDelay = 20;
  105373. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  105374. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  105375. }
  105376. setTimeout(function () {
  105377. _this.sceneManager.scene.executeWhenReady(function () {
  105378. _this.hideLoadingScreen();
  105379. });
  105380. }, hideLoadingDelay);
  105381. return;
  105382. };
  105383. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  105384. _this.onModelRemovedObservable.add(function () {
  105385. _this._configureTemplate();
  105386. });
  105387. _this.onEngineInitObservable.add(function () {
  105388. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  105389. _this._configureLights();
  105390. });
  105391. });
  105392. _this.onInitDoneObservable.add(function () {
  105393. if (!_this.sceneManager.models.length) {
  105394. _this.hideLoadingScreen();
  105395. }
  105396. });
  105397. return _this;
  105398. }
  105399. DefaultViewer.prototype.registerTemplatePlugin = function (plugin) {
  105400. var _this = this;
  105401. //validate
  105402. if (!plugin.templateName) {
  105403. throw new Error("No template name provided");
  105404. }
  105405. this._registeredPlugins.push(plugin);
  105406. var template = this.templateManager.getTemplate(plugin.templateName);
  105407. if (!template) {
  105408. throw new Error("Template " + plugin.templateName + " not found");
  105409. }
  105410. if (plugin.addHTMLTemplate) {
  105411. template.onHTMLRendered.add(function (tmpl) {
  105412. plugin.addHTMLTemplate(tmpl);
  105413. });
  105414. template.redraw();
  105415. }
  105416. if (plugin.eventsToAttach) {
  105417. plugin.eventsToAttach.forEach(function (eventName) {
  105418. plugin.onEvent && _this.templateManager.eventManager.registerCallback(plugin.templateName, function (event) {
  105419. if (plugin.onEvent && plugin.interactionPredicate(event)) {
  105420. plugin.onEvent(event);
  105421. }
  105422. }, eventName);
  105423. });
  105424. }
  105425. };
  105426. /**
  105427. * This will be executed when the templates initialize.
  105428. */
  105429. DefaultViewer.prototype._onTemplatesLoaded = function () {
  105430. var _this = this;
  105431. this.showLoadingScreen();
  105432. // navbar
  105433. this._initNavbar();
  105434. // close overlay button
  105435. var template = this.templateManager.getTemplate('overlay');
  105436. if (template) {
  105437. var closeButton = template.parent.querySelector('.close-button');
  105438. if (closeButton) {
  105439. closeButton.addEventListener('pointerdown', function () {
  105440. _this.hideOverlayScreen();
  105441. });
  105442. }
  105443. }
  105444. if (this.configuration.templates && this.configuration.templates.viewer) {
  105445. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  105446. this.onSceneInitObservable.addOnce(function () {
  105447. var filesInput = new babylonjs_1.FilesInput(_this.engine, _this.sceneManager.scene, function () {
  105448. }, function () {
  105449. }, function () {
  105450. }, function () {
  105451. }, function () {
  105452. }, function (file) {
  105453. _this.loadModel(file);
  105454. }, function () {
  105455. });
  105456. filesInput.monitorElementForDragNDrop(_this.templateManager.getCanvas());
  105457. });
  105458. }
  105459. }
  105460. return _super.prototype._onTemplatesLoaded.call(this);
  105461. };
  105462. DefaultViewer.prototype._initNavbar = function () {
  105463. var _this = this;
  105464. var navbar = this.templateManager.getTemplate('navBar');
  105465. if (navbar) {
  105466. this.onFrameRenderedObservable.add(this._updateProgressBar);
  105467. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  105468. // an example how to trigger the help button. publiclly available
  105469. this.templateManager.eventManager.registerCallback("navBar", function () {
  105470. // do your thing
  105471. }, "pointerdown", ".help-button");
  105472. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  105473. var evt = event.event;
  105474. var element = (evt.target);
  105475. if (!_this._currentAnimation)
  105476. return;
  105477. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  105478. if (isNaN(gotoFrame))
  105479. return;
  105480. _this._currentAnimation.goToFrame(gotoFrame);
  105481. }, "input");
  105482. this.templateManager.eventManager.registerCallback("navBar", function () {
  105483. if (_this._resumePlay) {
  105484. _this._togglePlayPause(true);
  105485. }
  105486. _this._resumePlay = false;
  105487. }, "pointerup", ".progress-wrapper");
  105488. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  105489. navbar.updateParams({
  105490. hideHdButton: true
  105491. });
  105492. }
  105493. this.registerTemplatePlugin(new hdButtonPlugin_1.HDButtonPlugin(this));
  105494. }
  105495. };
  105496. DefaultViewer.prototype.toggleVR = function () {
  105497. _super.prototype.toggleVR.call(this);
  105498. var viewerTemplate = this.templateManager.getTemplate('viewer');
  105499. var viewerElement = viewerTemplate && viewerTemplate.parent;
  105500. if (viewerElement) {
  105501. if (this._vrToggled) {
  105502. viewerElement.classList.add("in-vr");
  105503. }
  105504. else {
  105505. viewerElement.classList.remove("in-vr");
  105506. }
  105507. }
  105508. };
  105509. /**
  105510. * Preparing the container element to present the viewer
  105511. */
  105512. DefaultViewer.prototype._prepareContainerElement = function () {
  105513. this.containerElement.style.position = 'relative';
  105514. this.containerElement.style.height = '100%';
  105515. this.containerElement.style.display = 'flex';
  105516. };
  105517. /**
  105518. * This function will configure the templates and update them after a model was loaded
  105519. * It is mainly responsible to changing the title and subtitle etc'.
  105520. * @param model the model to be used to configure the templates by
  105521. */
  105522. DefaultViewer.prototype._configureTemplate = function (model) {
  105523. var navbar = this.templateManager.getTemplate('navBar');
  105524. if (!navbar)
  105525. return;
  105526. var newParams = navbar.configuration.params || {};
  105527. if (!model) {
  105528. newParams.animations = null;
  105529. }
  105530. else {
  105531. var animationNames = model.getAnimationNames();
  105532. newParams.animations = animationNames.map(function (a) { return { label: a, value: a }; });
  105533. if (animationNames.length) {
  105534. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  105535. this._animationList = animationNames;
  105536. newParams.paused = this._isAnimationPaused;
  105537. var animationIndex = 0;
  105538. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  105539. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  105540. if (animationIndex === -1) {
  105541. animationIndex = 0;
  105542. }
  105543. }
  105544. this._updateAnimationType(newParams.animations[animationIndex], newParams);
  105545. }
  105546. else {
  105547. newParams.animations = null;
  105548. }
  105549. if (model.configuration.thumbnail) {
  105550. newParams.logoImage = model.configuration.thumbnail;
  105551. }
  105552. }
  105553. navbar.updateParams(newParams, false);
  105554. };
  105555. /**
  105556. * This will load a new model to the default viewer
  105557. * overriding the AbstractViewer's loadModel.
  105558. * The scene will automatically be cleared of the old models, if exist.
  105559. * @param model the configuration object (or URL) to load.
  105560. */
  105561. DefaultViewer.prototype.loadModel = function (model) {
  105562. var _this = this;
  105563. if (!model) {
  105564. model = this.configuration.model;
  105565. }
  105566. this.showLoadingScreen();
  105567. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  105568. console.log(error);
  105569. _this.hideLoadingScreen();
  105570. _this.showOverlayScreen('error');
  105571. return Promise.reject(error);
  105572. });
  105573. };
  105574. /**
  105575. * Show the overlay and the defined sub-screen.
  105576. * Mainly used for help and errors
  105577. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  105578. */
  105579. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  105580. var _this = this;
  105581. var template = this.templateManager.getTemplate('overlay');
  105582. if (!template)
  105583. return Promise.resolve('Overlay template not found');
  105584. return template.show((function (template) {
  105585. var canvasRect = _this.containerElement.getBoundingClientRect();
  105586. template.parent.style.display = 'flex';
  105587. template.parent.style.width = canvasRect.width + "px";
  105588. template.parent.style.height = canvasRect.height + "px";
  105589. template.parent.style.opacity = "1";
  105590. var subTemplate = _this.templateManager.getTemplate(subScreen);
  105591. if (!subTemplate) {
  105592. return Promise.reject(subScreen + ' template not found');
  105593. }
  105594. return subTemplate.show((function (template) {
  105595. template.parent.style.display = 'flex';
  105596. return Promise.resolve(template);
  105597. }));
  105598. }));
  105599. };
  105600. /**
  105601. * Hide the overlay screen.
  105602. */
  105603. DefaultViewer.prototype.hideOverlayScreen = function () {
  105604. var template = this.templateManager.getTemplate('overlay');
  105605. if (!template)
  105606. return Promise.resolve('Overlay template not found');
  105607. return template.hide((function (template) {
  105608. template.parent.style.opacity = "0";
  105609. var onTransitionEnd = function () {
  105610. template.parent.removeEventListener("transitionend", onTransitionEnd);
  105611. template.parent.style.display = 'none';
  105612. };
  105613. template.parent.addEventListener("transitionend", onTransitionEnd);
  105614. var overlays = template.parent.querySelectorAll('.overlay');
  105615. if (overlays) {
  105616. for (var i = 0; i < overlays.length; ++i) {
  105617. var htmlElement = overlays.item(i);
  105618. htmlElement.style.display = 'none';
  105619. }
  105620. }
  105621. return Promise.resolve(template);
  105622. }));
  105623. };
  105624. /**
  105625. * show the viewer (in case it was hidden)
  105626. *
  105627. * @param visibilityFunction an optional function to execute in order to show the container
  105628. */
  105629. DefaultViewer.prototype.show = function (visibilityFunction) {
  105630. var template = this.templateManager.getTemplate('main');
  105631. //not possible, but yet:
  105632. if (!template)
  105633. return Promise.reject('Main template not found');
  105634. return template.show(visibilityFunction);
  105635. };
  105636. /**
  105637. * hide the viewer (in case it is visible)
  105638. *
  105639. * @param visibilityFunction an optional function to execute in order to hide the container
  105640. */
  105641. DefaultViewer.prototype.hide = function (visibilityFunction) {
  105642. var template = this.templateManager.getTemplate('main');
  105643. //not possible, but yet:
  105644. if (!template)
  105645. return Promise.reject('Main template not found');
  105646. return template.hide(visibilityFunction);
  105647. };
  105648. /**
  105649. * Show the loading screen.
  105650. * The loading screen can be configured using the configuration object
  105651. */
  105652. DefaultViewer.prototype.showLoadingScreen = function () {
  105653. var _this = this;
  105654. var template = this.templateManager.getTemplate('loadingScreen');
  105655. if (!template)
  105656. return Promise.resolve('Loading Screen template not found');
  105657. return template.show((function (template) {
  105658. var canvasRect = _this.containerElement.getBoundingClientRect();
  105659. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  105660. template.parent.style.display = 'flex';
  105661. template.parent.style.width = canvasRect.width + "px";
  105662. template.parent.style.height = canvasRect.height + "px";
  105663. template.parent.style.opacity = "1";
  105664. // from the configuration!!!
  105665. var color = "black";
  105666. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  105667. color = (_this.configuration.templates.loadingScreen.params &&
  105668. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  105669. }
  105670. template.parent.style.backgroundColor = color;
  105671. return Promise.resolve(template);
  105672. }));
  105673. };
  105674. /**
  105675. * Hide the loading screen
  105676. */
  105677. DefaultViewer.prototype.hideLoadingScreen = function () {
  105678. var template = this.templateManager.getTemplate('loadingScreen');
  105679. if (!template)
  105680. return Promise.resolve('Loading Screen template not found');
  105681. return template.hide((function (template) {
  105682. template.parent.style.opacity = "0";
  105683. var onTransitionEnd = function () {
  105684. template.parent.removeEventListener("transitionend", onTransitionEnd);
  105685. template.parent.style.display = 'none';
  105686. };
  105687. template.parent.addEventListener("transitionend", onTransitionEnd);
  105688. return Promise.resolve(template);
  105689. }));
  105690. };
  105691. DefaultViewer.prototype.dispose = function () {
  105692. this.templateManager.dispose();
  105693. _super.prototype.dispose.call(this);
  105694. };
  105695. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  105696. var _this = this;
  105697. _super.prototype._onConfigurationLoaded.call(this, configuration);
  105698. // initialize the templates
  105699. var templateConfiguration = this.configuration.templates || {};
  105700. this.templateManager.initTemplate(templateConfiguration);
  105701. // when done, execute onTemplatesLoaded()
  105702. this.templateManager.onAllLoaded.add(function () {
  105703. var canvas = _this.templateManager.getCanvas();
  105704. if (canvas) {
  105705. _this._canvas = canvas;
  105706. }
  105707. _this._onTemplateLoaded();
  105708. });
  105709. };
  105710. /**
  105711. * An extension of the light configuration of the abstract viewer.
  105712. * @param lightsConfiguration the light configuration to use
  105713. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  105714. */
  105715. DefaultViewer.prototype._configureLights = function () {
  105716. var _this = this;
  105717. // labs feature - flashlight
  105718. if (this.configuration.lab && this.configuration.lab.flashlight) {
  105719. var lightTarget_1;
  105720. var angle = 0.5;
  105721. var exponent = Math.PI / 2;
  105722. if (typeof this.configuration.lab.flashlight === "object") {
  105723. exponent = this.configuration.lab.flashlight.exponent || exponent;
  105724. angle = this.configuration.lab.flashlight.angle || angle;
  105725. }
  105726. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  105727. if (typeof this.configuration.lab.flashlight === "object") {
  105728. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  105729. if (this.configuration.lab.flashlight.diffuse) {
  105730. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  105731. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  105732. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  105733. }
  105734. if (this.configuration.lab.flashlight.specular) {
  105735. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  105736. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  105737. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  105738. }
  105739. }
  105740. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  105741. this.sceneManager.scene.onPointerObservable.add(function (eventData) {
  105742. if (eventData.type === 4 && eventData.pickInfo) {
  105743. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  105744. }
  105745. else {
  105746. lightTarget_1 = undefined;
  105747. }
  105748. });
  105749. var updateFlashlightFunction = function () {
  105750. if (_this.sceneManager.camera && flashlight) {
  105751. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  105752. if (lightTarget_1) {
  105753. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  105754. }
  105755. }
  105756. };
  105757. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  105758. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  105759. }
  105760. };
  105761. return DefaultViewer;
  105762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M7cUJBQ3hFO2lCQUNKO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsb0JBQW9CLENBQUMsd0JBQXdCLENBQUMsQ0FBQztZQUN2RSxJQUFJLENBQUMsa0NBQWtDLENBQUMsSUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBN25CRCxDQUFtQyx1QkFBYyxHQTZuQmhEO0FBN25CWSxzQ0FBYSJ9
  105765. /***/ }),
  105766. /* 9 */
  105767. /***/ (function(module, exports, __webpack_require__) {
  105768. "use strict";
  105769. Object.defineProperty(exports, "__esModule", { value: true });
  105770. var babylonjs_1 = __webpack_require__(0);
  105771. var configurationCompatibility_1 = __webpack_require__(10);
  105772. var configurationContainer_1 = __webpack_require__(26);
  105773. var globals_1 = __webpack_require__(4);
  105774. var loader_1 = __webpack_require__(27);
  105775. var _1 = __webpack_require__(1);
  105776. var modelLoader_1 = __webpack_require__(12);
  105777. var observablesManager_1 = __webpack_require__(58);
  105778. var sceneManager_1 = __webpack_require__(59);
  105779. var telemetryManager_1 = __webpack_require__(6);
  105780. var templateManager_1 = __webpack_require__(63);
  105781. var viewerManager_1 = __webpack_require__(7);
  105782. /**
  105783. * The AbstractViewr is the center of Babylon's viewer.
  105784. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  105785. */
  105786. var AbstractViewer = /** @class */ (function () {
  105787. function AbstractViewer(containerElement, initialConfiguration) {
  105788. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  105789. var _this = this;
  105790. this.containerElement = containerElement;
  105791. /**
  105792. * A flag that controls whether or not the render loop should be executed
  105793. */
  105794. this.runRenderLoop = true;
  105795. /**
  105796. * is this viewer disposed?
  105797. */
  105798. this._isDisposed = false;
  105799. this._hdToggled = false;
  105800. this._vrToggled = false;
  105801. this._vrModelRepositioning = 0;
  105802. this._vrScale = 1;
  105803. /**
  105804. * The resize function that will be registered with the window object
  105805. */
  105806. this._resize = function () {
  105807. // Only resize if Canvas is in the DOM
  105808. if (!_this.isCanvasInDOM()) {
  105809. return;
  105810. }
  105811. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  105812. return;
  105813. }
  105814. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  105815. return;
  105816. }
  105817. _this.engine.resize();
  105818. };
  105819. /**
  105820. * render loop that will be executed by the engine
  105821. */
  105822. this._render = function (force) {
  105823. if (force === void 0) { force = false; }
  105824. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  105825. if (_this.runRenderLoop || force) {
  105826. _this.engine.performanceMonitor.enable();
  105827. _this.sceneManager.scene.render();
  105828. _this.onFrameRenderedObservable.notifyObservers(_this);
  105829. }
  105830. else {
  105831. _this.engine.performanceMonitor.disable();
  105832. // update camera instead of rendering
  105833. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  105834. }
  105835. }
  105836. };
  105837. // if exists, use the container id. otherwise, generate a random string.
  105838. if (containerElement.id) {
  105839. this.baseId = containerElement.id;
  105840. }
  105841. else {
  105842. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  105843. }
  105844. this._registeredOnBeforeRenderFunctions = [];
  105845. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  105846. this.observablesManager = new observablesManager_1.ObservablesManager();
  105847. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  105848. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  105849. // extend the configuration
  105850. this._configurationLoader = new loader_1.ConfigurationLoader();
  105851. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  105852. _this._onConfigurationLoaded(configuration);
  105853. });
  105854. this.onSceneInitObservable.add(function () {
  105855. _this.updateConfiguration();
  105856. });
  105857. this.onInitDoneObservable.add(function () {
  105858. _this._isInit = true;
  105859. _this.engine.runRenderLoop(_this._render);
  105860. });
  105861. this._prepareContainerElement();
  105862. // add this viewer to the viewer manager
  105863. viewerManager_1.viewerManager.addViewer(this);
  105864. }
  105865. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  105866. // observables
  105867. /**
  105868. * Will notify when the scene was initialized
  105869. */
  105870. get: function () {
  105871. return this.observablesManager.onSceneInitObservable;
  105872. },
  105873. enumerable: true,
  105874. configurable: true
  105875. });
  105876. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  105877. /**
  105878. * will notify when the engine was initialized
  105879. */
  105880. get: function () {
  105881. return this.observablesManager.onEngineInitObservable;
  105882. },
  105883. enumerable: true,
  105884. configurable: true
  105885. });
  105886. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  105887. /**
  105888. * Will notify when a new model was added to the scene.
  105889. * Note that added does not neccessarily mean loaded!
  105890. */
  105891. get: function () {
  105892. return this.observablesManager.onModelAddedObservable;
  105893. },
  105894. enumerable: true,
  105895. configurable: true
  105896. });
  105897. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  105898. /**
  105899. * will notify after every model load
  105900. */
  105901. get: function () {
  105902. return this.observablesManager.onModelLoadedObservable;
  105903. },
  105904. enumerable: true,
  105905. configurable: true
  105906. });
  105907. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  105908. /**
  105909. * will notify when any model notify of progress
  105910. */
  105911. get: function () {
  105912. return this.observablesManager.onModelLoadProgressObservable;
  105913. },
  105914. enumerable: true,
  105915. configurable: true
  105916. });
  105917. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  105918. /**
  105919. * will notify when any model load failed.
  105920. */
  105921. get: function () {
  105922. return this.observablesManager.onModelLoadErrorObservable;
  105923. },
  105924. enumerable: true,
  105925. configurable: true
  105926. });
  105927. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  105928. /**
  105929. * Will notify when a model was removed from the scene;
  105930. */
  105931. get: function () {
  105932. return this.observablesManager.onModelRemovedObservable;
  105933. },
  105934. enumerable: true,
  105935. configurable: true
  105936. });
  105937. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  105938. /**
  105939. * will notify when a new loader was initialized.
  105940. * Used mainly to know when a model starts loading.
  105941. */
  105942. get: function () {
  105943. return this.observablesManager.onLoaderInitObservable;
  105944. },
  105945. enumerable: true,
  105946. configurable: true
  105947. });
  105948. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  105949. /**
  105950. * Observers registered here will be executed when the entire load process has finished.
  105951. */
  105952. get: function () {
  105953. return this.observablesManager.onViewerInitDoneObservable;
  105954. },
  105955. enumerable: true,
  105956. configurable: true
  105957. });
  105958. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  105959. /**
  105960. * Functions added to this observable will be executed on each frame rendered.
  105961. */
  105962. get: function () {
  105963. return this.observablesManager.onFrameRenderedObservable;
  105964. },
  105965. enumerable: true,
  105966. configurable: true
  105967. });
  105968. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  105969. /**
  105970. * The (single) canvas of this viewer
  105971. */
  105972. get: function () {
  105973. return this._canvas;
  105974. },
  105975. enumerable: true,
  105976. configurable: true
  105977. });
  105978. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  105979. get: function () {
  105980. return this._configurationContainer;
  105981. },
  105982. enumerable: true,
  105983. configurable: true
  105984. });
  105985. /**
  105986. * get the baseId of this viewer
  105987. */
  105988. AbstractViewer.prototype.getBaseId = function () {
  105989. return this.baseId;
  105990. };
  105991. /**
  105992. * Do we have a canvas to render on, and is it a part of the scene
  105993. */
  105994. AbstractViewer.prototype.isCanvasInDOM = function () {
  105995. return !!this._canvas && !!this._canvas.parentElement;
  105996. };
  105997. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  105998. /**
  105999. * Is the engine currently set to rende even when the page is in background
  106000. */
  106001. get: function () {
  106002. return this.engine && this.engine.renderEvenInBackground;
  106003. },
  106004. /**
  106005. * Set the viewer's background rendering flag.
  106006. */
  106007. set: function (value) {
  106008. if (this.engine) {
  106009. this.engine.renderEvenInBackground = value;
  106010. }
  106011. },
  106012. enumerable: true,
  106013. configurable: true
  106014. });
  106015. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  106016. /**
  106017. * Get the configuration object. This is a reference only.
  106018. * The configuration can ONLY be updated using the updateConfiguration function.
  106019. * changing this object will have no direct effect on the scene.
  106020. */
  106021. get: function () {
  106022. return this._configurationContainer.configuration;
  106023. },
  106024. enumerable: true,
  106025. configurable: true
  106026. });
  106027. /**
  106028. * force resizing the engine.
  106029. */
  106030. AbstractViewer.prototype.forceResize = function () {
  106031. this._resize();
  106032. };
  106033. AbstractViewer.prototype.toggleHD = function () {
  106034. this._hdToggled = !this._hdToggled;
  106035. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  106036. this.engine.setHardwareScalingLevel(scale);
  106037. };
  106038. AbstractViewer.prototype.toggleVR = function () {
  106039. this._vrToggled = !this._vrToggled;
  106040. if (this._vrToggled && this.sceneManager.vrHelper) {
  106041. // make sure the floor is set
  106042. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  106043. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  106044. }
  106045. this.sceneManager.vrHelper.enterVR();
  106046. // position the vr camera to be in front of the object or wherever the user has configured it to be
  106047. if (this.sceneManager.vrHelper.currentVRCamera) {
  106048. if (this.configuration.vr && this.configuration.vr.cameraPosition !== undefined) {
  106049. this.sceneManager.vrHelper.currentVRCamera.position.copyFrom(this.configuration.vr.cameraPosition);
  106050. }
  106051. else {
  106052. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  106053. }
  106054. this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion && this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  106055. // set the height of the model to be what the user has configured, or floating by default
  106056. if (this.configuration.vr && this.configuration.vr.modelHeightCorrection !== undefined) {
  106057. if (typeof this.configuration.vr.modelHeightCorrection === 'number') {
  106058. this._vrModelRepositioning = this.configuration.vr.modelHeightCorrection;
  106059. }
  106060. else if (this.configuration.vr.modelHeightCorrection) {
  106061. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  106062. }
  106063. else {
  106064. this._vrModelRepositioning = 0;
  106065. }
  106066. }
  106067. }
  106068. else {
  106069. this._vrModelRepositioning = 0;
  106070. }
  106071. // scale the model
  106072. if (this.sceneManager.models.length) {
  106073. var boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  106074. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  106075. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  106076. this._vrScale = (1 / maxDimension);
  106077. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  106078. this._vrScale *= this.configuration.vr.objectScaleFactor;
  106079. }
  106080. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  106081. // reposition the object to "float" in front of the user
  106082. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  106083. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  106084. }
  106085. // scale the environment to match the model
  106086. if (this.sceneManager.environmentHelper) {
  106087. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  106088. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  106089. }
  106090. // post processing
  106091. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  106092. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  106093. this.sceneManager.defaultRenderingPipeline.prepare();
  106094. }
  106095. }
  106096. else {
  106097. if (this.sceneManager.vrHelper) {
  106098. this.sceneManager.vrHelper.exitVR();
  106099. // undo the scaling of the model
  106100. if (this.sceneManager.models.length) {
  106101. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  106102. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  106103. }
  106104. // undo the scaling of the environment
  106105. if (this.sceneManager.environmentHelper) {
  106106. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  106107. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  106108. }
  106109. // post processing
  106110. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  106111. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  106112. this.sceneManager.defaultRenderingPipeline.prepare();
  106113. }
  106114. }
  106115. }
  106116. };
  106117. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  106118. var _this = this;
  106119. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  106120. if (this.configuration.observers) {
  106121. this._configureObservers(this.configuration.observers);
  106122. }
  106123. // TODO remove this after testing, as this is done in the updateConfiguration as well.
  106124. if (this.configuration.loaderPlugins) {
  106125. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  106126. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  106127. _this.modelLoader.addPlugin(name);
  106128. }
  106129. }));
  106130. }
  106131. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  106132. this.observablesManager.onViewerInitStartedObservable.notifyObservers(this);
  106133. };
  106134. /**
  106135. * Force a single render loop execution.
  106136. */
  106137. AbstractViewer.prototype.forceRender = function () {
  106138. this._render(true);
  106139. };
  106140. /**
  106141. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  106142. * @param callback optional callback that will be triggered when screenshot is done.
  106143. * @param width Optional screenshot width (default to 512).
  106144. * @param height Optional screenshot height (default to 512).
  106145. * @returns a promise with the screenshot data
  106146. */
  106147. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  106148. var _this = this;
  106149. if (width === void 0) { width = 0; }
  106150. if (height === void 0) { height = 0; }
  106151. width = width || this.canvas.clientWidth;
  106152. height = height || this.canvas.clientHeight;
  106153. // Create the screenshot
  106154. return new Promise(function (resolve, reject) {
  106155. try {
  106156. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  106157. if (callback) {
  106158. callback(data);
  106159. }
  106160. resolve(data);
  106161. });
  106162. }
  106163. catch (e) {
  106164. reject(e);
  106165. }
  106166. });
  106167. };
  106168. /**
  106169. * Update the current viewer configuration with new values.
  106170. * Only provided information will be updated, old configuration values will be kept.
  106171. * If this.configuration was manually changed, you can trigger this function with no parameters,
  106172. * and the entire configuration will be updated.
  106173. * @param newConfiguration the partial configuration to update or a URL to a JSON holding the updated configuration
  106174. *
  106175. */
  106176. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  106177. var _this = this;
  106178. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  106179. if (typeof newConfiguration === "string") {
  106180. babylonjs_1.Tools.LoadFile(newConfiguration, function (data) {
  106181. try {
  106182. var newData = JSON.parse(data.toString());
  106183. return _this.updateConfiguration(newData);
  106184. }
  106185. catch (e) {
  106186. console.log("Error parsing file " + newConfiguration);
  106187. }
  106188. }, undefined, undefined, undefined, function (error) {
  106189. console.log("Error parsing file " + newConfiguration, error);
  106190. });
  106191. }
  106192. else {
  106193. //backcompat
  106194. configurationCompatibility_1.processConfigurationCompatibility(newConfiguration);
  106195. // update this.configuration with the new data
  106196. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  106197. this.sceneManager.updateConfiguration(newConfiguration);
  106198. // observers in configuration
  106199. if (newConfiguration.observers) {
  106200. this._configureObservers(newConfiguration.observers);
  106201. }
  106202. if (newConfiguration.loaderPlugins) {
  106203. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  106204. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  106205. _this.modelLoader.addPlugin(name);
  106206. }
  106207. }));
  106208. }
  106209. }
  106210. };
  106211. /**
  106212. * this is used to register native functions using the configuration object.
  106213. * This will configure the observers.
  106214. * @param observersConfiguration observers configuration
  106215. */
  106216. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  106217. if (observersConfiguration.onEngineInit) {
  106218. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  106219. }
  106220. else {
  106221. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  106222. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  106223. }
  106224. }
  106225. if (observersConfiguration.onSceneInit) {
  106226. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  106227. }
  106228. else {
  106229. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  106230. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  106231. }
  106232. }
  106233. if (observersConfiguration.onModelLoaded) {
  106234. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  106235. }
  106236. else {
  106237. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  106238. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  106239. }
  106240. }
  106241. };
  106242. /**
  106243. * Dispoe the entire viewer including the scene and the engine
  106244. */
  106245. AbstractViewer.prototype.dispose = function () {
  106246. if (this._isDisposed) {
  106247. return;
  106248. }
  106249. window.removeEventListener('resize', this._resize);
  106250. if (this.sceneManager) {
  106251. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  106252. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  106253. }
  106254. this.sceneManager.dispose();
  106255. }
  106256. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  106257. this.observablesManager.dispose();
  106258. this.modelLoader.dispose();
  106259. if (this.engine) {
  106260. this.engine.dispose();
  106261. }
  106262. viewerManager_1.viewerManager.removeViewer(this);
  106263. this._isDisposed = true;
  106264. };
  106265. /**
  106266. * This function will execute when the HTML templates finished initializing.
  106267. * It should initialize the engine and continue execution.
  106268. *
  106269. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  106270. */
  106271. AbstractViewer.prototype._onTemplatesLoaded = function () {
  106272. return Promise.resolve(this);
  106273. };
  106274. /**
  106275. * This will force the creation of an engine and a scene.
  106276. * It will also load a model if preconfigured.
  106277. * But first - it will load the extendible onTemplateLoaded()!
  106278. */
  106279. AbstractViewer.prototype._onTemplateLoaded = function () {
  106280. var _this = this;
  106281. // check if viewer was disposed right after created
  106282. if (this._isDisposed) {
  106283. return Promise.reject("viewer was disposed");
  106284. }
  106285. return this._onTemplatesLoaded().then(function () {
  106286. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  106287. return _this._initEngine().then(function (engine) {
  106288. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  106289. }).then(function () {
  106290. _this._initTelemetryEvents();
  106291. if (autoLoad) {
  106292. return _this.loadModel(_this.configuration.model).catch(function () { }).then(function () { return _this.sceneManager.scene; });
  106293. }
  106294. else {
  106295. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  106296. }
  106297. }).then(function () {
  106298. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  106299. }).catch(function (e) {
  106300. babylonjs_1.Tools.Warn(e.toString());
  106301. return _this;
  106302. });
  106303. });
  106304. };
  106305. /**
  106306. * Initialize the engine. Retruns a promise in case async calls are needed.
  106307. *
  106308. * @protected
  106309. * @returns {Promise<Engine>}
  106310. * @memberof Viewer
  106311. */
  106312. AbstractViewer.prototype._initEngine = function () {
  106313. // init custom shaders
  106314. this._injectCustomShaders();
  106315. //let canvasElement = this.templateManager.getCanvas();
  106316. if (!this.canvas) {
  106317. return Promise.reject('Canvas element not found!');
  106318. }
  106319. var config = this.configuration.engine || {};
  106320. // TDO enable further configuration
  106321. // check for webgl2 support, force-disable if needed.
  106322. if (globals_1.viewerGlobals.disableWebGL2Support) {
  106323. config.engineOptions = config.engineOptions || {};
  106324. config.engineOptions.disableWebGL2Support = true;
  106325. }
  106326. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  106327. // Disable manifest checking
  106328. babylonjs_1.Database.IDBStorageEnabled = false;
  106329. if (!config.disableResize) {
  106330. window.addEventListener('resize', this._resize);
  106331. }
  106332. if (this.configuration.engine) {
  106333. if (this.configuration.engine.adaptiveQuality) {
  106334. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  106335. this.engine.setHardwareScalingLevel(scale);
  106336. }
  106337. if (this.configuration.engine.hdEnabled) {
  106338. this.toggleHD();
  106339. }
  106340. }
  106341. // create a new template manager for this viewer
  106342. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  106343. return Promise.resolve(this.engine);
  106344. };
  106345. /**
  106346. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  106347. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  106348. *
  106349. * @param modelConfig model configuration to use when loading the model.
  106350. * @param clearScene should the scene be cleared before loading this model
  106351. * @returns a ViewerModel object that is not yet fully loaded.
  106352. */
  106353. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  106354. var _this = this;
  106355. if (clearScene === void 0) { clearScene = true; }
  106356. var configuration;
  106357. if (typeof modelConfig === 'string') {
  106358. configuration = {
  106359. url: modelConfig
  106360. };
  106361. }
  106362. else if (modelConfig instanceof File) {
  106363. configuration = {
  106364. file: modelConfig,
  106365. root: "file:"
  106366. };
  106367. }
  106368. else {
  106369. configuration = modelConfig;
  106370. }
  106371. if (!configuration.url && !configuration.file) {
  106372. throw new Error("no model provided");
  106373. }
  106374. if (clearScene) {
  106375. this.sceneManager.clearScene(true, false);
  106376. }
  106377. //merge the configuration for future models:
  106378. if (this.configuration.model && typeof this.configuration.model === 'object') {
  106379. var globalConfig = _1.deepmerge({}, this.configuration.model);
  106380. configuration = _1.deepmerge(globalConfig, configuration);
  106381. if (modelConfig instanceof File) {
  106382. configuration.file = modelConfig;
  106383. }
  106384. }
  106385. else {
  106386. this.configuration.model = configuration;
  106387. }
  106388. this._isLoading = true;
  106389. var model = this.modelLoader.load(configuration);
  106390. this.lastUsedLoader = model.loader;
  106391. model.onLoadErrorObservable.add(function (errorObject) {
  106392. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  106393. });
  106394. model.onLoadProgressObservable.add(function (progressEvent) {
  106395. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  106396. });
  106397. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  106398. model.onLoadedObservable.add(function () {
  106399. _this._isLoading = false;
  106400. });
  106401. return model;
  106402. };
  106403. /**
  106404. * load a model using the provided configuration.
  106405. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  106406. * If you want to attach to the observables of the model, use initModle instead.
  106407. *
  106408. * @param modelConfig the model configuration or URL to load.
  106409. * @param clearScene Should the scene be cleared before loading the model
  106410. * @returns a Promise the fulfills when the model finished loading successfully.
  106411. */
  106412. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  106413. var _this = this;
  106414. if (clearScene === void 0) { clearScene = true; }
  106415. if (this._isLoading) {
  106416. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  106417. return Promise.reject("another model is curently being loaded.");
  106418. }
  106419. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  106420. if (!scene)
  106421. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  106422. return scene;
  106423. }).then(function () {
  106424. var model = _this.initModel(modelConfig, clearScene);
  106425. return new Promise(function (resolve, reject) {
  106426. // at this point, configuration.model is an object, not a string
  106427. model.onLoadedObservable.add(function () {
  106428. resolve(model);
  106429. });
  106430. model.onLoadErrorObservable.add(function (error) {
  106431. reject(error);
  106432. });
  106433. });
  106434. });
  106435. };
  106436. AbstractViewer.prototype._initTelemetryEvents = function () {
  106437. var _this = this;
  106438. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  106439. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  106440. userAgent: navigator.userAgent,
  106441. platform: navigator.platform
  106442. });
  106443. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  106444. var trackFPS = function () {
  106445. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  106446. };
  106447. trackFPS();
  106448. // Track the FPS again after 60 seconds
  106449. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  106450. };
  106451. /**
  106452. * Injects all the spectre shader in the babylon shader store
  106453. */
  106454. AbstractViewer.prototype._injectCustomShaders = function () {
  106455. var customShaders = this.configuration.customShaders;
  106456. // Inject all the spectre shader in the babylon shader store.
  106457. if (!customShaders) {
  106458. return;
  106459. }
  106460. if (customShaders.shaders) {
  106461. Object.keys(customShaders.shaders).forEach(function (key) {
  106462. // typescript considers a callback "unsafe", so... '!'
  106463. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  106464. });
  106465. }
  106466. if (customShaders.includes) {
  106467. Object.keys(customShaders.includes).forEach(function (key) {
  106468. // typescript considers a callback "unsafe", so... '!'
  106469. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  106470. });
  106471. }
  106472. };
  106473. return AbstractViewer;
  106474. }());
  106475. exports.AbstractViewer = AbstractViewer;
  106476. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4v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xJQXl2QkM7QUF6dkJxQix3Q0FBYyJ9
  106477. /***/ }),
  106478. /* 10 */
  106479. /***/ (function(module, exports, __webpack_require__) {
  106480. "use strict";
  106481. Object.defineProperty(exports, "__esModule", { value: true });
  106482. var configuration_1 = __webpack_require__(11);
  106483. /**
  106484. * This function will make sure the configuration file is taking deprecated fields into account
  106485. * and is setting them to the correct keys and values.
  106486. *
  106487. * @param configuration The configuration to process. Mutable!
  106488. */
  106489. function processConfigurationCompatibility(configuration) {
  106490. if (configuration.camera) {
  106491. // camera contrast -> image processing contrast
  106492. if (configuration.camera.contrast !== undefined) {
  106493. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  106494. }
  106495. // camera exposure -> image processing exposure
  106496. if (configuration.camera.exposure !== undefined) {
  106497. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  106498. }
  106499. }
  106500. if (configuration.scene) {
  106501. //glow
  106502. if (configuration.scene.glow) {
  106503. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  106504. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  106505. if (enabledProcessing !== false) {
  106506. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  106507. }
  106508. }
  106509. }
  106510. if (configuration.model && typeof configuration.model === 'object') {
  106511. // castShadows === castShadow
  106512. if (configuration.model.castShadows !== undefined && configuration.model.castShadow === undefined) {
  106513. configuration.model.castShadow = configuration.model.castShadows;
  106514. }
  106515. }
  106516. }
  106517. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  106518. function setKeyInObject(object, keys, value, shouldOverwrite) {
  106519. var keySplit = keys.split(".");
  106520. if (keySplit.length === 0)
  106521. return;
  106522. var lastKey = keySplit.pop();
  106523. if (!lastKey)
  106524. return;
  106525. var curObj = object;
  106526. keySplit.forEach(function (key) {
  106527. curObj[key] = curObj[key] || {};
  106528. curObj = curObj[key];
  106529. });
  106530. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  106531. return;
  106532. curObj[lastKey] = value;
  106533. }
  106534. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQUNILDJDQUFrRCxhQUFrQztJQUVoRixJQUFJLGFBQWEsQ0FBQyxNQUFNLEVBQUU7UUFDdEIsK0NBQStDO1FBQy9DLElBQUksYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLEtBQUssU0FBUyxFQUFFO1lBQzdDLGNBQWMsQ0FBQyxhQUFhLEVBQUUsNkNBQTZDLEVBQUUsYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLENBQUMsQ0FBQztTQUMvRztRQUVELCtDQUErQztRQUMvQyxJQUFJLGFBQWEsQ0FBQyxNQUFNLENBQUMsUUFBUSxLQUFLLFNBQVMsRUFBRTtZQUM3QyxjQUFjLENBQUMsYUFBYSxFQUFFLDZDQUE2QyxFQUFFLGFBQWEsQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7U0FDL0c7S0FDSjtJQUVELElBQUksYUFBYSxDQUFDLEtBQUssRUFBRTtRQUNyQixNQUFNO1FBQ04sSUFBSSxhQUFhLENBQUMsS0FBSyxDQUFDLElBQUksRUFBRTtZQUMxQixjQUFjLENBQUMsYUFBYSxFQUFFLGdEQUFnRCxFQUFFLElBQUksQ0FBQyxDQUFDO1lBQ3RGLElBQUksaUJBQWlCLEdBQUcsbUNBQW1CLENBQUMsOENBQThDLEVBQUUsYUFBYSxDQUFDLENBQUM7W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UFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  106535. /***/ }),
  106536. /* 11 */
  106537. /***/ (function(module, exports, __webpack_require__) {
  106538. "use strict";
  106539. Object.defineProperty(exports, "__esModule", { value: true });
  106540. function getConfigurationKey(key, configObject) {
  106541. var splits = key.split('.');
  106542. if (splits.length === 0 || !configObject)
  106543. return;
  106544. else if (splits.length === 1) {
  106545. if (configObject[key] !== undefined) {
  106546. return configObject[key];
  106547. }
  106548. }
  106549. else {
  106550. var firstKey = splits.shift();
  106551. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  106552. }
  106553. }
  106554. exports.getConfigurationKey = getConfigurationKey;
  106555. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  106556. /***/ }),
  106557. /* 12 */
  106558. /***/ (function(module, exports, __webpack_require__) {
  106559. "use strict";
  106560. Object.defineProperty(exports, "__esModule", { value: true });
  106561. var babylonjs_1 = __webpack_require__(0);
  106562. var babylonjs_loaders_1 = __webpack_require__(13);
  106563. var viewerModel_1 = __webpack_require__(5);
  106564. var _1 = __webpack_require__(53);
  106565. /**
  106566. * An instance of the class is in charge of loading the model correctly.
  106567. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  106568. *
  106569. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  106570. */
  106571. var ModelLoader = /** @class */ (function () {
  106572. /**
  106573. * Create a new Model loader
  106574. * @param _viewer the viewer using this model loader
  106575. */
  106576. function ModelLoader(_observablesManager, _configurationContainer) {
  106577. this._observablesManager = _observablesManager;
  106578. this._configurationContainer = _configurationContainer;
  106579. this._disposed = false;
  106580. this._loaders = [];
  106581. this._loadId = 0;
  106582. this._plugins = [];
  106583. }
  106584. Object.defineProperty(ModelLoader.prototype, "baseUrl", {
  106585. get: function () {
  106586. return this._baseUrl;
  106587. },
  106588. enumerable: true,
  106589. configurable: true
  106590. });
  106591. /**
  106592. * Adds a new plugin to the loader process.
  106593. *
  106594. * @param plugin the plugin name or the plugin itself
  106595. */
  106596. ModelLoader.prototype.addPlugin = function (plugin) {
  106597. var actualPlugin = {};
  106598. if (typeof plugin === 'string') {
  106599. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  106600. if (loadedPlugin) {
  106601. actualPlugin = loadedPlugin;
  106602. }
  106603. }
  106604. else {
  106605. actualPlugin = plugin;
  106606. }
  106607. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  106608. this._plugins.push(actualPlugin);
  106609. }
  106610. };
  106611. /**
  106612. * Load a model using predefined configuration
  106613. * @param modelConfiguration the modelConfiguration to use to load the model
  106614. */
  106615. ModelLoader.prototype.load = function (modelConfiguration) {
  106616. var _this = this;
  106617. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  106618. model.loadId = this._loadId++;
  106619. var filename;
  106620. if (modelConfiguration.file) {
  106621. this._baseUrl = "file:";
  106622. filename = modelConfiguration.file;
  106623. }
  106624. else if (modelConfiguration.url) {
  106625. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  106626. this._baseUrl = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  106627. }
  106628. if (!filename || !this._baseUrl) {
  106629. model.state = viewerModel_1.ModelState.ERROR;
  106630. babylonjs_1.Tools.Error("No URL provided");
  106631. return model;
  106632. }
  106633. var plugin = modelConfiguration.loader;
  106634. var scene = model.rootMesh.getScene();
  106635. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, this._baseUrl, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  106636. meshes.forEach(function (mesh) {
  106637. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  106638. model.addMesh(mesh);
  106639. });
  106640. model.particleSystems = particleSystems;
  106641. model.skeletons = skeletons;
  106642. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  106643. var animationGroup = animationGroups_1[_i];
  106644. model.addAnimationGroup(animationGroup);
  106645. }
  106646. _this._checkAndRun("onLoaded", model);
  106647. scene.executeWhenReady(function () {
  106648. model.onLoadedObservable.notifyObservers(model);
  106649. });
  106650. }, function (progressEvent) {
  106651. _this._checkAndRun("onProgress", progressEvent);
  106652. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  106653. }, function (scene, m, exception) {
  106654. model.state = viewerModel_1.ModelState.ERROR;
  106655. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  106656. _this._checkAndRun("onError", m, exception);
  106657. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  106658. }, plugin);
  106659. if (model.loader.name === "gltf") {
  106660. var gltfLoader_1 = model.loader;
  106661. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  106662. gltfLoader_1.compileMaterials = true;
  106663. if (!modelConfiguration.file) {
  106664. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  106665. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  106666. };
  106667. }
  106668. // if ground is set to "mirror":
  106669. if (this._configurationContainer
  106670. && this._configurationContainer.configuration
  106671. && this._configurationContainer.configuration.ground
  106672. && typeof this._configurationContainer.configuration.ground === 'object'
  106673. && this._configurationContainer.configuration.ground.mirror) {
  106674. gltfLoader_1.useClipPlane = true;
  106675. }
  106676. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  106677. gltfLoader_1[functionName].add(function (payload) {
  106678. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  106679. });
  106680. });
  106681. gltfLoader_1.onParsedObservable.add(function (data) {
  106682. if (data && data.json && data.json['asset']) {
  106683. model.loadInfo = data.json['asset'];
  106684. }
  106685. });
  106686. gltfLoader_1.onCompleteObservable.add(function () {
  106687. model.loaderDone = true;
  106688. });
  106689. }
  106690. else {
  106691. model.loaderDone = true;
  106692. }
  106693. this._checkAndRun("onInit", model.loader, model);
  106694. this._loaders.push(model.loader);
  106695. return model;
  106696. };
  106697. ModelLoader.prototype.cancelLoad = function (model) {
  106698. var loader = model.loader || this._loaders[model.loadId];
  106699. // ATM only available in the GLTF Loader
  106700. if (loader && loader.name === "gltf") {
  106701. var gltfLoader = loader;
  106702. gltfLoader.dispose();
  106703. model.state = viewerModel_1.ModelState.CANCELED;
  106704. }
  106705. else {
  106706. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  106707. }
  106708. };
  106709. /**
  106710. * dispose the model loader.
  106711. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  106712. */
  106713. ModelLoader.prototype.dispose = function () {
  106714. this._loaders.forEach(function (loader) {
  106715. if (loader.name === "gltf") {
  106716. loader.dispose();
  106717. }
  106718. });
  106719. this._loaders.length = 0;
  106720. this._disposed = true;
  106721. };
  106722. ModelLoader.prototype._checkAndRun = function (functionName) {
  106723. var _this = this;
  106724. var payload = [];
  106725. for (var _i = 1; _i < arguments.length; _i++) {
  106726. payload[_i - 1] = arguments[_i];
  106727. }
  106728. if (this._disposed)
  106729. return;
  106730. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  106731. try {
  106732. plugin[functionName].apply(_this, payload);
  106733. }
  106734. catch (e) { }
  106735. });
  106736. };
  106737. return ModelLoader;
  106738. }());
  106739. exports.ModelLoader = ModelLoader;
  106740. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUtqRixvREFBK0Q7QUFDL0QsK0JBQWtFO0FBRWxFOzs7OztHQUtHO0FBQ0g7SUFlSTs7O09BR0c7SUFDSCxxQkFBb0IsbUJBQXVDLEVBQVUsdUJBQWdEO1FBQWpHLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBVSw0QkFBdUIsR0FBdkIsdUJBQXVCLENBQXlCO1FBaEI3RyxjQUFTLE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UIsQ0FBQztJQUVPLGtDQUFZLEdBQXBCLFVBQXFCLFlBQW9CO1FBQXpDLGlCQU9DO1FBUDBDLGlCQUFzQjthQUF0QixVQUFzQixFQUF0QixxQkFBc0IsRUFBdEIsSUFBc0I7WUFBdEIsZ0NBQXNCOztRQUM3RCxJQUFJLElBQUksQ0FBQyxTQUFTO1lBQUUsT0FBTztRQUMzQixJQUFJLENBQUMsUUFBUSxDQUFDLE1BQU0sQ0FBQyxVQUFBLENBQUMsSUFBSSxPQUFBLENBQUMsQ0FBQyxZQUFZLENBQUMsRUFBZixDQUFlLENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxNQUFNO1lBQ3JELElBQUk7Z0JBQ0EsTUFBTSxDQUFDLFlBQVksQ0FBQyxDQUFDLEtBQUssQ0FBQyxLQUFJLEVBQUUsT0FBTyxDQUFDLENBQUM7YUFDN0M7WUFBQyxPQUFPLENBQUMsRUFBRSxHQUFHO1FBQ25CLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUNMLGtCQUFDO0FBQUQsQ0FBQyxBQXBMRCxJQW9MQztBQXBMWSxrQ0FBVyJ9
  106741. /***/ }),
  106742. /* 13 */
  106743. /***/ (function(module, exports, __webpack_require__) {
  106744. (function universalModuleDefinition(root, factory) {
  106745. var amdDependencies = [];
  106746. var BABYLON = root.BABYLON || this.BABYLON;
  106747. if(true) {
  106748. BABYLON = BABYLON || __webpack_require__(0);
  106749. module.exports = factory(BABYLON);
  106750. } else if(typeof define === 'function' && define.amd) {
  106751. amdDependencies.push("babylonjs");
  106752. define("babylonjs-loaders", amdDependencies, factory);
  106753. } else if(typeof exports === 'object') {
  106754. BABYLON = BABYLON || require("babylonjs");
  106755. exports["babylonjs-loaders"] = factory(BABYLON);
  106756. } else {
  106757. root["BABYLON"] = factory(BABYLON);
  106758. }
  106759. })(this, function(BABYLON) {
  106760. BABYLON = BABYLON || this.BABYLON;
  106761. 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};
  106762. 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)}}();
  106763. var BABYLON;
  106764. (function (BABYLON) {
  106765. var STLFileLoader = /** @class */ (function () {
  106766. function STLFileLoader() {
  106767. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  106768. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  106769. 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;
  106770. 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;
  106771. this.name = "stl";
  106772. // force data to come in as an ArrayBuffer
  106773. // we'll convert to string if it looks like it's an ASCII .stl
  106774. this.extensions = {
  106775. ".stl": { isBinary: true },
  106776. };
  106777. }
  106778. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  106779. var matches;
  106780. if (typeof data !== "string") {
  106781. if (this.isBinary(data)) {
  106782. // binary .stl
  106783. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  106784. this.parseBinary(babylonMesh, data);
  106785. if (meshes) {
  106786. meshes.push(babylonMesh);
  106787. }
  106788. return true;
  106789. }
  106790. // ASCII .stl
  106791. // convert to string
  106792. var array_buffer = new Uint8Array(data);
  106793. var str = '';
  106794. for (var i = 0; i < data.byteLength; i++) {
  106795. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  106796. }
  106797. data = str;
  106798. }
  106799. //if arrived here, data is a string, containing the STLA data.
  106800. while (matches = this.solidPattern.exec(data)) {
  106801. var meshName = matches[1];
  106802. var meshNameFromEnd = matches[3];
  106803. if (meshName != meshNameFromEnd) {
  106804. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  106805. return false;
  106806. }
  106807. // check meshesNames
  106808. if (meshesNames && meshName) {
  106809. if (meshesNames instanceof Array) {
  106810. if (!meshesNames.indexOf(meshName)) {
  106811. continue;
  106812. }
  106813. }
  106814. else {
  106815. if (meshName !== meshesNames) {
  106816. continue;
  106817. }
  106818. }
  106819. }
  106820. // stl mesh name can be empty as well
  106821. meshName = meshName || "stlmesh";
  106822. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  106823. this.parseASCII(babylonMesh, matches[2]);
  106824. if (meshes) {
  106825. meshes.push(babylonMesh);
  106826. }
  106827. }
  106828. return true;
  106829. };
  106830. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  106831. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  106832. if (result) {
  106833. scene.createDefaultCameraOrLight();
  106834. }
  106835. return result;
  106836. };
  106837. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  106838. var container = new BABYLON.AssetContainer(scene);
  106839. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  106840. container.removeAllFromScene();
  106841. return container;
  106842. };
  106843. STLFileLoader.prototype.isBinary = function (data) {
  106844. // check if file size is correct for binary stl
  106845. var faceSize, nFaces, reader;
  106846. reader = new DataView(data);
  106847. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  106848. nFaces = reader.getUint32(80, true);
  106849. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  106850. return true;
  106851. }
  106852. // check characters higher than ASCII to confirm binary
  106853. var fileLength = reader.byteLength;
  106854. for (var index = 0; index < fileLength; index++) {
  106855. if (reader.getUint8(index) > 127) {
  106856. return true;
  106857. }
  106858. }
  106859. return false;
  106860. };
  106861. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  106862. var reader = new DataView(data);
  106863. var faces = reader.getUint32(80, true);
  106864. var dataOffset = 84;
  106865. var faceLength = 12 * 4 + 2;
  106866. var offset = 0;
  106867. var positions = new Float32Array(faces * 3 * 3);
  106868. var normals = new Float32Array(faces * 3 * 3);
  106869. var indices = new Uint32Array(faces * 3);
  106870. var indicesCount = 0;
  106871. for (var face = 0; face < faces; face++) {
  106872. var start = dataOffset + face * faceLength;
  106873. var normalX = reader.getFloat32(start, true);
  106874. var normalY = reader.getFloat32(start + 4, true);
  106875. var normalZ = reader.getFloat32(start + 8, true);
  106876. for (var i = 1; i <= 3; i++) {
  106877. var vertexstart = start + i * 12;
  106878. // ordering is intentional to match ascii import
  106879. positions[offset] = reader.getFloat32(vertexstart, true);
  106880. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  106881. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  106882. normals[offset] = normalX;
  106883. normals[offset + 2] = normalY;
  106884. normals[offset + 1] = normalZ;
  106885. offset += 3;
  106886. }
  106887. indices[indicesCount] = indicesCount++;
  106888. indices[indicesCount] = indicesCount++;
  106889. indices[indicesCount] = indicesCount++;
  106890. }
  106891. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106892. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106893. mesh.setIndices(indices);
  106894. mesh.computeWorldMatrix(true);
  106895. };
  106896. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  106897. var positions = [];
  106898. var normals = [];
  106899. var indices = [];
  106900. var indicesCount = 0;
  106901. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  106902. var matches;
  106903. while (matches = this.facetsPattern.exec(solidData)) {
  106904. var facet = matches[1];
  106905. //one normal per face
  106906. var normalMatches = this.normalPattern.exec(facet);
  106907. this.normalPattern.lastIndex = 0;
  106908. if (!normalMatches) {
  106909. continue;
  106910. }
  106911. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  106912. var vertexMatch;
  106913. while (vertexMatch = this.vertexPattern.exec(facet)) {
  106914. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  106915. normals.push(normal[0], normal[1], normal[2]);
  106916. }
  106917. indices.push(indicesCount++, indicesCount++, indicesCount++);
  106918. this.vertexPattern.lastIndex = 0;
  106919. }
  106920. this.facetsPattern.lastIndex = 0;
  106921. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106922. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106923. mesh.setIndices(indices);
  106924. mesh.computeWorldMatrix(true);
  106925. };
  106926. return STLFileLoader;
  106927. }());
  106928. BABYLON.STLFileLoader = STLFileLoader;
  106929. if (BABYLON.SceneLoader) {
  106930. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  106931. }
  106932. })(BABYLON || (BABYLON = {}));
  106933. //# sourceMappingURL=babylon.stlFileLoader.js.map
  106934. var BABYLON;
  106935. (function (BABYLON) {
  106936. /**
  106937. * Class reading and parsing the MTL file bundled with the obj file.
  106938. */
  106939. var MTLFileLoader = /** @class */ (function () {
  106940. function MTLFileLoader() {
  106941. // All material loaded from the mtl will be set here
  106942. this.materials = [];
  106943. }
  106944. /**
  106945. * This function will read the mtl file and create each material described inside
  106946. * This function could be improve by adding :
  106947. * -some component missing (Ni, Tf...)
  106948. * -including the specific options available
  106949. *
  106950. * @param scene
  106951. * @param data
  106952. * @param rootUrl
  106953. */
  106954. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  106955. if (data instanceof ArrayBuffer) {
  106956. return;
  106957. }
  106958. //Split the lines from the file
  106959. var lines = data.split('\n');
  106960. //Space char
  106961. var delimiter_pattern = /\s+/;
  106962. //Array with RGB colors
  106963. var color;
  106964. //New material
  106965. var material = null;
  106966. //Look at each line
  106967. for (var i = 0; i < lines.length; i++) {
  106968. var line = lines[i].trim();
  106969. // Blank line or comment
  106970. if (line.length === 0 || line.charAt(0) === '#') {
  106971. continue;
  106972. }
  106973. //Get the first parameter (keyword)
  106974. var pos = line.indexOf(' ');
  106975. var key = (pos >= 0) ? line.substring(0, pos) : line;
  106976. key = key.toLowerCase();
  106977. //Get the data following the key
  106978. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  106979. //This mtl keyword will create the new material
  106980. if (key === "newmtl") {
  106981. //Check if it is the first material.
  106982. // Materials specifications are described after this keyword.
  106983. if (material) {
  106984. //Add the previous material in the material array.
  106985. this.materials.push(material);
  106986. }
  106987. //Create a new material.
  106988. // value is the name of the material read in the mtl file
  106989. material = new BABYLON.StandardMaterial(value, scene);
  106990. }
  106991. else if (key === "kd" && material) {
  106992. // Diffuse color (color under white light) using RGB values
  106993. //value = "r g b"
  106994. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106995. //color = [r,g,b]
  106996. //Set tghe color into the material
  106997. material.diffuseColor = BABYLON.Color3.FromArray(color);
  106998. }
  106999. else if (key === "ka" && material) {
  107000. // Ambient color (color under shadow) using RGB values
  107001. //value = "r g b"
  107002. color = value.split(delimiter_pattern, 3).map(parseFloat);
  107003. //color = [r,g,b]
  107004. //Set tghe color into the material
  107005. material.ambientColor = BABYLON.Color3.FromArray(color);
  107006. }
  107007. else if (key === "ks" && material) {
  107008. // Specular color (color when light is reflected from shiny surface) using RGB values
  107009. //value = "r g b"
  107010. color = value.split(delimiter_pattern, 3).map(parseFloat);
  107011. //color = [r,g,b]
  107012. //Set the color into the material
  107013. material.specularColor = BABYLON.Color3.FromArray(color);
  107014. }
  107015. else if (key === "ke" && material) {
  107016. // Emissive color using RGB values
  107017. color = value.split(delimiter_pattern, 3).map(parseFloat);
  107018. material.emissiveColor = BABYLON.Color3.FromArray(color);
  107019. }
  107020. else if (key === "ns" && material) {
  107021. //value = "Integer"
  107022. material.specularPower = parseFloat(value);
  107023. }
  107024. else if (key === "d" && material) {
  107025. //d is dissolve for current material. It mean alpha for BABYLON
  107026. material.alpha = parseFloat(value);
  107027. //Texture
  107028. //This part can be improved by adding the possible options of texture
  107029. }
  107030. else if (key === "map_ka" && material) {
  107031. // ambient texture map with a loaded image
  107032. //We must first get the folder of the image
  107033. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  107034. }
  107035. else if (key === "map_kd" && material) {
  107036. // Diffuse texture map with a loaded image
  107037. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  107038. }
  107039. else if (key === "map_ks" && material) {
  107040. // Specular texture map with a loaded image
  107041. //We must first get the folder of the image
  107042. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  107043. }
  107044. else if (key === "map_ns") {
  107045. //Specular
  107046. //Specular highlight component
  107047. //We must first get the folder of the image
  107048. //
  107049. //Not supported by BABYLON
  107050. //
  107051. // continue;
  107052. }
  107053. else if (key === "map_bump" && material) {
  107054. //The bump texture
  107055. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  107056. }
  107057. else if (key === "map_d" && material) {
  107058. // The dissolve of the material
  107059. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  107060. //Options for illumination
  107061. }
  107062. else if (key === "illum") {
  107063. //Illumination
  107064. if (value === "0") {
  107065. //That mean Kd == Kd
  107066. }
  107067. else if (value === "1") {
  107068. //Color on and Ambient on
  107069. }
  107070. else if (value === "2") {
  107071. //Highlight on
  107072. }
  107073. else if (value === "3") {
  107074. //Reflection on and Ray trace on
  107075. }
  107076. else if (value === "4") {
  107077. //Transparency: Glass on, Reflection: Ray trace on
  107078. }
  107079. else if (value === "5") {
  107080. //Reflection: Fresnel on and Ray trace on
  107081. }
  107082. else if (value === "6") {
  107083. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  107084. }
  107085. else if (value === "7") {
  107086. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  107087. }
  107088. else if (value === "8") {
  107089. //Reflection on and Ray trace off
  107090. }
  107091. else if (value === "9") {
  107092. //Transparency: Glass on, Reflection: Ray trace off
  107093. }
  107094. else if (value === "10") {
  107095. //Casts shadows onto invisible surfaces
  107096. }
  107097. }
  107098. else {
  107099. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  107100. }
  107101. }
  107102. //At the end of the file, add the last material
  107103. if (material) {
  107104. this.materials.push(material);
  107105. }
  107106. };
  107107. /**
  107108. * Gets the texture for the material.
  107109. *
  107110. * If the material is imported from input file,
  107111. * We sanitize the url to ensure it takes the textre from aside the material.
  107112. *
  107113. * @param rootUrl The root url to load from
  107114. * @param value The value stored in the mtl
  107115. * @return The Texture
  107116. */
  107117. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  107118. if (!value) {
  107119. return null;
  107120. }
  107121. var url = rootUrl;
  107122. // Load from input file.
  107123. if (rootUrl === "file:") {
  107124. var lastDelimiter = value.lastIndexOf("\\");
  107125. if (lastDelimiter === -1) {
  107126. lastDelimiter = value.lastIndexOf("/");
  107127. }
  107128. if (lastDelimiter > -1) {
  107129. url += value.substr(lastDelimiter + 1);
  107130. }
  107131. else {
  107132. url += value;
  107133. }
  107134. }
  107135. // Not from input file.
  107136. else {
  107137. url += value;
  107138. }
  107139. return new BABYLON.Texture(url, scene);
  107140. };
  107141. return MTLFileLoader;
  107142. }());
  107143. BABYLON.MTLFileLoader = MTLFileLoader;
  107144. var OBJFileLoader = /** @class */ (function () {
  107145. function OBJFileLoader() {
  107146. this.name = "obj";
  107147. this.extensions = ".obj";
  107148. this.obj = /^o/;
  107149. this.group = /^g/;
  107150. this.mtllib = /^mtllib /;
  107151. this.usemtl = /^usemtl /;
  107152. this.smooth = /^s /;
  107153. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  107154. // vn float float float
  107155. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  107156. // vt float float
  107157. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  107158. // f vertex vertex vertex ...
  107159. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  107160. // f vertex/uvs vertex/uvs vertex/uvs ...
  107161. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  107162. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  107163. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  107164. // f vertex//normal vertex//normal vertex//normal ...
  107165. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  107166. }
  107167. /**
  107168. * Calls synchronously the MTL file attached to this obj.
  107169. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  107170. * Without this function materials are not displayed in the first frame (but displayed after).
  107171. * In consequence it is impossible to get material information in your HTML file
  107172. *
  107173. * @param url The URL of the MTL file
  107174. * @param rootUrl
  107175. * @param onSuccess Callback function to be called when the MTL file is loaded
  107176. * @private
  107177. */
  107178. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  107179. //The complete path to the mtl file
  107180. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  107181. // Loads through the babylon tools to allow fileInput search.
  107182. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  107183. };
  107184. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107185. //get the meshes from OBJ file
  107186. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  107187. return {
  107188. meshes: meshes,
  107189. particleSystems: [],
  107190. skeletons: [],
  107191. animationGroups: []
  107192. };
  107193. });
  107194. };
  107195. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107196. //Get the 3D model
  107197. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  107198. // return void
  107199. });
  107200. };
  107201. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  107202. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  107203. var container = new BABYLON.AssetContainer(scene);
  107204. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  107205. container.removeAllFromScene();
  107206. return container;
  107207. });
  107208. };
  107209. /**
  107210. * Read the OBJ file and create an Array of meshes.
  107211. * Each mesh contains all information given by the OBJ and the MTL file.
  107212. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  107213. *
  107214. * @param meshesNames
  107215. * @param scene BABYLON.Scene The scene where are displayed the data
  107216. * @param data String The content of the obj file
  107217. * @param rootUrl String The path to the folder
  107218. * @returns Array<AbstractMesh>
  107219. * @private
  107220. */
  107221. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  107222. var _this = this;
  107223. var positions = []; //values for the positions of vertices
  107224. var normals = []; //Values for the normals
  107225. var uvs = []; //Values for the textures
  107226. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  107227. var handledMesh; //The current mesh of meshes array
  107228. var indicesForBabylon = []; //The list of indices for VertexData
  107229. var wrappedPositionForBabylon = []; //The list of position in vectors
  107230. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  107231. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  107232. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  107233. var curPositionInIndices = 0;
  107234. var hasMeshes = false; //Meshes are defined in the file
  107235. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  107236. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  107237. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  107238. var triangles = []; //Indices from new triangles coming from polygons
  107239. var materialNameFromObj = ""; //The name of the current material
  107240. var fileToLoad = ""; //The name of the mtlFile to load
  107241. var materialsFromMTLFile = new MTLFileLoader();
  107242. var objMeshName = ""; //The name of the current obj mesh
  107243. var increment = 1; //Id for meshes created by the multimaterial
  107244. var isFirstMaterial = true;
  107245. /**
  107246. * Search for obj in the given array.
  107247. * This function is called to check if a couple of data already exists in an array.
  107248. *
  107249. * If found, returns the index of the founded tuple index. Returns -1 if not found
  107250. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  107251. * @param obj Array<number>
  107252. * @returns {boolean}
  107253. */
  107254. var isInArray = function (arr, obj) {
  107255. if (!arr[obj[0]])
  107256. arr[obj[0]] = { normals: [], idx: [] };
  107257. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  107258. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  107259. };
  107260. var isInArrayUV = function (arr, obj) {
  107261. if (!arr[obj[0]])
  107262. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  107263. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  107264. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  107265. return arr[obj[0]].idx[idx];
  107266. }
  107267. return -1;
  107268. };
  107269. /**
  107270. * This function set the data for each triangle.
  107271. * Data are position, normals and uvs
  107272. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  107273. * If the tuple already exist, add only their indice
  107274. *
  107275. * @param indicePositionFromObj Integer The index in positions array
  107276. * @param indiceUvsFromObj Integer The index in uvs array
  107277. * @param indiceNormalFromObj Integer The index in normals array
  107278. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  107279. * @param textureVectorFromOBJ Vector3 The value of uvs
  107280. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  107281. */
  107282. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  107283. //Check if this tuple already exists in the list of tuples
  107284. var _index;
  107285. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  107286. _index = isInArrayUV(tuplePosNorm, [
  107287. indicePositionFromObj,
  107288. indiceNormalFromObj,
  107289. indiceUvsFromObj
  107290. ]);
  107291. }
  107292. else {
  107293. _index = isInArray(tuplePosNorm, [
  107294. indicePositionFromObj,
  107295. indiceNormalFromObj
  107296. ]);
  107297. }
  107298. //If it not exists
  107299. if (_index == -1) {
  107300. //Add an new indice.
  107301. //The array of indices is only an array with his length equal to the number of triangles - 1.
  107302. //We add vertices data in this order
  107303. indicesForBabylon.push(wrappedPositionForBabylon.length);
  107304. //Push the position of vertice for Babylon
  107305. //Each element is a BABYLON.Vector3(x,y,z)
  107306. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  107307. //Push the uvs for Babylon
  107308. //Each element is a BABYLON.Vector3(u,v)
  107309. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  107310. //Push the normals for Babylon
  107311. //Each element is a BABYLON.Vector3(x,y,z)
  107312. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  107313. //Add the tuple in the comparison list
  107314. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  107315. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  107316. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  107317. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  107318. }
  107319. else {
  107320. //The tuple already exists
  107321. //Add the index of the already existing tuple
  107322. //At this index we can get the value of position, normal and uvs of vertex
  107323. indicesForBabylon.push(_index);
  107324. }
  107325. };
  107326. /**
  107327. * Transform BABYLON.Vector() object onto 3 digits in an array
  107328. */
  107329. var unwrapData = function () {
  107330. //Every array has the same length
  107331. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  107332. //Push the x, y, z values of each element in the unwrapped array
  107333. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  107334. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  107335. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  107336. }
  107337. // Reset arrays for the next new meshes
  107338. wrappedPositionForBabylon = [];
  107339. wrappedNormalsForBabylon = [];
  107340. wrappedUvsForBabylon = [];
  107341. tuplePosNorm = [];
  107342. curPositionInIndices = 0;
  107343. };
  107344. /**
  107345. * Create triangles from polygons by recursion
  107346. * The best to understand how it works is to draw it in the same time you get the recursion.
  107347. * It is important to notice that a triangle is a polygon
  107348. * We get 4 patterns of face defined in OBJ File :
  107349. * facePattern1 = ["1","2","3","4","5","6"]
  107350. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  107351. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  107352. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  107353. * Each pattern is divided by the same method
  107354. * @param face Array[String] The indices of elements
  107355. * @param v Integer The variable to increment
  107356. */
  107357. var getTriangles = function (face, v) {
  107358. //Work for each element of the array
  107359. if (v + 1 < face.length) {
  107360. //Add on the triangle variable the indexes to obtain triangles
  107361. triangles.push(face[0], face[v], face[v + 1]);
  107362. //Incrementation for recursion
  107363. v += 1;
  107364. //Recursion
  107365. getTriangles(face, v);
  107366. }
  107367. //Result obtained after 2 iterations:
  107368. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  107369. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  107370. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  107371. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  107372. };
  107373. /**
  107374. * Create triangles and push the data for each polygon for the pattern 1
  107375. * In this pattern we get vertice positions
  107376. * @param face
  107377. * @param v
  107378. */
  107379. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  107380. //Get the indices of triangles for each polygon
  107381. getTriangles(face, v);
  107382. //For each element in the triangles array.
  107383. //This var could contains 1 to an infinity of triangles
  107384. for (var k = 0; k < triangles.length; k++) {
  107385. // Set position indice
  107386. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  107387. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  107388. positions[indicePositionFromObj], //Get the vectors data
  107389. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  107390. );
  107391. }
  107392. //Reset variable for the next line
  107393. triangles = [];
  107394. };
  107395. /**
  107396. * Create triangles and push the data for each polygon for the pattern 2
  107397. * In this pattern we get vertice positions and uvsu
  107398. * @param face
  107399. * @param v
  107400. */
  107401. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  107402. //Get the indices of triangles for each polygon
  107403. getTriangles(face, v);
  107404. for (var k = 0; k < triangles.length; k++) {
  107405. //triangle[k] = "1/1"
  107406. //Split the data for getting position and uv
  107407. var point = triangles[k].split("/"); // ["1", "1"]
  107408. //Set position indice
  107409. var indicePositionFromObj = parseInt(point[0]) - 1;
  107410. //Set uv indice
  107411. var indiceUvsFromObj = parseInt(point[1]) - 1;
  107412. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  107413. positions[indicePositionFromObj], //Get the values for each element
  107414. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  107415. );
  107416. }
  107417. //Reset variable for the next line
  107418. triangles = [];
  107419. };
  107420. /**
  107421. * Create triangles and push the data for each polygon for the pattern 3
  107422. * In this pattern we get vertice positions, uvs and normals
  107423. * @param face
  107424. * @param v
  107425. */
  107426. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  107427. //Get the indices of triangles for each polygon
  107428. getTriangles(face, v);
  107429. for (var k = 0; k < triangles.length; k++) {
  107430. //triangle[k] = "1/1/1"
  107431. //Split the data for getting position, uv, and normals
  107432. var point = triangles[k].split("/"); // ["1", "1", "1"]
  107433. // Set position indice
  107434. var indicePositionFromObj = parseInt(point[0]) - 1;
  107435. // Set uv indice
  107436. var indiceUvsFromObj = parseInt(point[1]) - 1;
  107437. // Set normal indice
  107438. var indiceNormalFromObj = parseInt(point[2]) - 1;
  107439. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  107440. );
  107441. }
  107442. //Reset variable for the next line
  107443. triangles = [];
  107444. };
  107445. /**
  107446. * Create triangles and push the data for each polygon for the pattern 4
  107447. * In this pattern we get vertice positions and normals
  107448. * @param face
  107449. * @param v
  107450. */
  107451. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  107452. getTriangles(face, v);
  107453. for (var k = 0; k < triangles.length; k++) {
  107454. //triangle[k] = "1//1"
  107455. //Split the data for getting position and normals
  107456. var point = triangles[k].split("//"); // ["1", "1"]
  107457. // We check indices, and normals
  107458. var indicePositionFromObj = parseInt(point[0]) - 1;
  107459. var indiceNormalFromObj = parseInt(point[1]) - 1;
  107460. setData(indicePositionFromObj, 1, //Default value for uv
  107461. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  107462. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  107463. }
  107464. //Reset variable for the next line
  107465. triangles = [];
  107466. };
  107467. var addPreviousObjMesh = function () {
  107468. //Check if it is not the first mesh. Otherwise we don't have data.
  107469. if (meshesFromObj.length > 0) {
  107470. //Get the previous mesh for applying the data about the faces
  107471. //=> in obj file, faces definition append after the name of the mesh
  107472. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  107473. //Set the data into Array for the mesh
  107474. unwrapData();
  107475. // Reverse tab. Otherwise face are displayed in the wrong sens
  107476. indicesForBabylon.reverse();
  107477. //Set the information for the mesh
  107478. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  107479. handledMesh.indices = indicesForBabylon.slice();
  107480. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  107481. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  107482. handledMesh.uvs = unwrappedUVForBabylon.slice();
  107483. //Reset the array for the next mesh
  107484. indicesForBabylon = [];
  107485. unwrappedPositionsForBabylon = [];
  107486. unwrappedNormalsForBabylon = [];
  107487. unwrappedUVForBabylon = [];
  107488. }
  107489. };
  107490. //Main function
  107491. //Split the file into lines
  107492. var lines = data.split('\n');
  107493. //Look at each line
  107494. for (var i = 0; i < lines.length; i++) {
  107495. var line = lines[i].trim();
  107496. var result;
  107497. //Comment or newLine
  107498. if (line.length === 0 || line.charAt(0) === '#') {
  107499. continue;
  107500. //Get information about one position possible for the vertices
  107501. }
  107502. else if ((result = this.vertexPattern.exec(line)) !== null) {
  107503. //Create a Vector3 with the position x, y, z
  107504. //Value of result:
  107505. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  107506. //Add the Vector in the list of positions
  107507. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  107508. }
  107509. else if ((result = this.normalPattern.exec(line)) !== null) {
  107510. //Create a Vector3 with the normals x, y, z
  107511. //Value of result
  107512. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  107513. //Add the Vector in the list of normals
  107514. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  107515. }
  107516. else if ((result = this.uvPattern.exec(line)) !== null) {
  107517. //Create a Vector2 with the normals u, v
  107518. //Value of result
  107519. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  107520. //Add the Vector in the list of uvs
  107521. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  107522. //Identify patterns of faces
  107523. //Face could be defined in different type of pattern
  107524. }
  107525. else if ((result = this.facePattern3.exec(line)) !== null) {
  107526. //Value of result:
  107527. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  107528. //Set the data for this face
  107529. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  107530. 1);
  107531. }
  107532. else if ((result = this.facePattern4.exec(line)) !== null) {
  107533. //Value of result:
  107534. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  107535. //Set the data for this face
  107536. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  107537. 1);
  107538. }
  107539. else if ((result = this.facePattern2.exec(line)) !== null) {
  107540. //Value of result:
  107541. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  107542. //Set the data for this face
  107543. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  107544. 1);
  107545. }
  107546. else if ((result = this.facePattern1.exec(line)) !== null) {
  107547. //Value of result
  107548. //["f 1 2 3", "1 2 3"...]
  107549. //Set the data for this face
  107550. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  107551. 1);
  107552. //Define a mesh or an object
  107553. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  107554. }
  107555. else if (this.group.test(line) || this.obj.test(line)) {
  107556. //Create a new mesh corresponding to the name of the group.
  107557. //Definition of the mesh
  107558. var objMesh =
  107559. //Set the name of the current obj mesh
  107560. {
  107561. name: line.substring(2).trim(),
  107562. indices: undefined,
  107563. positions: undefined,
  107564. normals: undefined,
  107565. uvs: undefined,
  107566. materialName: ""
  107567. };
  107568. addPreviousObjMesh();
  107569. //Push the last mesh created with only the name
  107570. meshesFromObj.push(objMesh);
  107571. //Set this variable to indicate that now meshesFromObj has objects defined inside
  107572. hasMeshes = true;
  107573. isFirstMaterial = true;
  107574. increment = 1;
  107575. //Keyword for applying a material
  107576. }
  107577. else if (this.usemtl.test(line)) {
  107578. //Get the name of the material
  107579. materialNameFromObj = line.substring(7).trim();
  107580. //If this new material is in the same mesh
  107581. if (!isFirstMaterial) {
  107582. //Set the data for the previous mesh
  107583. addPreviousObjMesh();
  107584. //Create a new mesh
  107585. var objMesh =
  107586. //Set the name of the current obj mesh
  107587. {
  107588. name: objMeshName + "_mm" + increment.toString(),
  107589. indices: undefined,
  107590. positions: undefined,
  107591. normals: undefined,
  107592. uvs: undefined,
  107593. materialName: materialNameFromObj
  107594. };
  107595. increment++;
  107596. //If meshes are already defined
  107597. meshesFromObj.push(objMesh);
  107598. }
  107599. //Set the material name if the previous line define a mesh
  107600. if (hasMeshes && isFirstMaterial) {
  107601. //Set the material name to the previous mesh (1 material per mesh)
  107602. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  107603. isFirstMaterial = false;
  107604. }
  107605. //Keyword for loading the mtl file
  107606. }
  107607. else if (this.mtllib.test(line)) {
  107608. //Get the name of mtl file
  107609. fileToLoad = line.substring(7).trim();
  107610. //Apply smoothing
  107611. }
  107612. else if (this.smooth.test(line)) {
  107613. // smooth shading => apply smoothing
  107614. //Toda y I don't know it work with babylon and with obj.
  107615. //With the obj file an integer is set
  107616. }
  107617. else {
  107618. //If there is another possibility
  107619. console.log("Unhandled expression at line : " + line);
  107620. }
  107621. }
  107622. //At the end of the file, add the last mesh into the meshesFromObj array
  107623. if (hasMeshes) {
  107624. //Set the data for the last mesh
  107625. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  107626. //Reverse indices for displaying faces in the good sens
  107627. indicesForBabylon.reverse();
  107628. //Get the good array
  107629. unwrapData();
  107630. //Set array
  107631. handledMesh.indices = indicesForBabylon;
  107632. handledMesh.positions = unwrappedPositionsForBabylon;
  107633. handledMesh.normals = unwrappedNormalsForBabylon;
  107634. handledMesh.uvs = unwrappedUVForBabylon;
  107635. }
  107636. //If any o or g keyword found, create a mesj with a random id
  107637. if (!hasMeshes) {
  107638. // reverse tab of indices
  107639. indicesForBabylon.reverse();
  107640. //Get positions normals uvs
  107641. unwrapData();
  107642. //Set data for one mesh
  107643. meshesFromObj.push({
  107644. name: BABYLON.Geometry.RandomId(),
  107645. indices: indicesForBabylon,
  107646. positions: unwrappedPositionsForBabylon,
  107647. normals: unwrappedNormalsForBabylon,
  107648. uvs: unwrappedUVForBabylon,
  107649. materialName: materialNameFromObj
  107650. });
  107651. }
  107652. //Create a BABYLON.Mesh list
  107653. var babylonMeshesArray = []; //The mesh for babylon
  107654. var materialToUse = new Array();
  107655. //Set data for each mesh
  107656. for (var j = 0; j < meshesFromObj.length; j++) {
  107657. //check meshesNames (stlFileLoader)
  107658. if (meshesNames && meshesFromObj[j].name) {
  107659. if (meshesNames instanceof Array) {
  107660. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  107661. continue;
  107662. }
  107663. }
  107664. else {
  107665. if (meshesFromObj[j].name !== meshesNames) {
  107666. continue;
  107667. }
  107668. }
  107669. }
  107670. //Get the current mesh
  107671. //Set the data with VertexBuffer for each mesh
  107672. handledMesh = meshesFromObj[j];
  107673. //Create a BABYLON.Mesh with the name of the obj mesh
  107674. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  107675. //Push the name of the material to an array
  107676. //This is indispensable for the importMesh function
  107677. materialToUse.push(meshesFromObj[j].materialName);
  107678. var vertexData = new BABYLON.VertexData(); //The container for the values
  107679. //Set the data for the babylonMesh
  107680. vertexData.positions = handledMesh.positions;
  107681. vertexData.normals = handledMesh.normals;
  107682. vertexData.uvs = handledMesh.uvs;
  107683. vertexData.indices = handledMesh.indices;
  107684. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  107685. vertexData.applyToMesh(babylonMesh);
  107686. if (OBJFileLoader.INVERT_Y) {
  107687. babylonMesh.scaling.y *= -1;
  107688. }
  107689. //Push the mesh into an array
  107690. babylonMeshesArray.push(babylonMesh);
  107691. }
  107692. var mtlPromises = [];
  107693. //load the materials
  107694. //Check if we have a file to load
  107695. if (fileToLoad !== "") {
  107696. //Load the file synchronously
  107697. mtlPromises.push(new Promise(function (resolve, reject) {
  107698. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  107699. try {
  107700. //Create materials thanks MTLLoader function
  107701. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  107702. //Look at each material loaded in the mtl file
  107703. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  107704. //Three variables to get all meshes with the same material
  107705. var startIndex = 0;
  107706. var _indices = [];
  107707. var _index;
  107708. //The material from MTL file is used in the meshes loaded
  107709. //Push the indice in an array
  107710. //Check if the material is not used for another mesh
  107711. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  107712. _indices.push(_index);
  107713. startIndex = _index + 1;
  107714. }
  107715. //If the material is not used dispose it
  107716. if (_index == -1 && _indices.length == 0) {
  107717. //If the material is not needed, remove it
  107718. materialsFromMTLFile.materials[n].dispose();
  107719. }
  107720. else {
  107721. for (var o = 0; o < _indices.length; o++) {
  107722. //Apply the material to the BABYLON.Mesh for each mesh with the material
  107723. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  107724. }
  107725. }
  107726. }
  107727. resolve();
  107728. }
  107729. catch (e) {
  107730. reject(e);
  107731. }
  107732. });
  107733. }));
  107734. }
  107735. //Return an array with all BABYLON.Mesh
  107736. return Promise.all(mtlPromises).then(function () {
  107737. return babylonMeshesArray;
  107738. });
  107739. };
  107740. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  107741. OBJFileLoader.INVERT_Y = false;
  107742. return OBJFileLoader;
  107743. }());
  107744. BABYLON.OBJFileLoader = OBJFileLoader;
  107745. if (BABYLON.SceneLoader) {
  107746. //Add this loader into the register plugin
  107747. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  107748. }
  107749. })(BABYLON || (BABYLON = {}));
  107750. //# sourceMappingURL=babylon.objFileLoader.js.map
  107751. var BABYLON;
  107752. (function (BABYLON) {
  107753. /**
  107754. * Mode that determines the coordinate system to use.
  107755. */
  107756. var GLTFLoaderCoordinateSystemMode;
  107757. (function (GLTFLoaderCoordinateSystemMode) {
  107758. /**
  107759. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  107760. */
  107761. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  107762. /**
  107763. * Sets the useRightHandedSystem flag on the scene.
  107764. */
  107765. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  107766. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  107767. /**
  107768. * Mode that determines what animations will start.
  107769. */
  107770. var GLTFLoaderAnimationStartMode;
  107771. (function (GLTFLoaderAnimationStartMode) {
  107772. /**
  107773. * No animation will start.
  107774. */
  107775. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  107776. /**
  107777. * The first animation will start.
  107778. */
  107779. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  107780. /**
  107781. * All animations will start.
  107782. */
  107783. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  107784. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  107785. /**
  107786. * Loader state.
  107787. */
  107788. var GLTFLoaderState;
  107789. (function (GLTFLoaderState) {
  107790. /**
  107791. * The asset is loading.
  107792. */
  107793. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  107794. /**
  107795. * The asset is ready for rendering.
  107796. */
  107797. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  107798. /**
  107799. * The asset is completely loaded.
  107800. */
  107801. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  107802. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  107803. /**
  107804. * File loader for loading glTF files into a scene.
  107805. */
  107806. var GLTFFileLoader = /** @class */ (function () {
  107807. function GLTFFileLoader() {
  107808. // #region Common options
  107809. /**
  107810. * Raised when the asset has been parsed
  107811. */
  107812. this.onParsedObservable = new BABYLON.Observable();
  107813. // #endregion
  107814. // #region V2 options
  107815. /**
  107816. * The coordinate system mode. Defaults to AUTO.
  107817. */
  107818. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  107819. /**
  107820. * The animation start mode. Defaults to FIRST.
  107821. */
  107822. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  107823. /**
  107824. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  107825. */
  107826. this.compileMaterials = false;
  107827. /**
  107828. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  107829. */
  107830. this.useClipPlane = false;
  107831. /**
  107832. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  107833. */
  107834. this.compileShadowGenerators = false;
  107835. /**
  107836. * Defines if the Alpha blended materials are only applied as coverage.
  107837. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  107838. * If true, no extra effects are applied to transparent pixels.
  107839. */
  107840. this.transparencyAsCoverage = false;
  107841. /** @hidden */
  107842. this._normalizeAnimationGroupsToBeginAtZero = true;
  107843. /**
  107844. * Function called before loading a url referenced by the asset.
  107845. */
  107846. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107847. /**
  107848. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107849. */
  107850. this.onMeshLoadedObservable = new BABYLON.Observable();
  107851. /**
  107852. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  107853. */
  107854. this.onTextureLoadedObservable = new BABYLON.Observable();
  107855. /**
  107856. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  107857. */
  107858. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107859. /**
  107860. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  107861. */
  107862. this.onCameraLoadedObservable = new BABYLON.Observable();
  107863. /**
  107864. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  107865. * For assets with LODs, raised when all of the LODs are complete.
  107866. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107867. */
  107868. this.onCompleteObservable = new BABYLON.Observable();
  107869. /**
  107870. * Observable raised after the loader is disposed.
  107871. */
  107872. this.onDisposeObservable = new BABYLON.Observable();
  107873. /**
  107874. * Observable raised after a loader extension is created.
  107875. * Set additional options for a loader extension in this event.
  107876. */
  107877. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107878. // #endregion
  107879. this._loader = null;
  107880. /**
  107881. * Name of the loader ("gltf")
  107882. */
  107883. this.name = "gltf";
  107884. /**
  107885. * Supported file extensions of the loader (.gltf, .glb)
  107886. */
  107887. this.extensions = {
  107888. ".gltf": { isBinary: false },
  107889. ".glb": { isBinary: true }
  107890. };
  107891. this._logIndentLevel = 0;
  107892. this._loggingEnabled = false;
  107893. /** @hidden */
  107894. this._log = this._logDisabled;
  107895. this._capturePerformanceCounters = false;
  107896. /** @hidden */
  107897. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  107898. /** @hidden */
  107899. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  107900. }
  107901. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  107902. /**
  107903. * Raised when the asset has been parsed
  107904. */
  107905. set: function (callback) {
  107906. if (this._onParsedObserver) {
  107907. this.onParsedObservable.remove(this._onParsedObserver);
  107908. }
  107909. this._onParsedObserver = this.onParsedObservable.add(callback);
  107910. },
  107911. enumerable: true,
  107912. configurable: true
  107913. });
  107914. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  107915. /**
  107916. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107917. */
  107918. set: function (callback) {
  107919. if (this._onMeshLoadedObserver) {
  107920. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  107921. }
  107922. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  107923. },
  107924. enumerable: true,
  107925. configurable: true
  107926. });
  107927. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  107928. /**
  107929. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  107930. */
  107931. set: function (callback) {
  107932. if (this._onTextureLoadedObserver) {
  107933. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  107934. }
  107935. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  107936. },
  107937. enumerable: true,
  107938. configurable: true
  107939. });
  107940. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  107941. /**
  107942. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  107943. */
  107944. set: function (callback) {
  107945. if (this._onMaterialLoadedObserver) {
  107946. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  107947. }
  107948. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  107949. },
  107950. enumerable: true,
  107951. configurable: true
  107952. });
  107953. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  107954. /**
  107955. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  107956. */
  107957. set: function (callback) {
  107958. if (this._onCameraLoadedObserver) {
  107959. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  107960. }
  107961. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  107962. },
  107963. enumerable: true,
  107964. configurable: true
  107965. });
  107966. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  107967. /**
  107968. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  107969. */
  107970. set: function (callback) {
  107971. if (this._onCompleteObserver) {
  107972. this.onCompleteObservable.remove(this._onCompleteObserver);
  107973. }
  107974. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  107975. },
  107976. enumerable: true,
  107977. configurable: true
  107978. });
  107979. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  107980. /**
  107981. * Callback raised after the loader is disposed.
  107982. */
  107983. set: function (callback) {
  107984. if (this._onDisposeObserver) {
  107985. this.onDisposeObservable.remove(this._onDisposeObserver);
  107986. }
  107987. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  107988. },
  107989. enumerable: true,
  107990. configurable: true
  107991. });
  107992. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  107993. /**
  107994. * Callback raised after a loader extension is created.
  107995. */
  107996. set: function (callback) {
  107997. if (this._onExtensionLoadedObserver) {
  107998. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  107999. }
  108000. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  108001. },
  108002. enumerable: true,
  108003. configurable: true
  108004. });
  108005. /**
  108006. * Returns a promise that resolves when the asset is completely loaded.
  108007. * @returns a promise that resolves when the asset is completely loaded.
  108008. */
  108009. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  108010. var _this = this;
  108011. return new Promise(function (resolve) {
  108012. _this.onCompleteObservable.addOnce(function () {
  108013. resolve();
  108014. });
  108015. });
  108016. };
  108017. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  108018. /**
  108019. * The loader state or null if the loader is not active.
  108020. */
  108021. get: function () {
  108022. return this._loader ? this._loader.state : null;
  108023. },
  108024. enumerable: true,
  108025. configurable: true
  108026. });
  108027. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  108028. /**
  108029. * Defines if the loader logging is enabled.
  108030. */
  108031. get: function () {
  108032. return this._loggingEnabled;
  108033. },
  108034. set: function (value) {
  108035. if (this._loggingEnabled === value) {
  108036. return;
  108037. }
  108038. this._loggingEnabled = value;
  108039. if (this._loggingEnabled) {
  108040. this._log = this._logEnabled;
  108041. }
  108042. else {
  108043. this._log = this._logDisabled;
  108044. }
  108045. },
  108046. enumerable: true,
  108047. configurable: true
  108048. });
  108049. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  108050. /**
  108051. * Defines if the loader should capture performance counters.
  108052. */
  108053. get: function () {
  108054. return this._capturePerformanceCounters;
  108055. },
  108056. set: function (value) {
  108057. if (this._capturePerformanceCounters === value) {
  108058. return;
  108059. }
  108060. this._capturePerformanceCounters = value;
  108061. if (this._capturePerformanceCounters) {
  108062. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  108063. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  108064. }
  108065. else {
  108066. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  108067. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  108068. }
  108069. },
  108070. enumerable: true,
  108071. configurable: true
  108072. });
  108073. /**
  108074. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  108075. */
  108076. GLTFFileLoader.prototype.dispose = function () {
  108077. if (this._loader) {
  108078. this._loader.dispose();
  108079. this._loader = null;
  108080. }
  108081. this._clear();
  108082. this.onDisposeObservable.notifyObservers(undefined);
  108083. this.onDisposeObservable.clear();
  108084. };
  108085. /** @hidden */
  108086. GLTFFileLoader.prototype._clear = function () {
  108087. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  108088. this.onMeshLoadedObservable.clear();
  108089. this.onTextureLoadedObservable.clear();
  108090. this.onMaterialLoadedObservable.clear();
  108091. this.onCameraLoadedObservable.clear();
  108092. this.onCompleteObservable.clear();
  108093. this.onExtensionLoadedObservable.clear();
  108094. };
  108095. /**
  108096. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  108097. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  108098. * @param scene the scene the meshes should be added to
  108099. * @param data the glTF data to load
  108100. * @param rootUrl root url to load from
  108101. * @param onProgress event that fires when loading progress has occured
  108102. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  108103. */
  108104. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108105. var _this = this;
  108106. return Promise.resolve().then(function () {
  108107. var loaderData = _this._parse(data);
  108108. _this._loader = _this._getLoader(loaderData);
  108109. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  108110. });
  108111. };
  108112. /**
  108113. * Imports all objects from the loaded glTF data and adds them to the scene
  108114. * @param scene the scene the objects should be added to
  108115. * @param data the glTF data to load
  108116. * @param rootUrl root url to load from
  108117. * @param onProgress event that fires when loading progress has occured
  108118. * @returns a promise which completes when objects have been loaded to the scene
  108119. */
  108120. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108121. var _this = this;
  108122. return Promise.resolve().then(function () {
  108123. var loaderData = _this._parse(data);
  108124. _this._loader = _this._getLoader(loaderData);
  108125. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  108126. });
  108127. };
  108128. /**
  108129. * Load into an asset container.
  108130. * @param scene The scene to load into
  108131. * @param data The data to import
  108132. * @param rootUrl The root url for scene and resources
  108133. * @param onProgress The callback when the load progresses
  108134. * @returns The loaded asset container
  108135. */
  108136. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  108137. var _this = this;
  108138. return Promise.resolve().then(function () {
  108139. var loaderData = _this._parse(data);
  108140. _this._loader = _this._getLoader(loaderData);
  108141. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  108142. var container = new BABYLON.AssetContainer(scene);
  108143. Array.prototype.push.apply(container.meshes, result.meshes);
  108144. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  108145. Array.prototype.push.apply(container.skeletons, result.skeletons);
  108146. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  108147. container.removeAllFromScene();
  108148. return container;
  108149. });
  108150. });
  108151. };
  108152. /**
  108153. * If the data string can be loaded directly.
  108154. * @param data string contianing the file data
  108155. * @returns if the data can be loaded directly
  108156. */
  108157. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  108158. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  108159. };
  108160. /**
  108161. * Instantiates a glTF file loader plugin.
  108162. * @returns the created plugin
  108163. */
  108164. GLTFFileLoader.prototype.createPlugin = function () {
  108165. return new GLTFFileLoader();
  108166. };
  108167. GLTFFileLoader.prototype._parse = function (data) {
  108168. this._startPerformanceCounter("Parse");
  108169. var parsedData;
  108170. if (data instanceof ArrayBuffer) {
  108171. this._log("Parsing binary");
  108172. parsedData = this._parseBinary(data);
  108173. }
  108174. else {
  108175. this._log("Parsing JSON");
  108176. this._log("JSON length: " + data.length);
  108177. parsedData = {
  108178. json: JSON.parse(data),
  108179. bin: null
  108180. };
  108181. }
  108182. this.onParsedObservable.notifyObservers(parsedData);
  108183. this.onParsedObservable.clear();
  108184. this._endPerformanceCounter("Parse");
  108185. return parsedData;
  108186. };
  108187. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  108188. var asset = loaderData.json.asset || {};
  108189. this._log("Asset version: " + asset.version);
  108190. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  108191. asset.generator && this._log("Asset generator: " + asset.generator);
  108192. var version = GLTFFileLoader._parseVersion(asset.version);
  108193. if (!version) {
  108194. throw new Error("Invalid version: " + asset.version);
  108195. }
  108196. if (asset.minVersion !== undefined) {
  108197. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  108198. if (!minVersion) {
  108199. throw new Error("Invalid minimum version: " + asset.minVersion);
  108200. }
  108201. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  108202. throw new Error("Incompatible minimum version: " + asset.minVersion);
  108203. }
  108204. }
  108205. var createLoaders = {
  108206. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  108207. 2: GLTFFileLoader._CreateGLTFLoaderV2
  108208. };
  108209. var createLoader = createLoaders[version.major];
  108210. if (!createLoader) {
  108211. throw new Error("Unsupported version: " + asset.version);
  108212. }
  108213. return createLoader(this);
  108214. };
  108215. GLTFFileLoader.prototype._parseBinary = function (data) {
  108216. var Binary = {
  108217. Magic: 0x46546C67
  108218. };
  108219. this._log("Binary length: " + data.byteLength);
  108220. var binaryReader = new BinaryReader(data);
  108221. var magic = binaryReader.readUint32();
  108222. if (magic !== Binary.Magic) {
  108223. throw new Error("Unexpected magic: " + magic);
  108224. }
  108225. var version = binaryReader.readUint32();
  108226. if (this.loggingEnabled) {
  108227. this._log("Binary version: " + version);
  108228. }
  108229. switch (version) {
  108230. case 1: return this._parseV1(binaryReader);
  108231. case 2: return this._parseV2(binaryReader);
  108232. }
  108233. throw new Error("Unsupported version: " + version);
  108234. };
  108235. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  108236. var ContentFormat = {
  108237. JSON: 0
  108238. };
  108239. var length = binaryReader.readUint32();
  108240. if (length != binaryReader.getLength()) {
  108241. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  108242. }
  108243. var contentLength = binaryReader.readUint32();
  108244. var contentFormat = binaryReader.readUint32();
  108245. var content;
  108246. switch (contentFormat) {
  108247. case ContentFormat.JSON: {
  108248. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  108249. break;
  108250. }
  108251. default: {
  108252. throw new Error("Unexpected content format: " + contentFormat);
  108253. }
  108254. }
  108255. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  108256. var body = binaryReader.readUint8Array(bytesRemaining);
  108257. return {
  108258. json: content,
  108259. bin: body
  108260. };
  108261. };
  108262. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  108263. var ChunkFormat = {
  108264. JSON: 0x4E4F534A,
  108265. BIN: 0x004E4942
  108266. };
  108267. var length = binaryReader.readUint32();
  108268. if (length !== binaryReader.getLength()) {
  108269. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  108270. }
  108271. // JSON chunk
  108272. var chunkLength = binaryReader.readUint32();
  108273. var chunkFormat = binaryReader.readUint32();
  108274. if (chunkFormat !== ChunkFormat.JSON) {
  108275. throw new Error("First chunk format is not JSON");
  108276. }
  108277. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  108278. // Look for BIN chunk
  108279. var bin = null;
  108280. while (binaryReader.getPosition() < binaryReader.getLength()) {
  108281. var chunkLength_1 = binaryReader.readUint32();
  108282. var chunkFormat_1 = binaryReader.readUint32();
  108283. switch (chunkFormat_1) {
  108284. case ChunkFormat.JSON: {
  108285. throw new Error("Unexpected JSON chunk");
  108286. }
  108287. case ChunkFormat.BIN: {
  108288. bin = binaryReader.readUint8Array(chunkLength_1);
  108289. break;
  108290. }
  108291. default: {
  108292. // ignore unrecognized chunkFormat
  108293. binaryReader.skipBytes(chunkLength_1);
  108294. break;
  108295. }
  108296. }
  108297. }
  108298. return {
  108299. json: json,
  108300. bin: bin
  108301. };
  108302. };
  108303. GLTFFileLoader._parseVersion = function (version) {
  108304. if (version === "1.0" || version === "1.0.1") {
  108305. return {
  108306. major: 1,
  108307. minor: 0
  108308. };
  108309. }
  108310. var match = (version + "").match(/^(\d+)\.(\d+)/);
  108311. if (!match) {
  108312. return null;
  108313. }
  108314. return {
  108315. major: parseInt(match[1]),
  108316. minor: parseInt(match[2])
  108317. };
  108318. };
  108319. GLTFFileLoader._compareVersion = function (a, b) {
  108320. if (a.major > b.major)
  108321. return 1;
  108322. if (a.major < b.major)
  108323. return -1;
  108324. if (a.minor > b.minor)
  108325. return 1;
  108326. if (a.minor < b.minor)
  108327. return -1;
  108328. return 0;
  108329. };
  108330. GLTFFileLoader._decodeBufferToText = function (buffer) {
  108331. var result = "";
  108332. var length = buffer.byteLength;
  108333. for (var i = 0; i < length; i++) {
  108334. result += String.fromCharCode(buffer[i]);
  108335. }
  108336. return result;
  108337. };
  108338. /** @hidden */
  108339. GLTFFileLoader.prototype._logOpen = function (message) {
  108340. this._log(message);
  108341. this._logIndentLevel++;
  108342. };
  108343. /** @hidden */
  108344. GLTFFileLoader.prototype._logClose = function () {
  108345. --this._logIndentLevel;
  108346. };
  108347. GLTFFileLoader.prototype._logEnabled = function (message) {
  108348. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  108349. BABYLON.Tools.Log("" + spaces + message);
  108350. };
  108351. GLTFFileLoader.prototype._logDisabled = function (message) {
  108352. };
  108353. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  108354. BABYLON.Tools.StartPerformanceCounter(counterName);
  108355. };
  108356. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  108357. };
  108358. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  108359. BABYLON.Tools.EndPerformanceCounter(counterName);
  108360. };
  108361. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  108362. };
  108363. // #endregion
  108364. // #region V1 options
  108365. /**
  108366. * 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.
  108367. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  108368. * Defaults to true.
  108369. * @hidden
  108370. */
  108371. GLTFFileLoader.IncrementalLoading = true;
  108372. /**
  108373. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  108374. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  108375. * @hidden
  108376. */
  108377. GLTFFileLoader.HomogeneousCoordinates = false;
  108378. GLTFFileLoader._logSpaces = " ";
  108379. return GLTFFileLoader;
  108380. }());
  108381. BABYLON.GLTFFileLoader = GLTFFileLoader;
  108382. var BinaryReader = /** @class */ (function () {
  108383. function BinaryReader(arrayBuffer) {
  108384. this._arrayBuffer = arrayBuffer;
  108385. this._dataView = new DataView(arrayBuffer);
  108386. this._byteOffset = 0;
  108387. }
  108388. BinaryReader.prototype.getPosition = function () {
  108389. return this._byteOffset;
  108390. };
  108391. BinaryReader.prototype.getLength = function () {
  108392. return this._arrayBuffer.byteLength;
  108393. };
  108394. BinaryReader.prototype.readUint32 = function () {
  108395. var value = this._dataView.getUint32(this._byteOffset, true);
  108396. this._byteOffset += 4;
  108397. return value;
  108398. };
  108399. BinaryReader.prototype.readUint8Array = function (length) {
  108400. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  108401. this._byteOffset += length;
  108402. return value;
  108403. };
  108404. BinaryReader.prototype.skipBytes = function (length) {
  108405. this._byteOffset += length;
  108406. };
  108407. return BinaryReader;
  108408. }());
  108409. if (BABYLON.SceneLoader) {
  108410. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  108411. }
  108412. })(BABYLON || (BABYLON = {}));
  108413. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  108414. var BABYLON;
  108415. (function (BABYLON) {
  108416. var GLTF1;
  108417. (function (GLTF1) {
  108418. /**
  108419. * Enums
  108420. */
  108421. var EComponentType;
  108422. (function (EComponentType) {
  108423. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  108424. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  108425. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  108426. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  108427. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  108428. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  108429. var EShaderType;
  108430. (function (EShaderType) {
  108431. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  108432. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  108433. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  108434. var EParameterType;
  108435. (function (EParameterType) {
  108436. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  108437. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  108438. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  108439. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  108440. EParameterType[EParameterType["INT"] = 5124] = "INT";
  108441. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  108442. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  108443. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  108444. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  108445. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  108446. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  108447. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  108448. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  108449. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  108450. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  108451. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  108452. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  108453. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  108454. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  108455. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  108456. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  108457. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  108458. var ETextureWrapMode;
  108459. (function (ETextureWrapMode) {
  108460. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  108461. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  108462. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  108463. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  108464. var ETextureFilterType;
  108465. (function (ETextureFilterType) {
  108466. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  108467. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  108468. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  108469. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  108470. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  108471. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  108472. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  108473. var ETextureFormat;
  108474. (function (ETextureFormat) {
  108475. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  108476. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  108477. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  108478. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  108479. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  108480. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  108481. var ECullingType;
  108482. (function (ECullingType) {
  108483. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  108484. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  108485. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  108486. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  108487. var EBlendingFunction;
  108488. (function (EBlendingFunction) {
  108489. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  108490. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  108491. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  108492. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  108493. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  108494. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  108495. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  108496. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  108497. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  108498. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  108499. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  108500. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  108501. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  108502. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  108503. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  108504. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  108505. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108506. })(BABYLON || (BABYLON = {}));
  108507. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108508. var BABYLON;
  108509. (function (BABYLON) {
  108510. var GLTF1;
  108511. (function (GLTF1) {
  108512. /**
  108513. * Tokenizer. Used for shaders compatibility
  108514. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  108515. */
  108516. var ETokenType;
  108517. (function (ETokenType) {
  108518. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  108519. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  108520. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  108521. })(ETokenType || (ETokenType = {}));
  108522. var Tokenizer = /** @class */ (function () {
  108523. function Tokenizer(toParse) {
  108524. this._pos = 0;
  108525. this.currentToken = ETokenType.UNKNOWN;
  108526. this.currentIdentifier = "";
  108527. this.currentString = "";
  108528. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  108529. this._toParse = toParse;
  108530. this._maxPos = toParse.length;
  108531. }
  108532. Tokenizer.prototype.getNextToken = function () {
  108533. if (this.isEnd())
  108534. return ETokenType.END_OF_INPUT;
  108535. this.currentString = this.read();
  108536. this.currentToken = ETokenType.UNKNOWN;
  108537. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  108538. this.currentToken = ETokenType.IDENTIFIER;
  108539. this.currentIdentifier = this.currentString;
  108540. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  108541. this.currentIdentifier += this.currentString;
  108542. this.forward();
  108543. }
  108544. }
  108545. return this.currentToken;
  108546. };
  108547. Tokenizer.prototype.peek = function () {
  108548. return this._toParse[this._pos];
  108549. };
  108550. Tokenizer.prototype.read = function () {
  108551. return this._toParse[this._pos++];
  108552. };
  108553. Tokenizer.prototype.forward = function () {
  108554. this._pos++;
  108555. };
  108556. Tokenizer.prototype.isEnd = function () {
  108557. return this._pos >= this._maxPos;
  108558. };
  108559. return Tokenizer;
  108560. }());
  108561. /**
  108562. * Values
  108563. */
  108564. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  108565. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  108566. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  108567. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  108568. /**
  108569. * Parse
  108570. */
  108571. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  108572. for (var buf in parsedBuffers) {
  108573. var parsedBuffer = parsedBuffers[buf];
  108574. gltfRuntime.buffers[buf] = parsedBuffer;
  108575. gltfRuntime.buffersCount++;
  108576. }
  108577. };
  108578. var parseShaders = function (parsedShaders, gltfRuntime) {
  108579. for (var sha in parsedShaders) {
  108580. var parsedShader = parsedShaders[sha];
  108581. gltfRuntime.shaders[sha] = parsedShader;
  108582. gltfRuntime.shaderscount++;
  108583. }
  108584. };
  108585. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  108586. for (var object in parsedObjects) {
  108587. var parsedObject = parsedObjects[object];
  108588. gltfRuntime[runtimeProperty][object] = parsedObject;
  108589. }
  108590. };
  108591. /**
  108592. * Utils
  108593. */
  108594. var normalizeUVs = function (buffer) {
  108595. if (!buffer) {
  108596. return;
  108597. }
  108598. for (var i = 0; i < buffer.length / 2; i++) {
  108599. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  108600. }
  108601. };
  108602. var getAttribute = function (attributeParameter) {
  108603. if (attributeParameter.semantic === "NORMAL") {
  108604. return "normal";
  108605. }
  108606. else if (attributeParameter.semantic === "POSITION") {
  108607. return "position";
  108608. }
  108609. else if (attributeParameter.semantic === "JOINT") {
  108610. return "matricesIndices";
  108611. }
  108612. else if (attributeParameter.semantic === "WEIGHT") {
  108613. return "matricesWeights";
  108614. }
  108615. else if (attributeParameter.semantic === "COLOR") {
  108616. return "color";
  108617. }
  108618. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  108619. var channel = Number(attributeParameter.semantic.split("_")[1]);
  108620. return "uv" + (channel === 0 ? "" : channel + 1);
  108621. }
  108622. return null;
  108623. };
  108624. /**
  108625. * Loads and creates animations
  108626. */
  108627. var loadAnimations = function (gltfRuntime) {
  108628. for (var anim in gltfRuntime.animations) {
  108629. var animation = gltfRuntime.animations[anim];
  108630. if (!animation.channels || !animation.samplers) {
  108631. continue;
  108632. }
  108633. var lastAnimation = null;
  108634. for (var i = 0; i < animation.channels.length; i++) {
  108635. // Get parameters and load buffers
  108636. var channel = animation.channels[i];
  108637. var sampler = animation.samplers[channel.sampler];
  108638. if (!sampler) {
  108639. continue;
  108640. }
  108641. var inputData = null;
  108642. var outputData = null;
  108643. if (animation.parameters) {
  108644. inputData = animation.parameters[sampler.input];
  108645. outputData = animation.parameters[sampler.output];
  108646. }
  108647. else {
  108648. inputData = sampler.input;
  108649. outputData = sampler.output;
  108650. }
  108651. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  108652. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  108653. var targetID = channel.target.id;
  108654. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  108655. if (targetNode === null) {
  108656. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  108657. }
  108658. if (targetNode === null) {
  108659. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  108660. continue;
  108661. }
  108662. var isBone = targetNode instanceof BABYLON.Bone;
  108663. // Get target path (position, rotation or scaling)
  108664. var targetPath = channel.target.path;
  108665. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  108666. if (targetPathIndex !== -1) {
  108667. targetPath = babylonAnimationPaths[targetPathIndex];
  108668. }
  108669. // Determine animation type
  108670. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  108671. if (!isBone) {
  108672. if (targetPath === "rotationQuaternion") {
  108673. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108674. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  108675. }
  108676. else {
  108677. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108678. }
  108679. }
  108680. // Create animation and key frames
  108681. var babylonAnimation = null;
  108682. var keys = [];
  108683. var arrayOffset = 0;
  108684. var modifyKey = false;
  108685. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  108686. babylonAnimation = lastAnimation;
  108687. modifyKey = true;
  108688. }
  108689. if (!modifyKey) {
  108690. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  108691. }
  108692. // For each frame
  108693. for (var j = 0; j < bufferInput.length; j++) {
  108694. var value = null;
  108695. if (targetPath === "rotationQuaternion") { // VEC4
  108696. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  108697. arrayOffset += 4;
  108698. }
  108699. else { // Position and scaling are VEC3
  108700. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  108701. arrayOffset += 3;
  108702. }
  108703. if (isBone) {
  108704. var bone = targetNode;
  108705. var translation = BABYLON.Vector3.Zero();
  108706. var rotationQuaternion = new BABYLON.Quaternion();
  108707. var scaling = BABYLON.Vector3.Zero();
  108708. // Warning on decompose
  108709. var mat = bone.getBaseMatrix();
  108710. if (modifyKey && lastAnimation) {
  108711. mat = lastAnimation.getKeys()[j].value;
  108712. }
  108713. mat.decompose(scaling, rotationQuaternion, translation);
  108714. if (targetPath === "position") {
  108715. translation = value;
  108716. }
  108717. else if (targetPath === "rotationQuaternion") {
  108718. rotationQuaternion = value;
  108719. }
  108720. else {
  108721. scaling = value;
  108722. }
  108723. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  108724. }
  108725. if (!modifyKey) {
  108726. keys.push({
  108727. frame: bufferInput[j],
  108728. value: value
  108729. });
  108730. }
  108731. else if (lastAnimation) {
  108732. lastAnimation.getKeys()[j].value = value;
  108733. }
  108734. }
  108735. // Finish
  108736. if (!modifyKey && babylonAnimation) {
  108737. babylonAnimation.setKeys(keys);
  108738. targetNode.animations.push(babylonAnimation);
  108739. }
  108740. lastAnimation = babylonAnimation;
  108741. gltfRuntime.scene.stopAnimation(targetNode);
  108742. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  108743. }
  108744. }
  108745. };
  108746. /**
  108747. * Returns the bones transformation matrix
  108748. */
  108749. var configureBoneTransformation = function (node) {
  108750. var mat = null;
  108751. if (node.translation || node.rotation || node.scale) {
  108752. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  108753. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  108754. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  108755. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  108756. }
  108757. else {
  108758. mat = BABYLON.Matrix.FromArray(node.matrix);
  108759. }
  108760. return mat;
  108761. };
  108762. /**
  108763. * Returns the parent bone
  108764. */
  108765. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  108766. // Try to find
  108767. for (var i = 0; i < newSkeleton.bones.length; i++) {
  108768. if (newSkeleton.bones[i].name === jointName) {
  108769. return newSkeleton.bones[i];
  108770. }
  108771. }
  108772. // Not found, search in gltf nodes
  108773. var nodes = gltfRuntime.nodes;
  108774. for (var nde in nodes) {
  108775. var node = nodes[nde];
  108776. if (!node.jointName) {
  108777. continue;
  108778. }
  108779. var children = node.children;
  108780. for (var i = 0; i < children.length; i++) {
  108781. var child = gltfRuntime.nodes[children[i]];
  108782. if (!child.jointName) {
  108783. continue;
  108784. }
  108785. if (child.jointName === jointName) {
  108786. var mat = configureBoneTransformation(node);
  108787. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  108788. bone.id = nde;
  108789. return bone;
  108790. }
  108791. }
  108792. }
  108793. return null;
  108794. };
  108795. /**
  108796. * Returns the appropriate root node
  108797. */
  108798. var getNodeToRoot = function (nodesToRoot, id) {
  108799. for (var i = 0; i < nodesToRoot.length; i++) {
  108800. var nodeToRoot = nodesToRoot[i];
  108801. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  108802. var child = nodeToRoot.node.children[j];
  108803. if (child === id) {
  108804. return nodeToRoot.bone;
  108805. }
  108806. }
  108807. }
  108808. return null;
  108809. };
  108810. /**
  108811. * Returns the node with the joint name
  108812. */
  108813. var getJointNode = function (gltfRuntime, jointName) {
  108814. var nodes = gltfRuntime.nodes;
  108815. var node = nodes[jointName];
  108816. if (node) {
  108817. return {
  108818. node: node,
  108819. id: jointName
  108820. };
  108821. }
  108822. for (var nde in nodes) {
  108823. node = nodes[nde];
  108824. if (node.jointName === jointName) {
  108825. return {
  108826. node: node,
  108827. id: nde
  108828. };
  108829. }
  108830. }
  108831. return null;
  108832. };
  108833. /**
  108834. * Checks if a nodes is in joints
  108835. */
  108836. var nodeIsInJoints = function (skins, id) {
  108837. for (var i = 0; i < skins.jointNames.length; i++) {
  108838. if (skins.jointNames[i] === id) {
  108839. return true;
  108840. }
  108841. }
  108842. return false;
  108843. };
  108844. /**
  108845. * Fills the nodes to root for bones and builds hierarchy
  108846. */
  108847. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  108848. // Creates nodes for root
  108849. for (var nde in gltfRuntime.nodes) {
  108850. var node = gltfRuntime.nodes[nde];
  108851. var id = nde;
  108852. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  108853. continue;
  108854. }
  108855. // Create node to root bone
  108856. var mat = configureBoneTransformation(node);
  108857. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  108858. bone.id = id;
  108859. nodesToRoot.push({ bone: bone, node: node, id: id });
  108860. }
  108861. // Parenting
  108862. for (var i = 0; i < nodesToRoot.length; i++) {
  108863. var nodeToRoot = nodesToRoot[i];
  108864. var children = nodeToRoot.node.children;
  108865. for (var j = 0; j < children.length; j++) {
  108866. var child = null;
  108867. for (var k = 0; k < nodesToRoot.length; k++) {
  108868. if (nodesToRoot[k].id === children[j]) {
  108869. child = nodesToRoot[k];
  108870. break;
  108871. }
  108872. }
  108873. if (child) {
  108874. child.bone._parent = nodeToRoot.bone;
  108875. nodeToRoot.bone.children.push(child.bone);
  108876. }
  108877. }
  108878. }
  108879. };
  108880. /**
  108881. * Imports a skeleton
  108882. */
  108883. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  108884. if (!newSkeleton) {
  108885. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  108886. }
  108887. if (!skins.babylonSkeleton) {
  108888. return newSkeleton;
  108889. }
  108890. // Find the root bones
  108891. var nodesToRoot = [];
  108892. var nodesToRootToAdd = [];
  108893. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  108894. newSkeleton.bones = [];
  108895. // Joints
  108896. for (var i = 0; i < skins.jointNames.length; i++) {
  108897. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108898. if (!jointNode) {
  108899. continue;
  108900. }
  108901. var node = jointNode.node;
  108902. if (!node) {
  108903. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  108904. continue;
  108905. }
  108906. var id = jointNode.id;
  108907. // Optimize, if the bone already exists...
  108908. var existingBone = gltfRuntime.scene.getBoneByID(id);
  108909. if (existingBone) {
  108910. newSkeleton.bones.push(existingBone);
  108911. continue;
  108912. }
  108913. // Search for parent bone
  108914. var foundBone = false;
  108915. var parentBone = null;
  108916. for (var j = 0; j < i; j++) {
  108917. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  108918. if (!jointNode_1) {
  108919. continue;
  108920. }
  108921. var joint = jointNode_1.node;
  108922. if (!joint) {
  108923. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  108924. continue;
  108925. }
  108926. var children = joint.children;
  108927. if (!children) {
  108928. continue;
  108929. }
  108930. foundBone = false;
  108931. for (var k = 0; k < children.length; k++) {
  108932. if (children[k] === id) {
  108933. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  108934. foundBone = true;
  108935. break;
  108936. }
  108937. }
  108938. if (foundBone) {
  108939. break;
  108940. }
  108941. }
  108942. // Create bone
  108943. var mat = configureBoneTransformation(node);
  108944. if (!parentBone && nodesToRoot.length > 0) {
  108945. parentBone = getNodeToRoot(nodesToRoot, id);
  108946. if (parentBone) {
  108947. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  108948. nodesToRootToAdd.push(parentBone);
  108949. }
  108950. }
  108951. }
  108952. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  108953. bone.id = id;
  108954. }
  108955. // Polish
  108956. var bones = newSkeleton.bones;
  108957. newSkeleton.bones = [];
  108958. for (var i = 0; i < skins.jointNames.length; i++) {
  108959. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108960. if (!jointNode) {
  108961. continue;
  108962. }
  108963. for (var j = 0; j < bones.length; j++) {
  108964. if (bones[j].id === jointNode.id) {
  108965. newSkeleton.bones.push(bones[j]);
  108966. break;
  108967. }
  108968. }
  108969. }
  108970. newSkeleton.prepare();
  108971. // Finish
  108972. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  108973. newSkeleton.bones.push(nodesToRootToAdd[i]);
  108974. }
  108975. return newSkeleton;
  108976. };
  108977. /**
  108978. * Imports a mesh and its geometries
  108979. */
  108980. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  108981. if (!newMesh) {
  108982. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108983. newMesh.id = id;
  108984. }
  108985. if (!node.babylonNode) {
  108986. return newMesh;
  108987. }
  108988. var subMaterials = [];
  108989. var vertexData = null;
  108990. var verticesStarts = new Array();
  108991. var verticesCounts = new Array();
  108992. var indexStarts = new Array();
  108993. var indexCounts = new Array();
  108994. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  108995. var meshID = meshes[meshIndex];
  108996. var mesh = gltfRuntime.meshes[meshID];
  108997. if (!mesh) {
  108998. continue;
  108999. }
  109000. // Positions, normals and UVs
  109001. for (var i = 0; i < mesh.primitives.length; i++) {
  109002. // Temporary vertex data
  109003. var tempVertexData = new BABYLON.VertexData();
  109004. var primitive = mesh.primitives[i];
  109005. if (primitive.mode !== 4) {
  109006. // continue;
  109007. }
  109008. var attributes = primitive.attributes;
  109009. var accessor = null;
  109010. var buffer = null;
  109011. // Set positions, normal and uvs
  109012. for (var semantic in attributes) {
  109013. // Link accessor and buffer view
  109014. accessor = gltfRuntime.accessors[attributes[semantic]];
  109015. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  109016. if (semantic === "NORMAL") {
  109017. tempVertexData.normals = new Float32Array(buffer.length);
  109018. tempVertexData.normals.set(buffer);
  109019. }
  109020. else if (semantic === "POSITION") {
  109021. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  109022. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  109023. for (var j = 0; j < buffer.length; j += 4) {
  109024. tempVertexData.positions[j] = buffer[j];
  109025. tempVertexData.positions[j + 1] = buffer[j + 1];
  109026. tempVertexData.positions[j + 2] = buffer[j + 2];
  109027. }
  109028. }
  109029. else {
  109030. tempVertexData.positions = new Float32Array(buffer.length);
  109031. tempVertexData.positions.set(buffer);
  109032. }
  109033. verticesCounts.push(tempVertexData.positions.length);
  109034. }
  109035. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  109036. var channel = Number(semantic.split("_")[1]);
  109037. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  109038. var uvs = new Float32Array(buffer.length);
  109039. uvs.set(buffer);
  109040. normalizeUVs(uvs);
  109041. tempVertexData.set(uvs, uvKind);
  109042. }
  109043. else if (semantic === "JOINT") {
  109044. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  109045. tempVertexData.matricesIndices.set(buffer);
  109046. }
  109047. else if (semantic === "WEIGHT") {
  109048. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  109049. tempVertexData.matricesWeights.set(buffer);
  109050. }
  109051. else if (semantic === "COLOR") {
  109052. tempVertexData.colors = new Float32Array(buffer.length);
  109053. tempVertexData.colors.set(buffer);
  109054. }
  109055. }
  109056. // Indices
  109057. accessor = gltfRuntime.accessors[primitive.indices];
  109058. if (accessor) {
  109059. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  109060. tempVertexData.indices = new Int32Array(buffer.length);
  109061. tempVertexData.indices.set(buffer);
  109062. indexCounts.push(tempVertexData.indices.length);
  109063. }
  109064. else {
  109065. // Set indices on the fly
  109066. var indices = [];
  109067. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  109068. indices.push(j);
  109069. }
  109070. tempVertexData.indices = new Int32Array(indices);
  109071. indexCounts.push(tempVertexData.indices.length);
  109072. }
  109073. if (!vertexData) {
  109074. vertexData = tempVertexData;
  109075. }
  109076. else {
  109077. vertexData.merge(tempVertexData);
  109078. }
  109079. // Sub material
  109080. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  109081. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  109082. // Update vertices start and index start
  109083. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  109084. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  109085. }
  109086. }
  109087. var material;
  109088. if (subMaterials.length > 1) {
  109089. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  109090. material.subMaterials = subMaterials;
  109091. }
  109092. else {
  109093. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  109094. }
  109095. if (subMaterials.length === 1) {
  109096. material = subMaterials[0];
  109097. }
  109098. if (!newMesh.material) {
  109099. newMesh.material = material;
  109100. }
  109101. // Apply geometry
  109102. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  109103. newMesh.computeWorldMatrix(true);
  109104. // Apply submeshes
  109105. newMesh.subMeshes = [];
  109106. var index = 0;
  109107. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  109108. var meshID = meshes[meshIndex];
  109109. var mesh = gltfRuntime.meshes[meshID];
  109110. if (!mesh) {
  109111. continue;
  109112. }
  109113. for (var i = 0; i < mesh.primitives.length; i++) {
  109114. if (mesh.primitives[i].mode !== 4) {
  109115. //continue;
  109116. }
  109117. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  109118. index++;
  109119. }
  109120. }
  109121. // Finish
  109122. return newMesh;
  109123. };
  109124. /**
  109125. * Configure node transformation from position, rotation and scaling
  109126. */
  109127. var configureNode = function (newNode, position, rotation, scaling) {
  109128. if (newNode.position) {
  109129. newNode.position = position;
  109130. }
  109131. if (newNode.rotationQuaternion || newNode.rotation) {
  109132. newNode.rotationQuaternion = rotation;
  109133. }
  109134. if (newNode.scaling) {
  109135. newNode.scaling = scaling;
  109136. }
  109137. };
  109138. /**
  109139. * Configures node from transformation matrix
  109140. */
  109141. var configureNodeFromMatrix = function (newNode, node, parent) {
  109142. if (node.matrix) {
  109143. var position = new BABYLON.Vector3(0, 0, 0);
  109144. var rotation = new BABYLON.Quaternion();
  109145. var scaling = new BABYLON.Vector3(0, 0, 0);
  109146. var mat = BABYLON.Matrix.FromArray(node.matrix);
  109147. mat.decompose(scaling, rotation, position);
  109148. configureNode(newNode, position, rotation, scaling);
  109149. }
  109150. else if (node.translation && node.rotation && node.scale) {
  109151. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  109152. }
  109153. newNode.computeWorldMatrix(true);
  109154. };
  109155. /**
  109156. * Imports a node
  109157. */
  109158. var importNode = function (gltfRuntime, node, id, parent) {
  109159. var lastNode = null;
  109160. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  109161. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  109162. return null;
  109163. }
  109164. }
  109165. // Meshes
  109166. if (node.skin) {
  109167. if (node.meshes) {
  109168. var skin = gltfRuntime.skins[node.skin];
  109169. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  109170. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  109171. if (newMesh.skeleton === null) {
  109172. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  109173. if (!skin.babylonSkeleton) {
  109174. skin.babylonSkeleton = newMesh.skeleton;
  109175. }
  109176. }
  109177. lastNode = newMesh;
  109178. }
  109179. }
  109180. else if (node.meshes) {
  109181. /**
  109182. * Improve meshes property
  109183. */
  109184. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  109185. lastNode = newMesh;
  109186. }
  109187. // Lights
  109188. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  109189. var light = gltfRuntime.lights[node.light];
  109190. if (light) {
  109191. if (light.type === "ambient") {
  109192. var ambienLight = light[light.type];
  109193. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  109194. hemiLight.name = node.name || "";
  109195. if (ambienLight.color) {
  109196. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  109197. }
  109198. lastNode = hemiLight;
  109199. }
  109200. else if (light.type === "directional") {
  109201. var directionalLight = light[light.type];
  109202. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  109203. dirLight.name = node.name || "";
  109204. if (directionalLight.color) {
  109205. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  109206. }
  109207. lastNode = dirLight;
  109208. }
  109209. else if (light.type === "point") {
  109210. var pointLight = light[light.type];
  109211. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  109212. ptLight.name = node.name || "";
  109213. if (pointLight.color) {
  109214. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  109215. }
  109216. lastNode = ptLight;
  109217. }
  109218. else if (light.type === "spot") {
  109219. var spotLight = light[light.type];
  109220. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  109221. spLight.name = node.name || "";
  109222. if (spotLight.color) {
  109223. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  109224. }
  109225. if (spotLight.fallOfAngle) {
  109226. spLight.angle = spotLight.fallOfAngle;
  109227. }
  109228. if (spotLight.fallOffExponent) {
  109229. spLight.exponent = spotLight.fallOffExponent;
  109230. }
  109231. lastNode = spLight;
  109232. }
  109233. }
  109234. }
  109235. // Cameras
  109236. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  109237. var camera = gltfRuntime.cameras[node.camera];
  109238. if (camera) {
  109239. if (camera.type === "orthographic") {
  109240. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  109241. orthoCamera.name = node.name || "";
  109242. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  109243. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  109244. lastNode = orthoCamera;
  109245. }
  109246. else if (camera.type === "perspective") {
  109247. var perspectiveCamera = camera[camera.type];
  109248. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  109249. persCamera.name = node.name || "";
  109250. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  109251. if (!perspectiveCamera.aspectRatio) {
  109252. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  109253. }
  109254. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  109255. persCamera.maxZ = perspectiveCamera.zfar;
  109256. persCamera.minZ = perspectiveCamera.znear;
  109257. }
  109258. lastNode = persCamera;
  109259. }
  109260. }
  109261. }
  109262. // Empty node
  109263. if (!node.jointName) {
  109264. if (node.babylonNode) {
  109265. return node.babylonNode;
  109266. }
  109267. else if (lastNode === null) {
  109268. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  109269. node.babylonNode = dummy;
  109270. lastNode = dummy;
  109271. }
  109272. }
  109273. if (lastNode !== null) {
  109274. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  109275. configureNodeFromMatrix(lastNode, node, parent);
  109276. }
  109277. else {
  109278. var translation = node.translation || [0, 0, 0];
  109279. var rotation = node.rotation || [0, 0, 0, 1];
  109280. var scale = node.scale || [1, 1, 1];
  109281. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  109282. }
  109283. lastNode.updateCache(true);
  109284. node.babylonNode = lastNode;
  109285. }
  109286. return lastNode;
  109287. };
  109288. /**
  109289. * Traverses nodes and creates them
  109290. */
  109291. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  109292. if (meshIncluded === void 0) { meshIncluded = false; }
  109293. var node = gltfRuntime.nodes[id];
  109294. var newNode = null;
  109295. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  109296. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  109297. meshIncluded = true;
  109298. }
  109299. else {
  109300. meshIncluded = false;
  109301. }
  109302. }
  109303. else {
  109304. meshIncluded = true;
  109305. }
  109306. if (!node.jointName && meshIncluded) {
  109307. newNode = importNode(gltfRuntime, node, id, parent);
  109308. if (newNode !== null) {
  109309. newNode.id = id;
  109310. newNode.parent = parent;
  109311. }
  109312. }
  109313. if (node.children) {
  109314. for (var i = 0; i < node.children.length; i++) {
  109315. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  109316. }
  109317. }
  109318. };
  109319. /**
  109320. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  109321. */
  109322. var postLoad = function (gltfRuntime) {
  109323. // Nodes
  109324. var currentScene = gltfRuntime.currentScene;
  109325. if (currentScene) {
  109326. for (var i = 0; i < currentScene.nodes.length; i++) {
  109327. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109328. }
  109329. }
  109330. else {
  109331. for (var thing in gltfRuntime.scenes) {
  109332. currentScene = gltfRuntime.scenes[thing];
  109333. for (var i = 0; i < currentScene.nodes.length; i++) {
  109334. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109335. }
  109336. }
  109337. }
  109338. // Set animations
  109339. loadAnimations(gltfRuntime);
  109340. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  109341. var skeleton = gltfRuntime.scene.skeletons[i];
  109342. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  109343. }
  109344. };
  109345. /**
  109346. * onBind shaderrs callback to set uniforms and matrices
  109347. */
  109348. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  109349. var materialValues = material.values || technique.parameters;
  109350. for (var unif in unTreatedUniforms) {
  109351. var uniform = unTreatedUniforms[unif];
  109352. var type = uniform.type;
  109353. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  109354. if (uniform.semantic && !uniform.source && !uniform.node) {
  109355. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  109356. }
  109357. else if (uniform.semantic && (uniform.source || uniform.node)) {
  109358. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  109359. if (source === null) {
  109360. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  109361. }
  109362. if (source === null) {
  109363. continue;
  109364. }
  109365. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  109366. }
  109367. }
  109368. else {
  109369. var value = materialValues[technique.uniforms[unif]];
  109370. if (!value) {
  109371. continue;
  109372. }
  109373. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  109374. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  109375. if (texture === null || texture === undefined) {
  109376. continue;
  109377. }
  109378. shaderMaterial.getEffect().setTexture(unif, texture);
  109379. }
  109380. else {
  109381. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  109382. }
  109383. }
  109384. }
  109385. onSuccess(shaderMaterial);
  109386. };
  109387. /**
  109388. * Prepare uniforms to send the only one time
  109389. * Loads the appropriate textures
  109390. */
  109391. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  109392. var materialValues = material.values || technique.parameters;
  109393. var techniqueUniforms = technique.uniforms;
  109394. /**
  109395. * Prepare values here (not matrices)
  109396. */
  109397. for (var unif in unTreatedUniforms) {
  109398. var uniform = unTreatedUniforms[unif];
  109399. var type = uniform.type;
  109400. var value = materialValues[techniqueUniforms[unif]];
  109401. if (value === undefined) {
  109402. // In case the value is the same for all materials
  109403. value = uniform.value;
  109404. }
  109405. if (!value) {
  109406. continue;
  109407. }
  109408. var onLoadTexture = function (uniformName) {
  109409. return function (texture) {
  109410. if (uniform.value && uniformName) {
  109411. // Static uniform
  109412. shaderMaterial.setTexture(uniformName, texture);
  109413. delete unTreatedUniforms[uniformName];
  109414. }
  109415. };
  109416. };
  109417. // Texture (sampler2D)
  109418. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  109419. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  109420. }
  109421. // Others
  109422. else {
  109423. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  109424. // Static uniform
  109425. delete unTreatedUniforms[unif];
  109426. }
  109427. }
  109428. }
  109429. };
  109430. /**
  109431. * Shader compilation failed
  109432. */
  109433. var onShaderCompileError = function (program, shaderMaterial, onError) {
  109434. return function (effect, error) {
  109435. shaderMaterial.dispose(true);
  109436. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  109437. };
  109438. };
  109439. /**
  109440. * Shader compilation success
  109441. */
  109442. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  109443. return function (_) {
  109444. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  109445. shaderMaterial.onBind = function (mesh) {
  109446. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  109447. };
  109448. };
  109449. };
  109450. /**
  109451. * Returns the appropriate uniform if already handled by babylon
  109452. */
  109453. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  109454. for (var unif in technique.uniforms) {
  109455. var uniform = technique.uniforms[unif];
  109456. var uniformParameter = technique.parameters[uniform];
  109457. if (tokenizer.currentIdentifier === unif) {
  109458. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  109459. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  109460. if (transformIndex !== -1) {
  109461. delete unTreatedUniforms[unif];
  109462. return babylonTransforms[transformIndex];
  109463. }
  109464. }
  109465. }
  109466. }
  109467. return tokenizer.currentIdentifier;
  109468. };
  109469. /**
  109470. * All shaders loaded. Create materials one by one
  109471. */
  109472. var importMaterials = function (gltfRuntime) {
  109473. // Create materials
  109474. for (var mat in gltfRuntime.materials) {
  109475. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  109476. }
  109477. };
  109478. /**
  109479. * Implementation of the base glTF spec
  109480. */
  109481. var GLTFLoaderBase = /** @class */ (function () {
  109482. function GLTFLoaderBase() {
  109483. }
  109484. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  109485. var gltfRuntime = {
  109486. extensions: {},
  109487. accessors: {},
  109488. buffers: {},
  109489. bufferViews: {},
  109490. meshes: {},
  109491. lights: {},
  109492. cameras: {},
  109493. nodes: {},
  109494. images: {},
  109495. textures: {},
  109496. shaders: {},
  109497. programs: {},
  109498. samplers: {},
  109499. techniques: {},
  109500. materials: {},
  109501. animations: {},
  109502. skins: {},
  109503. extensionsUsed: [],
  109504. scenes: {},
  109505. buffersCount: 0,
  109506. shaderscount: 0,
  109507. scene: scene,
  109508. rootUrl: rootUrl,
  109509. loadedBufferCount: 0,
  109510. loadedBufferViews: {},
  109511. loadedShaderCount: 0,
  109512. importOnlyMeshes: false,
  109513. dummyNodes: []
  109514. };
  109515. // Parse
  109516. if (parsedData.extensions) {
  109517. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  109518. }
  109519. if (parsedData.extensionsUsed) {
  109520. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  109521. }
  109522. if (parsedData.buffers) {
  109523. parseBuffers(parsedData.buffers, gltfRuntime);
  109524. }
  109525. if (parsedData.bufferViews) {
  109526. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  109527. }
  109528. if (parsedData.accessors) {
  109529. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  109530. }
  109531. if (parsedData.meshes) {
  109532. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  109533. }
  109534. if (parsedData.lights) {
  109535. parseObject(parsedData.lights, "lights", gltfRuntime);
  109536. }
  109537. if (parsedData.cameras) {
  109538. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  109539. }
  109540. if (parsedData.nodes) {
  109541. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  109542. }
  109543. if (parsedData.images) {
  109544. parseObject(parsedData.images, "images", gltfRuntime);
  109545. }
  109546. if (parsedData.textures) {
  109547. parseObject(parsedData.textures, "textures", gltfRuntime);
  109548. }
  109549. if (parsedData.shaders) {
  109550. parseShaders(parsedData.shaders, gltfRuntime);
  109551. }
  109552. if (parsedData.programs) {
  109553. parseObject(parsedData.programs, "programs", gltfRuntime);
  109554. }
  109555. if (parsedData.samplers) {
  109556. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  109557. }
  109558. if (parsedData.techniques) {
  109559. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  109560. }
  109561. if (parsedData.materials) {
  109562. parseObject(parsedData.materials, "materials", gltfRuntime);
  109563. }
  109564. if (parsedData.animations) {
  109565. parseObject(parsedData.animations, "animations", gltfRuntime);
  109566. }
  109567. if (parsedData.skins) {
  109568. parseObject(parsedData.skins, "skins", gltfRuntime);
  109569. }
  109570. if (parsedData.scenes) {
  109571. gltfRuntime.scenes = parsedData.scenes;
  109572. }
  109573. if (parsedData.scene && parsedData.scenes) {
  109574. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  109575. }
  109576. return gltfRuntime;
  109577. };
  109578. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109579. var buffer = gltfRuntime.buffers[id];
  109580. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  109581. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  109582. }
  109583. else {
  109584. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  109585. if (request) {
  109586. onError(request.status + " " + request.statusText);
  109587. }
  109588. });
  109589. }
  109590. };
  109591. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109592. var texture = gltfRuntime.textures[id];
  109593. if (!texture || !texture.source) {
  109594. onError("");
  109595. return;
  109596. }
  109597. if (texture.babylonTexture) {
  109598. onSuccess(null);
  109599. return;
  109600. }
  109601. var source = gltfRuntime.images[texture.source];
  109602. if (BABYLON.Tools.IsBase64(source.uri)) {
  109603. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  109604. }
  109605. else {
  109606. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  109607. if (request) {
  109608. onError(request.status + " " + request.statusText);
  109609. }
  109610. });
  109611. }
  109612. };
  109613. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109614. var texture = gltfRuntime.textures[id];
  109615. if (texture.babylonTexture) {
  109616. onSuccess(texture.babylonTexture);
  109617. return;
  109618. }
  109619. var sampler = gltfRuntime.samplers[texture.sampler];
  109620. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  109621. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  109622. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  109623. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  109624. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  109625. var blob = new Blob([buffer]);
  109626. var blobURL = URL.createObjectURL(blob);
  109627. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  109628. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  109629. if (sampler.wrapS !== undefined) {
  109630. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  109631. }
  109632. if (sampler.wrapT !== undefined) {
  109633. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  109634. }
  109635. newTexture.name = id;
  109636. texture.babylonTexture = newTexture;
  109637. onSuccess(newTexture);
  109638. };
  109639. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109640. var shader = gltfRuntime.shaders[id];
  109641. if (BABYLON.Tools.IsBase64(shader.uri)) {
  109642. var shaderString = atob(shader.uri.split(",")[1]);
  109643. if (onSuccess) {
  109644. onSuccess(shaderString);
  109645. }
  109646. }
  109647. else {
  109648. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  109649. if (request && onError) {
  109650. onError(request.status + " " + request.statusText);
  109651. }
  109652. });
  109653. }
  109654. };
  109655. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109656. var material = gltfRuntime.materials[id];
  109657. if (!material.technique) {
  109658. if (onError) {
  109659. onError("No technique found.");
  109660. }
  109661. return;
  109662. }
  109663. var technique = gltfRuntime.techniques[material.technique];
  109664. if (!technique) {
  109665. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109666. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  109667. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109668. onSuccess(defaultMaterial);
  109669. return;
  109670. }
  109671. var program = gltfRuntime.programs[technique.program];
  109672. var states = technique.states;
  109673. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  109674. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  109675. var newVertexShader = "";
  109676. var newPixelShader = "";
  109677. var vertexTokenizer = new Tokenizer(vertexShader);
  109678. var pixelTokenizer = new Tokenizer(pixelShader);
  109679. var unTreatedUniforms = {};
  109680. var uniforms = [];
  109681. var attributes = [];
  109682. var samplers = [];
  109683. // Fill uniform, sampler2D and attributes
  109684. for (var unif in technique.uniforms) {
  109685. var uniform = technique.uniforms[unif];
  109686. var uniformParameter = technique.parameters[uniform];
  109687. unTreatedUniforms[unif] = uniformParameter;
  109688. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  109689. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  109690. if (transformIndex !== -1) {
  109691. uniforms.push(babylonTransforms[transformIndex]);
  109692. delete unTreatedUniforms[unif];
  109693. }
  109694. else {
  109695. uniforms.push(unif);
  109696. }
  109697. }
  109698. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  109699. samplers.push(unif);
  109700. }
  109701. else {
  109702. uniforms.push(unif);
  109703. }
  109704. }
  109705. for (var attr in technique.attributes) {
  109706. var attribute = technique.attributes[attr];
  109707. var attributeParameter = technique.parameters[attribute];
  109708. if (attributeParameter.semantic) {
  109709. attributes.push(getAttribute(attributeParameter));
  109710. }
  109711. }
  109712. // Configure vertex shader
  109713. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  109714. var tokenType = vertexTokenizer.currentToken;
  109715. if (tokenType !== ETokenType.IDENTIFIER) {
  109716. newVertexShader += vertexTokenizer.currentString;
  109717. continue;
  109718. }
  109719. var foundAttribute = false;
  109720. for (var attr in technique.attributes) {
  109721. var attribute = technique.attributes[attr];
  109722. var attributeParameter = technique.parameters[attribute];
  109723. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  109724. newVertexShader += getAttribute(attributeParameter);
  109725. foundAttribute = true;
  109726. break;
  109727. }
  109728. }
  109729. if (foundAttribute) {
  109730. continue;
  109731. }
  109732. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  109733. }
  109734. // Configure pixel shader
  109735. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  109736. var tokenType = pixelTokenizer.currentToken;
  109737. if (tokenType !== ETokenType.IDENTIFIER) {
  109738. newPixelShader += pixelTokenizer.currentString;
  109739. continue;
  109740. }
  109741. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  109742. }
  109743. // Create shader material
  109744. var shaderPath = {
  109745. vertex: program.vertexShader + id,
  109746. fragment: program.fragmentShader + id
  109747. };
  109748. var options = {
  109749. attributes: attributes,
  109750. uniforms: uniforms,
  109751. samplers: samplers,
  109752. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  109753. };
  109754. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  109755. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  109756. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  109757. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  109758. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  109759. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109760. if (states && states.functions) {
  109761. var functions = states.functions;
  109762. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  109763. shaderMaterial.backFaceCulling = false;
  109764. }
  109765. var blendFunc = functions.blendFuncSeparate;
  109766. if (blendFunc) {
  109767. 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) {
  109768. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  109769. }
  109770. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109771. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  109772. }
  109773. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109774. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  109775. }
  109776. 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) {
  109777. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  109778. }
  109779. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109780. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  109781. }
  109782. 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) {
  109783. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  109784. }
  109785. }
  109786. }
  109787. };
  109788. return GLTFLoaderBase;
  109789. }());
  109790. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  109791. /**
  109792. * glTF V1 Loader
  109793. */
  109794. var GLTFLoader = /** @class */ (function () {
  109795. function GLTFLoader() {
  109796. this.state = null;
  109797. }
  109798. GLTFLoader.RegisterExtension = function (extension) {
  109799. if (GLTFLoader.Extensions[extension.name]) {
  109800. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  109801. return;
  109802. }
  109803. GLTFLoader.Extensions[extension.name] = extension;
  109804. };
  109805. GLTFLoader.prototype.dispose = function () {
  109806. // do nothing
  109807. };
  109808. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  109809. var _this = this;
  109810. scene.useRightHandedSystem = true;
  109811. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109812. gltfRuntime.importOnlyMeshes = true;
  109813. if (meshesNames === "") {
  109814. gltfRuntime.importMeshesNames = [];
  109815. }
  109816. else if (typeof meshesNames === "string") {
  109817. gltfRuntime.importMeshesNames = [meshesNames];
  109818. }
  109819. else if (meshesNames && !(meshesNames instanceof Array)) {
  109820. gltfRuntime.importMeshesNames = [meshesNames];
  109821. }
  109822. else {
  109823. gltfRuntime.importMeshesNames = [];
  109824. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  109825. }
  109826. // Create nodes
  109827. _this._createNodes(gltfRuntime);
  109828. var meshes = new Array();
  109829. var skeletons = new Array();
  109830. // Fill arrays of meshes and skeletons
  109831. for (var nde in gltfRuntime.nodes) {
  109832. var node = gltfRuntime.nodes[nde];
  109833. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  109834. meshes.push(node.babylonNode);
  109835. }
  109836. }
  109837. for (var skl in gltfRuntime.skins) {
  109838. var skin = gltfRuntime.skins[skl];
  109839. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  109840. skeletons.push(skin.babylonSkeleton);
  109841. }
  109842. }
  109843. // Load buffers, shaders, materials, etc.
  109844. _this._loadBuffersAsync(gltfRuntime, function () {
  109845. _this._loadShadersAsync(gltfRuntime, function () {
  109846. importMaterials(gltfRuntime);
  109847. postLoad(gltfRuntime);
  109848. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109849. onSuccess(meshes, skeletons);
  109850. }
  109851. });
  109852. }, onProgress);
  109853. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109854. onSuccess(meshes, skeletons);
  109855. }
  109856. }, onError);
  109857. return true;
  109858. };
  109859. /**
  109860. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  109861. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  109862. * @param scene the scene the meshes should be added to
  109863. * @param data gltf data containing information of the meshes in a loaded file
  109864. * @param rootUrl root url to load from
  109865. * @param onProgress event that fires when loading progress has occured
  109866. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  109867. */
  109868. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109869. var _this = this;
  109870. return new Promise(function (resolve, reject) {
  109871. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  109872. resolve({
  109873. meshes: meshes,
  109874. particleSystems: [],
  109875. skeletons: skeletons,
  109876. animationGroups: []
  109877. });
  109878. }, onProgress, function (message) {
  109879. reject(new Error(message));
  109880. });
  109881. });
  109882. };
  109883. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  109884. var _this = this;
  109885. scene.useRightHandedSystem = true;
  109886. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109887. // Load runtime extensios
  109888. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  109889. // Create nodes
  109890. _this._createNodes(gltfRuntime);
  109891. // Load buffers, shaders, materials, etc.
  109892. _this._loadBuffersAsync(gltfRuntime, function () {
  109893. _this._loadShadersAsync(gltfRuntime, function () {
  109894. importMaterials(gltfRuntime);
  109895. postLoad(gltfRuntime);
  109896. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  109897. onSuccess();
  109898. }
  109899. });
  109900. });
  109901. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  109902. onSuccess();
  109903. }
  109904. }, onError);
  109905. }, onError);
  109906. };
  109907. /**
  109908. * Imports all objects from a loaded gltf file and adds them to the scene
  109909. * @param scene the scene the objects should be added to
  109910. * @param data gltf data containing information of the meshes in a loaded file
  109911. * @param rootUrl root url to load from
  109912. * @param onProgress event that fires when loading progress has occured
  109913. * @returns a promise which completes when objects have been loaded to the scene
  109914. */
  109915. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109916. var _this = this;
  109917. return new Promise(function (resolve, reject) {
  109918. _this._loadAsync(scene, data, rootUrl, function () {
  109919. resolve();
  109920. }, onProgress, function (message) {
  109921. reject(new Error(message));
  109922. });
  109923. });
  109924. };
  109925. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  109926. var hasShaders = false;
  109927. var processShader = function (sha, shader) {
  109928. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  109929. if (shaderString instanceof ArrayBuffer) {
  109930. return;
  109931. }
  109932. gltfRuntime.loadedShaderCount++;
  109933. if (shaderString) {
  109934. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  109935. }
  109936. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  109937. onload();
  109938. }
  109939. }, function () {
  109940. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  109941. });
  109942. };
  109943. for (var sha in gltfRuntime.shaders) {
  109944. hasShaders = true;
  109945. var shader = gltfRuntime.shaders[sha];
  109946. if (shader) {
  109947. processShader.bind(this, sha, shader)();
  109948. }
  109949. else {
  109950. BABYLON.Tools.Error("No shader named: " + sha);
  109951. }
  109952. }
  109953. if (!hasShaders) {
  109954. onload();
  109955. }
  109956. };
  109957. ;
  109958. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  109959. var hasBuffers = false;
  109960. var processBuffer = function (buf, buffer) {
  109961. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  109962. gltfRuntime.loadedBufferCount++;
  109963. if (bufferView) {
  109964. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  109965. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  109966. }
  109967. gltfRuntime.loadedBufferViews[buf] = bufferView;
  109968. }
  109969. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  109970. onLoad();
  109971. }
  109972. }, function () {
  109973. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  109974. });
  109975. };
  109976. for (var buf in gltfRuntime.buffers) {
  109977. hasBuffers = true;
  109978. var buffer = gltfRuntime.buffers[buf];
  109979. if (buffer) {
  109980. processBuffer.bind(this, buf, buffer)();
  109981. }
  109982. else {
  109983. BABYLON.Tools.Error("No buffer named: " + buf);
  109984. }
  109985. }
  109986. if (!hasBuffers) {
  109987. onLoad();
  109988. }
  109989. };
  109990. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  109991. var currentScene = gltfRuntime.currentScene;
  109992. if (currentScene) {
  109993. // Only one scene even if multiple scenes are defined
  109994. for (var i = 0; i < currentScene.nodes.length; i++) {
  109995. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109996. }
  109997. }
  109998. else {
  109999. // Load all scenes
  110000. for (var thing in gltfRuntime.scenes) {
  110001. currentScene = gltfRuntime.scenes[thing];
  110002. for (var i = 0; i < currentScene.nodes.length; i++) {
  110003. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  110004. }
  110005. }
  110006. }
  110007. };
  110008. GLTFLoader.Extensions = {};
  110009. return GLTFLoader;
  110010. }());
  110011. GLTF1.GLTFLoader = GLTFLoader;
  110012. ;
  110013. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  110014. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  110015. })(BABYLON || (BABYLON = {}));
  110016. //# sourceMappingURL=babylon.glTFLoader.js.map
  110017. var BABYLON;
  110018. (function (BABYLON) {
  110019. var GLTF1;
  110020. (function (GLTF1) {
  110021. /**
  110022. * Utils functions for GLTF
  110023. */
  110024. var GLTFUtils = /** @class */ (function () {
  110025. function GLTFUtils() {
  110026. }
  110027. /**
  110028. * Sets the given "parameter" matrix
  110029. * @param scene: the {BABYLON.Scene} object
  110030. * @param source: the source node where to pick the matrix
  110031. * @param parameter: the GLTF technique parameter
  110032. * @param uniformName: the name of the shader's uniform
  110033. * @param shaderMaterial: the shader material
  110034. */
  110035. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  110036. var mat = null;
  110037. if (parameter.semantic === "MODEL") {
  110038. mat = source.getWorldMatrix();
  110039. }
  110040. else if (parameter.semantic === "PROJECTION") {
  110041. mat = scene.getProjectionMatrix();
  110042. }
  110043. else if (parameter.semantic === "VIEW") {
  110044. mat = scene.getViewMatrix();
  110045. }
  110046. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  110047. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  110048. }
  110049. else if (parameter.semantic === "MODELVIEW") {
  110050. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  110051. }
  110052. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  110053. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  110054. }
  110055. else if (parameter.semantic === "MODELINVERSE") {
  110056. mat = source.getWorldMatrix().invert();
  110057. }
  110058. else if (parameter.semantic === "VIEWINVERSE") {
  110059. mat = scene.getViewMatrix().invert();
  110060. }
  110061. else if (parameter.semantic === "PROJECTIONINVERSE") {
  110062. mat = scene.getProjectionMatrix().invert();
  110063. }
  110064. else if (parameter.semantic === "MODELVIEWINVERSE") {
  110065. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  110066. }
  110067. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  110068. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  110069. }
  110070. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  110071. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  110072. }
  110073. else {
  110074. debugger;
  110075. }
  110076. if (mat) {
  110077. switch (parameter.type) {
  110078. case GLTF1.EParameterType.FLOAT_MAT2:
  110079. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  110080. break;
  110081. case GLTF1.EParameterType.FLOAT_MAT3:
  110082. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  110083. break;
  110084. case GLTF1.EParameterType.FLOAT_MAT4:
  110085. shaderMaterial.setMatrix(uniformName, mat);
  110086. break;
  110087. default: break;
  110088. }
  110089. }
  110090. };
  110091. /**
  110092. * Sets the given "parameter" matrix
  110093. * @param shaderMaterial: the shader material
  110094. * @param uniform: the name of the shader's uniform
  110095. * @param value: the value of the uniform
  110096. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  110097. */
  110098. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  110099. switch (type) {
  110100. case GLTF1.EParameterType.FLOAT:
  110101. shaderMaterial.setFloat(uniform, value);
  110102. return true;
  110103. case GLTF1.EParameterType.FLOAT_VEC2:
  110104. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  110105. return true;
  110106. case GLTF1.EParameterType.FLOAT_VEC3:
  110107. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  110108. return true;
  110109. case GLTF1.EParameterType.FLOAT_VEC4:
  110110. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  110111. return true;
  110112. default: return false;
  110113. }
  110114. };
  110115. /**
  110116. * Returns the wrap mode of the texture
  110117. * @param mode: the mode value
  110118. */
  110119. GLTFUtils.GetWrapMode = function (mode) {
  110120. switch (mode) {
  110121. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110122. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110123. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110124. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110125. }
  110126. };
  110127. /**
  110128. * Returns the byte stride giving an accessor
  110129. * @param accessor: the GLTF accessor objet
  110130. */
  110131. GLTFUtils.GetByteStrideFromType = function (accessor) {
  110132. // Needs this function since "byteStride" isn't requiered in glTF format
  110133. var type = accessor.type;
  110134. switch (type) {
  110135. case "VEC2": return 2;
  110136. case "VEC3": return 3;
  110137. case "VEC4": return 4;
  110138. case "MAT2": return 4;
  110139. case "MAT3": return 9;
  110140. case "MAT4": return 16;
  110141. default: return 1;
  110142. }
  110143. };
  110144. /**
  110145. * Returns the texture filter mode giving a mode value
  110146. * @param mode: the filter mode value
  110147. */
  110148. GLTFUtils.GetTextureFilterMode = function (mode) {
  110149. switch (mode) {
  110150. case GLTF1.ETextureFilterType.LINEAR:
  110151. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  110152. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  110153. case GLTF1.ETextureFilterType.NEAREST:
  110154. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  110155. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  110156. }
  110157. };
  110158. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  110159. var byteOffset = bufferView.byteOffset + byteOffset;
  110160. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  110161. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  110162. throw new Error("Buffer access is out of range");
  110163. }
  110164. var buffer = loadedBufferView.buffer;
  110165. byteOffset += loadedBufferView.byteOffset;
  110166. switch (componentType) {
  110167. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  110168. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  110169. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  110170. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  110171. default: return new Float32Array(buffer, byteOffset, byteLength);
  110172. }
  110173. };
  110174. /**
  110175. * Returns a buffer from its accessor
  110176. * @param gltfRuntime: the GLTF runtime
  110177. * @param accessor: the GLTF accessor
  110178. */
  110179. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  110180. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  110181. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  110182. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  110183. };
  110184. /**
  110185. * Decodes a buffer view into a string
  110186. * @param view: the buffer view
  110187. */
  110188. GLTFUtils.DecodeBufferToText = function (view) {
  110189. var result = "";
  110190. var length = view.byteLength;
  110191. for (var i = 0; i < length; ++i) {
  110192. result += String.fromCharCode(view[i]);
  110193. }
  110194. return result;
  110195. };
  110196. /**
  110197. * Returns the default material of gltf. Related to
  110198. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  110199. * @param scene: the Babylon.js scene
  110200. */
  110201. GLTFUtils.GetDefaultMaterial = function (scene) {
  110202. if (!GLTFUtils._DefaultMaterial) {
  110203. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  110204. "precision highp float;",
  110205. "",
  110206. "uniform mat4 worldView;",
  110207. "uniform mat4 projection;",
  110208. "",
  110209. "attribute vec3 position;",
  110210. "",
  110211. "void main(void)",
  110212. "{",
  110213. " gl_Position = projection * worldView * vec4(position, 1.0);",
  110214. "}"
  110215. ].join("\n");
  110216. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  110217. "precision highp float;",
  110218. "",
  110219. "uniform vec4 u_emission;",
  110220. "",
  110221. "void main(void)",
  110222. "{",
  110223. " gl_FragColor = u_emission;",
  110224. "}"
  110225. ].join("\n");
  110226. var shaderPath = {
  110227. vertex: "GLTFDefaultMaterial",
  110228. fragment: "GLTFDefaultMaterial"
  110229. };
  110230. var options = {
  110231. attributes: ["position"],
  110232. uniforms: ["worldView", "projection", "u_emission"],
  110233. samplers: new Array(),
  110234. needAlphaBlending: false
  110235. };
  110236. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  110237. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  110238. }
  110239. return GLTFUtils._DefaultMaterial;
  110240. };
  110241. // The GLTF default material
  110242. GLTFUtils._DefaultMaterial = null;
  110243. return GLTFUtils;
  110244. }());
  110245. GLTF1.GLTFUtils = GLTFUtils;
  110246. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  110247. })(BABYLON || (BABYLON = {}));
  110248. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  110249. var BABYLON;
  110250. (function (BABYLON) {
  110251. var GLTF1;
  110252. (function (GLTF1) {
  110253. var GLTFLoaderExtension = /** @class */ (function () {
  110254. function GLTFLoaderExtension(name) {
  110255. this._name = name;
  110256. }
  110257. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  110258. get: function () {
  110259. return this._name;
  110260. },
  110261. enumerable: true,
  110262. configurable: true
  110263. });
  110264. /**
  110265. * Defines an override for loading the runtime
  110266. * Return true to stop further extensions from loading the runtime
  110267. */
  110268. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  110269. return false;
  110270. };
  110271. /**
  110272. * Defines an onverride for creating gltf runtime
  110273. * Return true to stop further extensions from creating the runtime
  110274. */
  110275. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  110276. return false;
  110277. };
  110278. /**
  110279. * Defines an override for loading buffers
  110280. * Return true to stop further extensions from loading this buffer
  110281. */
  110282. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  110283. return false;
  110284. };
  110285. /**
  110286. * Defines an override for loading texture buffers
  110287. * Return true to stop further extensions from loading this texture data
  110288. */
  110289. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  110290. return false;
  110291. };
  110292. /**
  110293. * Defines an override for creating textures
  110294. * Return true to stop further extensions from loading this texture
  110295. */
  110296. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  110297. return false;
  110298. };
  110299. /**
  110300. * Defines an override for loading shader strings
  110301. * Return true to stop further extensions from loading this shader data
  110302. */
  110303. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  110304. return false;
  110305. };
  110306. /**
  110307. * Defines an override for loading materials
  110308. * Return true to stop further extensions from loading this material
  110309. */
  110310. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  110311. return false;
  110312. };
  110313. // ---------
  110314. // Utilities
  110315. // ---------
  110316. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  110317. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110318. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  110319. }, function () {
  110320. setTimeout(function () {
  110321. if (!onSuccess) {
  110322. return;
  110323. }
  110324. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  110325. });
  110326. });
  110327. };
  110328. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  110329. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110330. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  110331. }, function () {
  110332. setTimeout(function () {
  110333. onSuccess();
  110334. });
  110335. });
  110336. };
  110337. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  110338. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110339. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  110340. }, function () {
  110341. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  110342. });
  110343. };
  110344. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  110345. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  110346. if (buffer) {
  110347. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  110348. }
  110349. }, onError);
  110350. };
  110351. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  110352. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110353. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  110354. }, function () {
  110355. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  110356. });
  110357. };
  110358. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  110359. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110360. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  110361. }, function () {
  110362. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  110363. });
  110364. };
  110365. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  110366. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110367. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  110368. }, function () {
  110369. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  110370. });
  110371. };
  110372. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  110373. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  110374. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  110375. }, function () {
  110376. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  110377. });
  110378. };
  110379. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  110380. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  110381. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  110382. if (func(loaderExtension)) {
  110383. return;
  110384. }
  110385. }
  110386. defaultFunc();
  110387. };
  110388. return GLTFLoaderExtension;
  110389. }());
  110390. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  110391. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  110392. })(BABYLON || (BABYLON = {}));
  110393. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110394. var BABYLON;
  110395. (function (BABYLON) {
  110396. var GLTF1;
  110397. (function (GLTF1) {
  110398. var BinaryExtensionBufferName = "binary_glTF";
  110399. ;
  110400. ;
  110401. var GLTFBinaryExtension = /** @class */ (function (_super) {
  110402. __extends(GLTFBinaryExtension, _super);
  110403. function GLTFBinaryExtension() {
  110404. return _super.call(this, "KHR_binary_glTF") || this;
  110405. }
  110406. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  110407. var extensionsUsed = data.json.extensionsUsed;
  110408. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  110409. return false;
  110410. }
  110411. this._bin = data.bin;
  110412. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  110413. return true;
  110414. };
  110415. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  110416. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  110417. return false;
  110418. }
  110419. if (id !== BinaryExtensionBufferName) {
  110420. return false;
  110421. }
  110422. onSuccess(this._bin);
  110423. return true;
  110424. };
  110425. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  110426. var texture = gltfRuntime.textures[id];
  110427. var source = gltfRuntime.images[texture.source];
  110428. if (!source.extensions || !(this.name in source.extensions)) {
  110429. return false;
  110430. }
  110431. var sourceExt = source.extensions[this.name];
  110432. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  110433. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  110434. onSuccess(buffer);
  110435. return true;
  110436. };
  110437. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  110438. var shader = gltfRuntime.shaders[id];
  110439. if (!shader.extensions || !(this.name in shader.extensions)) {
  110440. return false;
  110441. }
  110442. var binaryExtensionShader = shader.extensions[this.name];
  110443. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  110444. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  110445. setTimeout(function () {
  110446. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  110447. onSuccess(shaderString);
  110448. });
  110449. return true;
  110450. };
  110451. return GLTFBinaryExtension;
  110452. }(GLTF1.GLTFLoaderExtension));
  110453. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  110454. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  110455. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  110456. })(BABYLON || (BABYLON = {}));
  110457. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  110458. var BABYLON;
  110459. (function (BABYLON) {
  110460. var GLTF1;
  110461. (function (GLTF1) {
  110462. ;
  110463. ;
  110464. ;
  110465. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  110466. __extends(GLTFMaterialsCommonExtension, _super);
  110467. function GLTFMaterialsCommonExtension() {
  110468. return _super.call(this, "KHR_materials_common") || this;
  110469. }
  110470. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  110471. if (!gltfRuntime.extensions)
  110472. return false;
  110473. var extension = gltfRuntime.extensions[this.name];
  110474. if (!extension)
  110475. return false;
  110476. // Create lights
  110477. var lights = extension.lights;
  110478. if (lights) {
  110479. for (var thing in lights) {
  110480. var light = lights[thing];
  110481. switch (light.type) {
  110482. case "ambient":
  110483. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  110484. var ambient = light.ambient;
  110485. if (ambient) {
  110486. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  110487. }
  110488. break;
  110489. case "point":
  110490. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  110491. var point = light.point;
  110492. if (point) {
  110493. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  110494. }
  110495. break;
  110496. case "directional":
  110497. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  110498. var directional = light.directional;
  110499. if (directional) {
  110500. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  110501. }
  110502. break;
  110503. case "spot":
  110504. var spot = light.spot;
  110505. if (spot) {
  110506. 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);
  110507. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  110508. }
  110509. break;
  110510. default:
  110511. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  110512. break;
  110513. }
  110514. }
  110515. }
  110516. return false;
  110517. };
  110518. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  110519. var material = gltfRuntime.materials[id];
  110520. if (!material || !material.extensions)
  110521. return false;
  110522. var extension = material.extensions[this.name];
  110523. if (!extension)
  110524. return false;
  110525. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  110526. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  110527. if (extension.technique === "CONSTANT") {
  110528. standardMaterial.disableLighting = true;
  110529. }
  110530. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  110531. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  110532. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  110533. // Ambient
  110534. if (typeof extension.values.ambient === "string") {
  110535. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  110536. }
  110537. else {
  110538. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  110539. }
  110540. // Diffuse
  110541. if (typeof extension.values.diffuse === "string") {
  110542. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  110543. }
  110544. else {
  110545. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  110546. }
  110547. // Emission
  110548. if (typeof extension.values.emission === "string") {
  110549. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  110550. }
  110551. else {
  110552. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  110553. }
  110554. // Specular
  110555. if (typeof extension.values.specular === "string") {
  110556. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  110557. }
  110558. else {
  110559. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  110560. }
  110561. return true;
  110562. };
  110563. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  110564. // Create buffer from texture url
  110565. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  110566. // Create texture from buffer
  110567. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  110568. }, onError);
  110569. };
  110570. return GLTFMaterialsCommonExtension;
  110571. }(GLTF1.GLTFLoaderExtension));
  110572. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  110573. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  110574. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  110575. })(BABYLON || (BABYLON = {}));
  110576. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  110577. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  110578. /**
  110579. * Defines the module used to import/export glTF 2.0 assets
  110580. */
  110581. var BABYLON;
  110582. (function (BABYLON) {
  110583. var GLTF2;
  110584. (function (GLTF2) {
  110585. /** @hidden */
  110586. var _ArrayItem = /** @class */ (function () {
  110587. function _ArrayItem() {
  110588. }
  110589. _ArrayItem.Assign = function (values) {
  110590. if (values) {
  110591. for (var index = 0; index < values.length; index++) {
  110592. values[index]._index = index;
  110593. }
  110594. }
  110595. };
  110596. return _ArrayItem;
  110597. }());
  110598. GLTF2._ArrayItem = _ArrayItem;
  110599. /** @hidden */
  110600. var GLTFLoader = /** @class */ (function () {
  110601. function GLTFLoader(parent) {
  110602. this._completePromises = new Array();
  110603. this._disposed = false;
  110604. this._state = null;
  110605. this._extensions = {};
  110606. this._defaultSampler = {};
  110607. this._defaultBabylonMaterials = {};
  110608. this._requests = new Array();
  110609. this._parent = parent;
  110610. }
  110611. GLTFLoader._Register = function (name, factory) {
  110612. if (GLTFLoader._ExtensionFactories[name]) {
  110613. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  110614. return;
  110615. }
  110616. GLTFLoader._ExtensionFactories[name] = factory;
  110617. // Keep the order of registration so that extensions registered first are called first.
  110618. GLTFLoader._ExtensionNames.push(name);
  110619. };
  110620. Object.defineProperty(GLTFLoader.prototype, "state", {
  110621. /**
  110622. * Loader state or null if the loader is not active.
  110623. */
  110624. get: function () {
  110625. return this._state;
  110626. },
  110627. enumerable: true,
  110628. configurable: true
  110629. });
  110630. GLTFLoader.prototype.dispose = function () {
  110631. if (this._disposed) {
  110632. return;
  110633. }
  110634. this._disposed = true;
  110635. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110636. var request = _a[_i];
  110637. request.abort();
  110638. }
  110639. this._requests.length = 0;
  110640. delete this._gltf;
  110641. delete this._babylonScene;
  110642. delete this._readyPromise;
  110643. this._completePromises.length = 0;
  110644. for (var name_1 in this._extensions) {
  110645. this._extensions[name_1].dispose();
  110646. }
  110647. this._extensions = {};
  110648. delete this._rootBabylonMesh;
  110649. delete this._progressCallback;
  110650. this._parent._clear();
  110651. };
  110652. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  110653. var _this = this;
  110654. return Promise.resolve().then(function () {
  110655. _this._babylonScene = scene;
  110656. _this._rootUrl = rootUrl;
  110657. _this._progressCallback = onProgress;
  110658. _this._loadData(data);
  110659. var nodes = null;
  110660. if (meshesNames) {
  110661. var nodeMap_1 = {};
  110662. if (_this._gltf.nodes) {
  110663. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  110664. var node = _a[_i];
  110665. if (node.name) {
  110666. nodeMap_1[node.name] = node._index;
  110667. }
  110668. }
  110669. }
  110670. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  110671. nodes = names.map(function (name) {
  110672. var node = nodeMap_1[name];
  110673. if (node === undefined) {
  110674. throw new Error("Failed to find node '" + name + "'");
  110675. }
  110676. return node;
  110677. });
  110678. }
  110679. return _this._loadAsync(nodes).then(function () {
  110680. return {
  110681. meshes: _this._getMeshes(),
  110682. particleSystems: [],
  110683. skeletons: _this._getSkeletons(),
  110684. animationGroups: _this._getAnimationGroups()
  110685. };
  110686. });
  110687. });
  110688. };
  110689. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  110690. var _this = this;
  110691. return Promise.resolve().then(function () {
  110692. _this._babylonScene = scene;
  110693. _this._rootUrl = rootUrl;
  110694. _this._progressCallback = onProgress;
  110695. _this._loadData(data);
  110696. return _this._loadAsync(null);
  110697. });
  110698. };
  110699. GLTFLoader.prototype._loadAsync = function (nodes) {
  110700. var _this = this;
  110701. return Promise.resolve().then(function () {
  110702. _this._parent._startPerformanceCounter("Loading => Ready");
  110703. _this._parent._startPerformanceCounter("Loading => Complete");
  110704. _this._state = BABYLON.GLTFLoaderState.LOADING;
  110705. _this._parent._log("Loading");
  110706. var readyDeferred = new BABYLON.Deferred();
  110707. _this._readyPromise = readyDeferred.promise;
  110708. _this._loadExtensions();
  110709. _this._checkExtensions();
  110710. var promises = new Array();
  110711. if (nodes) {
  110712. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  110713. }
  110714. else {
  110715. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  110716. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  110717. }
  110718. if (_this._parent.compileMaterials) {
  110719. promises.push(_this._compileMaterialsAsync());
  110720. }
  110721. if (_this._parent.compileShadowGenerators) {
  110722. promises.push(_this._compileShadowGeneratorsAsync());
  110723. }
  110724. var resultPromise = Promise.all(promises).then(function () {
  110725. _this._state = BABYLON.GLTFLoaderState.READY;
  110726. _this._parent._log("Ready");
  110727. readyDeferred.resolve();
  110728. _this._startAnimations();
  110729. });
  110730. resultPromise.then(function () {
  110731. _this._parent._endPerformanceCounter("Loading => Ready");
  110732. BABYLON.Tools.SetImmediate(function () {
  110733. if (!_this._disposed) {
  110734. Promise.all(_this._completePromises).then(function () {
  110735. _this._parent._endPerformanceCounter("Loading => Complete");
  110736. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  110737. _this._parent._log("Complete");
  110738. _this._parent.onCompleteObservable.notifyObservers(undefined);
  110739. _this._parent.onCompleteObservable.clear();
  110740. _this.dispose();
  110741. }).catch(function (error) {
  110742. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110743. _this.dispose();
  110744. });
  110745. }
  110746. });
  110747. });
  110748. return resultPromise;
  110749. }).catch(function (error) {
  110750. if (!_this._disposed) {
  110751. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110752. _this.dispose();
  110753. throw error;
  110754. }
  110755. });
  110756. };
  110757. GLTFLoader.prototype._loadData = function (data) {
  110758. this._gltf = data.json;
  110759. this._setupData();
  110760. if (data.bin) {
  110761. var buffers = this._gltf.buffers;
  110762. if (buffers && buffers[0] && !buffers[0].uri) {
  110763. var binaryBuffer = buffers[0];
  110764. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  110765. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  110766. }
  110767. binaryBuffer._data = Promise.resolve(data.bin);
  110768. }
  110769. else {
  110770. BABYLON.Tools.Warn("Unexpected BIN chunk");
  110771. }
  110772. }
  110773. };
  110774. GLTFLoader.prototype._setupData = function () {
  110775. _ArrayItem.Assign(this._gltf.accessors);
  110776. _ArrayItem.Assign(this._gltf.animations);
  110777. _ArrayItem.Assign(this._gltf.buffers);
  110778. _ArrayItem.Assign(this._gltf.bufferViews);
  110779. _ArrayItem.Assign(this._gltf.cameras);
  110780. _ArrayItem.Assign(this._gltf.images);
  110781. _ArrayItem.Assign(this._gltf.materials);
  110782. _ArrayItem.Assign(this._gltf.meshes);
  110783. _ArrayItem.Assign(this._gltf.nodes);
  110784. _ArrayItem.Assign(this._gltf.samplers);
  110785. _ArrayItem.Assign(this._gltf.scenes);
  110786. _ArrayItem.Assign(this._gltf.skins);
  110787. _ArrayItem.Assign(this._gltf.textures);
  110788. if (this._gltf.nodes) {
  110789. var nodeParents = {};
  110790. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  110791. var node = _a[_i];
  110792. if (node.children) {
  110793. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  110794. var index = _c[_b];
  110795. nodeParents[index] = node._index;
  110796. }
  110797. }
  110798. }
  110799. var rootNode = this._createRootNode();
  110800. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  110801. var node = _e[_d];
  110802. var parentIndex = nodeParents[node._index];
  110803. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  110804. }
  110805. }
  110806. };
  110807. GLTFLoader.prototype._loadExtensions = function () {
  110808. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110809. var name_2 = _a[_i];
  110810. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  110811. this._extensions[name_2] = extension;
  110812. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  110813. }
  110814. this._parent.onExtensionLoadedObservable.clear();
  110815. };
  110816. GLTFLoader.prototype._checkExtensions = function () {
  110817. if (this._gltf.extensionsRequired) {
  110818. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  110819. var name_3 = _a[_i];
  110820. var extension = this._extensions[name_3];
  110821. if (!extension || !extension.enabled) {
  110822. throw new Error("Require extension " + name_3 + " is not available");
  110823. }
  110824. }
  110825. }
  110826. };
  110827. GLTFLoader.prototype._createRootNode = function () {
  110828. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  110829. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  110830. switch (this._parent.coordinateSystemMode) {
  110831. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  110832. if (!this._babylonScene.useRightHandedSystem) {
  110833. rootNode.rotation = [0, 1, 0, 0];
  110834. rootNode.scale = [1, 1, -1];
  110835. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  110836. }
  110837. break;
  110838. }
  110839. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  110840. this._babylonScene.useRightHandedSystem = true;
  110841. break;
  110842. }
  110843. default: {
  110844. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  110845. }
  110846. }
  110847. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  110848. return rootNode;
  110849. };
  110850. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  110851. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  110852. if (extensionPromise) {
  110853. return extensionPromise;
  110854. }
  110855. var promises = new Array();
  110856. this._parent._logOpen(context + " " + (scene.name || ""));
  110857. if (scene.nodes) {
  110858. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  110859. var index = _a[_i];
  110860. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  110861. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  110862. }
  110863. }
  110864. promises.push(this._loadAnimationsAsync());
  110865. this._parent._logClose();
  110866. return Promise.all(promises).then(function () { });
  110867. };
  110868. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  110869. if (node._primitiveBabylonMeshes) {
  110870. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  110871. var babylonMesh = _a[_i];
  110872. callback(babylonMesh);
  110873. }
  110874. }
  110875. else {
  110876. callback(node._babylonMesh);
  110877. }
  110878. };
  110879. GLTFLoader.prototype._getMeshes = function () {
  110880. var meshes = new Array();
  110881. // Root mesh is always first.
  110882. meshes.push(this._rootBabylonMesh);
  110883. var nodes = this._gltf.nodes;
  110884. if (nodes) {
  110885. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  110886. var node = nodes_1[_i];
  110887. if (node._babylonMesh) {
  110888. meshes.push(node._babylonMesh);
  110889. }
  110890. if (node._primitiveBabylonMeshes) {
  110891. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  110892. var babylonMesh = _b[_a];
  110893. meshes.push(babylonMesh);
  110894. }
  110895. }
  110896. }
  110897. }
  110898. return meshes;
  110899. };
  110900. GLTFLoader.prototype._getSkeletons = function () {
  110901. var skeletons = new Array();
  110902. var skins = this._gltf.skins;
  110903. if (skins) {
  110904. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  110905. var skin = skins_1[_i];
  110906. if (skin._babylonSkeleton) {
  110907. skeletons.push(skin._babylonSkeleton);
  110908. }
  110909. }
  110910. }
  110911. return skeletons;
  110912. };
  110913. GLTFLoader.prototype._getAnimationGroups = function () {
  110914. var animationGroups = new Array();
  110915. var animations = this._gltf.animations;
  110916. if (animations) {
  110917. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  110918. var animation = animations_1[_i];
  110919. if (animation._babylonAnimationGroup) {
  110920. animationGroups.push(animation._babylonAnimationGroup);
  110921. }
  110922. }
  110923. }
  110924. return animationGroups;
  110925. };
  110926. GLTFLoader.prototype._startAnimations = function () {
  110927. switch (this._parent.animationStartMode) {
  110928. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  110929. // do nothing
  110930. break;
  110931. }
  110932. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  110933. var babylonAnimationGroups = this._getAnimationGroups();
  110934. if (babylonAnimationGroups.length !== 0) {
  110935. babylonAnimationGroups[0].start(true);
  110936. }
  110937. break;
  110938. }
  110939. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  110940. var babylonAnimationGroups = this._getAnimationGroups();
  110941. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  110942. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  110943. babylonAnimationGroup.start(true);
  110944. }
  110945. break;
  110946. }
  110947. default: {
  110948. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  110949. return;
  110950. }
  110951. }
  110952. };
  110953. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  110954. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  110955. if (extensionPromise) {
  110956. return extensionPromise;
  110957. }
  110958. if (node._babylonMesh) {
  110959. throw new Error(context + ": Invalid recursive node hierarchy");
  110960. }
  110961. var promises = new Array();
  110962. this._parent._logOpen(context + " " + (node.name || ""));
  110963. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  110964. node._babylonMesh = babylonMesh;
  110965. babylonMesh.setEnabled(false);
  110966. GLTFLoader._LoadTransform(node, babylonMesh);
  110967. if (node.mesh != undefined) {
  110968. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  110969. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  110970. }
  110971. if (node.camera != undefined) {
  110972. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  110973. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  110974. }
  110975. if (node.children) {
  110976. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  110977. var index = _a[_i];
  110978. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  110979. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  110980. }
  110981. }
  110982. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  110983. this._parent._logClose();
  110984. return Promise.all(promises).then(function () {
  110985. babylonMesh.setEnabled(true);
  110986. });
  110987. };
  110988. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  110989. var _this = this;
  110990. var promises = new Array();
  110991. this._parent._logOpen(context + " " + (mesh.name || ""));
  110992. var primitives = mesh.primitives;
  110993. if (!primitives || primitives.length === 0) {
  110994. throw new Error(context + ": Primitives are missing");
  110995. }
  110996. _ArrayItem.Assign(primitives);
  110997. if (primitives.length === 1) {
  110998. var primitive = primitives[0];
  110999. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  111000. }
  111001. else {
  111002. node._primitiveBabylonMeshes = [];
  111003. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  111004. var primitive = primitives_1[_i];
  111005. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  111006. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  111007. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  111008. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  111009. }
  111010. }
  111011. if (node.skin != undefined) {
  111012. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  111013. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  111014. }
  111015. this._parent._logClose();
  111016. return Promise.all(promises).then(function () {
  111017. _this._forEachPrimitive(node, function (babylonMesh) {
  111018. babylonMesh._refreshBoundingInfo(true);
  111019. });
  111020. });
  111021. };
  111022. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  111023. var _this = this;
  111024. var promises = new Array();
  111025. this._parent._logOpen("" + context);
  111026. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  111027. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  111028. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  111029. babylonGeometry.applyToMesh(babylonMesh);
  111030. });
  111031. }));
  111032. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  111033. if (primitive.material == undefined) {
  111034. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  111035. }
  111036. else {
  111037. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  111038. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111039. babylonMesh.material = babylonMaterial;
  111040. }));
  111041. }
  111042. this._parent._logClose();
  111043. return Promise.all(promises).then(function () { });
  111044. };
  111045. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  111046. var _this = this;
  111047. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  111048. if (extensionPromise) {
  111049. return extensionPromise;
  111050. }
  111051. var attributes = primitive.attributes;
  111052. if (!attributes) {
  111053. throw new Error(context + ": Attributes are missing");
  111054. }
  111055. var promises = new Array();
  111056. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  111057. if (primitive.indices == undefined) {
  111058. babylonMesh.isUnIndexed = true;
  111059. }
  111060. else {
  111061. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  111062. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  111063. babylonGeometry.setIndices(data);
  111064. }));
  111065. }
  111066. var loadAttribute = function (attribute, kind, callback) {
  111067. if (attributes[attribute] == undefined) {
  111068. return;
  111069. }
  111070. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  111071. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  111072. babylonMesh._delayInfo.push(kind);
  111073. }
  111074. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  111075. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  111076. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  111077. }));
  111078. if (callback) {
  111079. callback(accessor);
  111080. }
  111081. };
  111082. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  111083. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  111084. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  111085. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  111086. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  111087. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  111088. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  111089. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  111090. if (accessor.type === "VEC4" /* VEC4 */) {
  111091. babylonMesh.hasVertexAlpha = true;
  111092. }
  111093. });
  111094. return Promise.all(promises).then(function () {
  111095. return babylonGeometry;
  111096. });
  111097. };
  111098. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  111099. if (!primitive.targets) {
  111100. return;
  111101. }
  111102. if (node._numMorphTargets == undefined) {
  111103. node._numMorphTargets = primitive.targets.length;
  111104. }
  111105. else if (primitive.targets.length !== node._numMorphTargets) {
  111106. throw new Error(context + ": Primitives do not have the same number of targets");
  111107. }
  111108. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  111109. for (var index = 0; index < primitive.targets.length; index++) {
  111110. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  111111. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  111112. // TODO: tell the target whether it has positions, normals, tangents
  111113. }
  111114. };
  111115. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  111116. if (!primitive.targets) {
  111117. return Promise.resolve();
  111118. }
  111119. var promises = new Array();
  111120. var morphTargetManager = babylonMesh.morphTargetManager;
  111121. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  111122. var babylonMorphTarget = morphTargetManager.getTarget(index);
  111123. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  111124. }
  111125. return Promise.all(promises).then(function () { });
  111126. };
  111127. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  111128. var _this = this;
  111129. var promises = new Array();
  111130. var loadAttribute = function (attribute, kind, setData) {
  111131. if (attributes[attribute] == undefined) {
  111132. return;
  111133. }
  111134. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  111135. if (!babylonVertexBuffer) {
  111136. return;
  111137. }
  111138. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  111139. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  111140. setData(babylonVertexBuffer, data);
  111141. }));
  111142. };
  111143. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  111144. babylonVertexBuffer.forEach(data.length, function (value, index) {
  111145. data[index] += value;
  111146. });
  111147. babylonMorphTarget.setPositions(data);
  111148. });
  111149. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  111150. babylonVertexBuffer.forEach(data.length, function (value, index) {
  111151. data[index] += value;
  111152. });
  111153. babylonMorphTarget.setNormals(data);
  111154. });
  111155. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  111156. var dataIndex = 0;
  111157. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  111158. // Tangent data for morph targets is stored as xyz delta.
  111159. // The vertexData.tangent is stored as xyzw.
  111160. // So we need to skip every fourth vertexData.tangent.
  111161. if (((index + 1) % 4) !== 0) {
  111162. data[dataIndex++] += value;
  111163. }
  111164. });
  111165. babylonMorphTarget.setTangents(data);
  111166. });
  111167. return Promise.all(promises).then(function () { });
  111168. };
  111169. GLTFLoader._LoadTransform = function (node, babylonNode) {
  111170. var position = BABYLON.Vector3.Zero();
  111171. var rotation = BABYLON.Quaternion.Identity();
  111172. var scaling = BABYLON.Vector3.One();
  111173. if (node.matrix) {
  111174. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  111175. matrix.decompose(scaling, rotation, position);
  111176. }
  111177. else {
  111178. if (node.translation)
  111179. position = BABYLON.Vector3.FromArray(node.translation);
  111180. if (node.rotation)
  111181. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  111182. if (node.scale)
  111183. scaling = BABYLON.Vector3.FromArray(node.scale);
  111184. }
  111185. babylonNode.position = position;
  111186. babylonNode.rotationQuaternion = rotation;
  111187. babylonNode.scaling = scaling;
  111188. };
  111189. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  111190. var _this = this;
  111191. var assignSkeleton = function (skeleton) {
  111192. _this._forEachPrimitive(node, function (babylonMesh) {
  111193. babylonMesh.skeleton = skeleton;
  111194. });
  111195. // Ignore the TRS of skinned nodes.
  111196. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  111197. node._babylonMesh.parent = _this._rootBabylonMesh;
  111198. node._babylonMesh.position = BABYLON.Vector3.Zero();
  111199. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  111200. node._babylonMesh.scaling = BABYLON.Vector3.One();
  111201. };
  111202. if (skin._loaded) {
  111203. return skin._loaded.then(function () {
  111204. assignSkeleton(skin._babylonSkeleton);
  111205. });
  111206. }
  111207. var skeletonId = "skeleton" + skin._index;
  111208. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  111209. skin._babylonSkeleton = babylonSkeleton;
  111210. this._loadBones(context, skin);
  111211. assignSkeleton(babylonSkeleton);
  111212. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  111213. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  111214. }));
  111215. };
  111216. GLTFLoader.prototype._loadBones = function (context, skin) {
  111217. var babylonBones = {};
  111218. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  111219. var index = _a[_i];
  111220. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  111221. this._loadBone(node, skin, babylonBones);
  111222. }
  111223. };
  111224. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  111225. var babylonBone = babylonBones[node._index];
  111226. if (babylonBone) {
  111227. return babylonBone;
  111228. }
  111229. var babylonParentBone = null;
  111230. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  111231. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  111232. }
  111233. var boneIndex = skin.joints.indexOf(node._index);
  111234. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  111235. babylonBones[node._index] = babylonBone;
  111236. node._babylonBones = node._babylonBones || [];
  111237. node._babylonBones.push(babylonBone);
  111238. return babylonBone;
  111239. };
  111240. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  111241. if (skin.inverseBindMatrices == undefined) {
  111242. return Promise.resolve(null);
  111243. }
  111244. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  111245. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  111246. };
  111247. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  111248. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  111249. var babylonBone = _a[_i];
  111250. var baseMatrix = BABYLON.Matrix.Identity();
  111251. var boneIndex = babylonBone._index;
  111252. if (inverseBindMatricesData && boneIndex !== -1) {
  111253. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  111254. baseMatrix.invertToRef(baseMatrix);
  111255. }
  111256. var babylonParentBone = babylonBone.getParent();
  111257. if (babylonParentBone) {
  111258. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  111259. }
  111260. babylonBone.updateMatrix(baseMatrix, false, false);
  111261. babylonBone._updateDifferenceMatrix(undefined, false);
  111262. }
  111263. };
  111264. GLTFLoader.prototype._getNodeMatrix = function (node) {
  111265. return node.matrix ?
  111266. BABYLON.Matrix.FromArray(node.matrix) :
  111267. 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());
  111268. };
  111269. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  111270. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  111271. babylonCamera.parent = babylonMesh;
  111272. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  111273. switch (camera.type) {
  111274. case "perspective" /* PERSPECTIVE */: {
  111275. var perspective = camera.perspective;
  111276. if (!perspective) {
  111277. throw new Error(context + ": Camera perspective properties are missing");
  111278. }
  111279. babylonCamera.fov = perspective.yfov;
  111280. babylonCamera.minZ = perspective.znear;
  111281. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  111282. break;
  111283. }
  111284. case "orthographic" /* ORTHOGRAPHIC */: {
  111285. if (!camera.orthographic) {
  111286. throw new Error(context + ": Camera orthographic properties are missing");
  111287. }
  111288. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  111289. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  111290. babylonCamera.orthoRight = camera.orthographic.xmag;
  111291. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  111292. babylonCamera.orthoTop = camera.orthographic.ymag;
  111293. babylonCamera.minZ = camera.orthographic.znear;
  111294. babylonCamera.maxZ = camera.orthographic.zfar;
  111295. break;
  111296. }
  111297. default: {
  111298. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  111299. }
  111300. }
  111301. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  111302. };
  111303. GLTFLoader.prototype._loadAnimationsAsync = function () {
  111304. var animations = this._gltf.animations;
  111305. if (!animations) {
  111306. return Promise.resolve();
  111307. }
  111308. var promises = new Array();
  111309. for (var index = 0; index < animations.length; index++) {
  111310. var animation = animations[index];
  111311. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  111312. }
  111313. return Promise.all(promises).then(function () { });
  111314. };
  111315. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  111316. var _this = this;
  111317. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  111318. animation._babylonAnimationGroup = babylonAnimationGroup;
  111319. var promises = new Array();
  111320. _ArrayItem.Assign(animation.channels);
  111321. _ArrayItem.Assign(animation.samplers);
  111322. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  111323. var channel = _a[_i];
  111324. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  111325. }
  111326. return Promise.all(promises).then(function () {
  111327. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  111328. });
  111329. };
  111330. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  111331. var _this = this;
  111332. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  111333. // Ignore animations that have no animation targets.
  111334. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  111335. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  111336. return Promise.resolve();
  111337. }
  111338. // Ignore animations targeting TRS of skinned nodes.
  111339. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  111340. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  111341. return Promise.resolve();
  111342. }
  111343. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  111344. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  111345. var targetPath;
  111346. var animationType;
  111347. switch (channel.target.path) {
  111348. case "translation" /* TRANSLATION */: {
  111349. targetPath = "position";
  111350. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  111351. break;
  111352. }
  111353. case "rotation" /* ROTATION */: {
  111354. targetPath = "rotationQuaternion";
  111355. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  111356. break;
  111357. }
  111358. case "scale" /* SCALE */: {
  111359. targetPath = "scaling";
  111360. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  111361. break;
  111362. }
  111363. case "weights" /* WEIGHTS */: {
  111364. targetPath = "influence";
  111365. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  111366. break;
  111367. }
  111368. default: {
  111369. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  111370. }
  111371. }
  111372. var outputBufferOffset = 0;
  111373. var getNextOutputValue;
  111374. switch (targetPath) {
  111375. case "position": {
  111376. getNextOutputValue = function () {
  111377. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  111378. outputBufferOffset += 3;
  111379. return value;
  111380. };
  111381. break;
  111382. }
  111383. case "rotationQuaternion": {
  111384. getNextOutputValue = function () {
  111385. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  111386. outputBufferOffset += 4;
  111387. return value;
  111388. };
  111389. break;
  111390. }
  111391. case "scaling": {
  111392. getNextOutputValue = function () {
  111393. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  111394. outputBufferOffset += 3;
  111395. return value;
  111396. };
  111397. break;
  111398. }
  111399. case "influence": {
  111400. getNextOutputValue = function () {
  111401. var value = new Array(targetNode._numMorphTargets);
  111402. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  111403. value[i] = data.output[outputBufferOffset++];
  111404. }
  111405. return value;
  111406. };
  111407. break;
  111408. }
  111409. }
  111410. var getNextKey;
  111411. switch (data.interpolation) {
  111412. case "STEP" /* STEP */: {
  111413. getNextKey = function (frameIndex) { return ({
  111414. frame: data.input[frameIndex],
  111415. value: getNextOutputValue(),
  111416. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  111417. }); };
  111418. break;
  111419. }
  111420. case "LINEAR" /* LINEAR */: {
  111421. getNextKey = function (frameIndex) { return ({
  111422. frame: data.input[frameIndex],
  111423. value: getNextOutputValue()
  111424. }); };
  111425. break;
  111426. }
  111427. case "CUBICSPLINE" /* CUBICSPLINE */: {
  111428. getNextKey = function (frameIndex) { return ({
  111429. frame: data.input[frameIndex],
  111430. inTangent: getNextOutputValue(),
  111431. value: getNextOutputValue(),
  111432. outTangent: getNextOutputValue()
  111433. }); };
  111434. break;
  111435. }
  111436. }
  111437. var keys = new Array(data.input.length);
  111438. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  111439. keys[frameIndex] = getNextKey(frameIndex);
  111440. }
  111441. if (targetPath === "influence") {
  111442. var _loop_1 = function (targetIndex) {
  111443. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  111444. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  111445. babylonAnimation.setKeys(keys.map(function (key) { return ({
  111446. frame: key.frame,
  111447. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  111448. value: key.value[targetIndex],
  111449. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  111450. }); }));
  111451. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  111452. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  111453. var babylonAnimationClone = babylonAnimation.clone();
  111454. morphTarget.animations.push(babylonAnimationClone);
  111455. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  111456. });
  111457. };
  111458. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  111459. _loop_1(targetIndex);
  111460. }
  111461. }
  111462. else {
  111463. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  111464. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  111465. babylonAnimation.setKeys(keys);
  111466. if (targetNode._babylonBones) {
  111467. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  111468. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  111469. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  111470. babylonAnimationTarget.animations.push(babylonAnimation);
  111471. }
  111472. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  111473. }
  111474. else {
  111475. targetNode._babylonMesh.animations.push(babylonAnimation);
  111476. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  111477. }
  111478. }
  111479. });
  111480. };
  111481. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  111482. if (sampler._data) {
  111483. return sampler._data;
  111484. }
  111485. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  111486. switch (interpolation) {
  111487. case "STEP" /* STEP */:
  111488. case "LINEAR" /* LINEAR */:
  111489. case "CUBICSPLINE" /* CUBICSPLINE */: {
  111490. break;
  111491. }
  111492. default: {
  111493. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  111494. }
  111495. }
  111496. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  111497. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  111498. sampler._data = Promise.all([
  111499. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  111500. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  111501. ]).then(function (_a) {
  111502. var inputData = _a[0], outputData = _a[1];
  111503. return {
  111504. input: inputData,
  111505. interpolation: interpolation,
  111506. output: outputData,
  111507. };
  111508. });
  111509. return sampler._data;
  111510. };
  111511. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  111512. if (buffer._data) {
  111513. return buffer._data;
  111514. }
  111515. if (!buffer.uri) {
  111516. throw new Error(context + ": Uri is missing");
  111517. }
  111518. buffer._data = this._loadUriAsync(context, buffer.uri);
  111519. return buffer._data;
  111520. };
  111521. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  111522. if (bufferView._data) {
  111523. return bufferView._data;
  111524. }
  111525. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  111526. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  111527. try {
  111528. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  111529. }
  111530. catch (e) {
  111531. throw new Error(context + ": " + e.message);
  111532. }
  111533. });
  111534. return bufferView._data;
  111535. };
  111536. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  111537. if (accessor.type !== "SCALAR" /* SCALAR */) {
  111538. throw new Error(context + ": Invalid type " + accessor.type);
  111539. }
  111540. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  111541. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  111542. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  111543. throw new Error(context + ": Invalid component type " + accessor.componentType);
  111544. }
  111545. if (accessor._data) {
  111546. return accessor._data;
  111547. }
  111548. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  111549. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  111550. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  111551. });
  111552. return accessor._data;
  111553. };
  111554. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  111555. // TODO: support normalized and stride
  111556. var _this = this;
  111557. if (accessor.componentType !== 5126 /* FLOAT */) {
  111558. throw new Error("Invalid component type " + accessor.componentType);
  111559. }
  111560. if (accessor._data) {
  111561. return accessor._data;
  111562. }
  111563. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  111564. var length = numComponents * accessor.count;
  111565. if (accessor.bufferView == undefined) {
  111566. accessor._data = Promise.resolve(new Float32Array(length));
  111567. }
  111568. else {
  111569. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  111570. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  111571. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  111572. });
  111573. }
  111574. if (accessor.sparse) {
  111575. var sparse_1 = accessor.sparse;
  111576. accessor._data = accessor._data.then(function (data) {
  111577. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  111578. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  111579. return Promise.all([
  111580. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  111581. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  111582. ]).then(function (_a) {
  111583. var indicesData = _a[0], valuesData = _a[1];
  111584. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  111585. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  111586. var valuesIndex = 0;
  111587. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  111588. var dataIndex = indices[indicesIndex] * numComponents;
  111589. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  111590. data[dataIndex++] = values[valuesIndex++];
  111591. }
  111592. }
  111593. return data;
  111594. });
  111595. });
  111596. }
  111597. return accessor._data;
  111598. };
  111599. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  111600. var _this = this;
  111601. if (bufferView._babylonBuffer) {
  111602. return bufferView._babylonBuffer;
  111603. }
  111604. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  111605. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  111606. });
  111607. return bufferView._babylonBuffer;
  111608. };
  111609. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  111610. var _this = this;
  111611. if (accessor._babylonVertexBuffer) {
  111612. return accessor._babylonVertexBuffer;
  111613. }
  111614. if (accessor.sparse) {
  111615. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  111616. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  111617. });
  111618. }
  111619. else {
  111620. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  111621. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  111622. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  111623. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  111624. });
  111625. }
  111626. return accessor._babylonVertexBuffer;
  111627. };
  111628. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  111629. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  111630. if (!babylonMaterial) {
  111631. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  111632. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  111633. babylonMaterial.metallic = 1;
  111634. babylonMaterial.roughness = 1;
  111635. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111636. }
  111637. return babylonMaterial;
  111638. };
  111639. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  111640. var promises = new Array();
  111641. // Ensure metallic workflow
  111642. babylonMaterial.metallic = 1;
  111643. babylonMaterial.roughness = 1;
  111644. var properties = material.pbrMetallicRoughness;
  111645. if (properties) {
  111646. if (properties.baseColorFactor) {
  111647. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  111648. babylonMaterial.alpha = properties.baseColorFactor[3];
  111649. }
  111650. else {
  111651. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111652. }
  111653. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  111654. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  111655. if (properties.baseColorTexture) {
  111656. promises.push(this._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  111657. babylonMaterial.albedoTexture = texture;
  111658. }));
  111659. }
  111660. if (properties.metallicRoughnessTexture) {
  111661. promises.push(this._loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  111662. babylonMaterial.metallicTexture = texture;
  111663. }));
  111664. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  111665. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  111666. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  111667. }
  111668. }
  111669. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111670. return Promise.all(promises).then(function () { });
  111671. };
  111672. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111673. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  111674. if (extensionPromise) {
  111675. return extensionPromise;
  111676. }
  111677. material._babylonData = material._babylonData || {};
  111678. var babylonData = material._babylonData[babylonDrawMode];
  111679. if (!babylonData) {
  111680. this._parent._logOpen(context + " " + (material.name || ""));
  111681. var name_4 = material.name || "material" + material._index;
  111682. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  111683. babylonData = {
  111684. material: babylonMaterial,
  111685. meshes: [],
  111686. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  111687. };
  111688. material._babylonData[babylonDrawMode] = babylonData;
  111689. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111690. this._parent._logClose();
  111691. }
  111692. babylonData.meshes.push(babylonMesh);
  111693. babylonMesh.onDisposeObservable.addOnce(function () {
  111694. var index = babylonData.meshes.indexOf(babylonMesh);
  111695. if (index !== -1) {
  111696. babylonData.meshes.splice(index, 1);
  111697. }
  111698. });
  111699. assign(babylonData.material);
  111700. return babylonData.loaded;
  111701. };
  111702. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111703. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  111704. if (extensionPromise) {
  111705. return extensionPromise;
  111706. }
  111707. var promises = new Array();
  111708. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111709. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  111710. return Promise.all(promises).then(function () { });
  111711. };
  111712. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  111713. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  111714. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  111715. babylonMaterial.fillMode = drawMode;
  111716. babylonMaterial.enableSpecularAntiAliasing = true;
  111717. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  111718. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  111719. return babylonMaterial;
  111720. };
  111721. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  111722. var promises = new Array();
  111723. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  111724. if (material.doubleSided) {
  111725. babylonMaterial.backFaceCulling = false;
  111726. babylonMaterial.twoSidedLighting = true;
  111727. }
  111728. if (material.normalTexture) {
  111729. promises.push(this._loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  111730. babylonMaterial.bumpTexture = texture;
  111731. }));
  111732. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  111733. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  111734. if (material.normalTexture.scale != undefined) {
  111735. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  111736. }
  111737. }
  111738. if (material.occlusionTexture) {
  111739. promises.push(this._loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  111740. babylonMaterial.ambientTexture = texture;
  111741. }));
  111742. babylonMaterial.useAmbientInGrayScale = true;
  111743. if (material.occlusionTexture.strength != undefined) {
  111744. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  111745. }
  111746. }
  111747. if (material.emissiveTexture) {
  111748. promises.push(this._loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  111749. babylonMaterial.emissiveTexture = texture;
  111750. }));
  111751. }
  111752. return Promise.all(promises).then(function () { });
  111753. };
  111754. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  111755. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  111756. switch (alphaMode) {
  111757. case "OPAQUE" /* OPAQUE */: {
  111758. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  111759. break;
  111760. }
  111761. case "MASK" /* MASK */: {
  111762. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  111763. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  111764. if (babylonMaterial.albedoTexture) {
  111765. babylonMaterial.albedoTexture.hasAlpha = true;
  111766. }
  111767. break;
  111768. }
  111769. case "BLEND" /* BLEND */: {
  111770. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  111771. if (babylonMaterial.albedoTexture) {
  111772. babylonMaterial.albedoTexture.hasAlpha = true;
  111773. babylonMaterial.useAlphaFromAlbedoTexture = true;
  111774. }
  111775. break;
  111776. }
  111777. default: {
  111778. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  111779. }
  111780. }
  111781. };
  111782. GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  111783. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);
  111784. if (extensionPromise) {
  111785. return extensionPromise;
  111786. }
  111787. this._parent._logOpen("" + context);
  111788. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  111789. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  111790. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  111791. assign(babylonTexture);
  111792. });
  111793. this._parent._logClose();
  111794. return promise;
  111795. };
  111796. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  111797. var _this = this;
  111798. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);
  111799. if (extensionPromise) {
  111800. return extensionPromise;
  111801. }
  111802. var promises = new Array();
  111803. this._parent._logOpen(context + " " + (texture.name || ""));
  111804. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  111805. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  111806. var deferred = new BABYLON.Deferred();
  111807. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  111808. if (!_this._disposed) {
  111809. deferred.resolve();
  111810. }
  111811. }, function (message, exception) {
  111812. if (!_this._disposed) {
  111813. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  111814. }
  111815. });
  111816. promises.push(deferred.promise);
  111817. babylonTexture.name = texture.name || "texture" + texture._index;
  111818. babylonTexture.wrapU = samplerData.wrapU;
  111819. babylonTexture.wrapV = samplerData.wrapV;
  111820. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  111821. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (data) {
  111822. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  111823. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  111824. }));
  111825. assign(babylonTexture);
  111826. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  111827. this._parent._logClose();
  111828. return Promise.all(promises).then(function () { });
  111829. };
  111830. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  111831. if (!sampler._data) {
  111832. sampler._data = {
  111833. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  111834. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  111835. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  111836. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  111837. };
  111838. }
  111839. ;
  111840. return sampler._data;
  111841. };
  111842. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  111843. if (!image._data) {
  111844. this._parent._logOpen(context + " " + (image.name || ""));
  111845. if (image.uri) {
  111846. image._data = this._loadUriAsync(context, image.uri);
  111847. }
  111848. else {
  111849. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  111850. image._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  111851. }
  111852. this._parent._logClose();
  111853. }
  111854. return image._data;
  111855. };
  111856. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  111857. var _this = this;
  111858. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  111859. if (extensionPromise) {
  111860. return extensionPromise;
  111861. }
  111862. if (!GLTFLoader._ValidateUri(uri)) {
  111863. throw new Error(context + ": Uri '" + uri + "' is invalid");
  111864. }
  111865. if (BABYLON.Tools.IsBase64(uri)) {
  111866. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  111867. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  111868. return Promise.resolve(data);
  111869. }
  111870. this._parent._log("Loading " + uri);
  111871. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  111872. return new Promise(function (resolve, reject) {
  111873. if (!_this._disposed) {
  111874. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  111875. if (!_this._disposed) {
  111876. var data = new Uint8Array(fileData);
  111877. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  111878. resolve(data);
  111879. }
  111880. }, function (event) {
  111881. if (!_this._disposed) {
  111882. if (request_1) {
  111883. request_1._lengthComputable = event.lengthComputable;
  111884. request_1._loaded = event.loaded;
  111885. request_1._total = event.total;
  111886. }
  111887. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  111888. try {
  111889. _this._onProgress();
  111890. }
  111891. catch (e) {
  111892. reject(e);
  111893. }
  111894. }
  111895. }
  111896. }, _this._babylonScene.database, true, function (request, exception) {
  111897. if (!_this._disposed) {
  111898. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  111899. }
  111900. });
  111901. _this._requests.push(request_1);
  111902. }
  111903. });
  111904. });
  111905. };
  111906. GLTFLoader.prototype._onProgress = function () {
  111907. if (!this._progressCallback) {
  111908. return;
  111909. }
  111910. var lengthComputable = true;
  111911. var loaded = 0;
  111912. var total = 0;
  111913. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  111914. var request = _a[_i];
  111915. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  111916. return;
  111917. }
  111918. lengthComputable = lengthComputable && request._lengthComputable;
  111919. loaded += request._loaded;
  111920. total += request._total;
  111921. }
  111922. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  111923. };
  111924. GLTFLoader._GetProperty = function (context, array, index) {
  111925. if (!array || index == undefined || !array[index]) {
  111926. throw new Error(context + ": Failed to find index (" + index + ")");
  111927. }
  111928. return array[index];
  111929. };
  111930. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  111931. // Set defaults if undefined
  111932. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  111933. switch (mode) {
  111934. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  111935. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  111936. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  111937. default:
  111938. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  111939. return BABYLON.Texture.WRAP_ADDRESSMODE;
  111940. }
  111941. };
  111942. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  111943. // Set defaults if undefined
  111944. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  111945. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  111946. if (magFilter === 9729 /* LINEAR */) {
  111947. switch (minFilter) {
  111948. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  111949. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  111950. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  111951. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  111952. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  111953. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111954. default:
  111955. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111956. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111957. }
  111958. }
  111959. else {
  111960. if (magFilter !== 9728 /* NEAREST */) {
  111961. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  111962. }
  111963. switch (minFilter) {
  111964. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  111965. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  111966. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111967. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  111968. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  111969. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  111970. default:
  111971. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111972. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111973. }
  111974. }
  111975. };
  111976. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  111977. var buffer = bufferView.buffer;
  111978. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  111979. try {
  111980. switch (componentType) {
  111981. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  111982. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  111983. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  111984. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  111985. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  111986. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  111987. default: throw new Error("Invalid component type " + componentType);
  111988. }
  111989. }
  111990. catch (e) {
  111991. throw new Error(context + ": " + e);
  111992. }
  111993. };
  111994. GLTFLoader._GetNumComponents = function (context, type) {
  111995. switch (type) {
  111996. case "SCALAR": return 1;
  111997. case "VEC2": return 2;
  111998. case "VEC3": return 3;
  111999. case "VEC4": return 4;
  112000. case "MAT2": return 4;
  112001. case "MAT3": return 9;
  112002. case "MAT4": return 16;
  112003. }
  112004. throw new Error(context + ": Invalid type (" + type + ")");
  112005. };
  112006. GLTFLoader._ValidateUri = function (uri) {
  112007. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  112008. };
  112009. GLTFLoader._GetDrawMode = function (context, mode) {
  112010. if (mode == undefined) {
  112011. mode = 4 /* TRIANGLES */;
  112012. }
  112013. switch (mode) {
  112014. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  112015. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  112016. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  112017. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  112018. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  112019. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  112020. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  112021. }
  112022. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  112023. };
  112024. GLTFLoader.prototype._compileMaterialsAsync = function () {
  112025. var _this = this;
  112026. this._parent._startPerformanceCounter("Compile materials");
  112027. var promises = new Array();
  112028. if (this._gltf.materials) {
  112029. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  112030. var material = _a[_i];
  112031. if (material._babylonData) {
  112032. for (var babylonDrawMode in material._babylonData) {
  112033. var babylonData = material._babylonData[babylonDrawMode];
  112034. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  112035. var babylonMesh = _c[_b];
  112036. // Ensure nonUniformScaling is set if necessary.
  112037. babylonMesh.computeWorldMatrix(true);
  112038. var babylonMaterial = babylonData.material;
  112039. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  112040. if (this._parent.useClipPlane) {
  112041. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  112042. }
  112043. }
  112044. }
  112045. }
  112046. }
  112047. }
  112048. return Promise.all(promises).then(function () {
  112049. _this._parent._endPerformanceCounter("Compile materials");
  112050. });
  112051. };
  112052. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  112053. var _this = this;
  112054. this._parent._startPerformanceCounter("Compile shadow generators");
  112055. var promises = new Array();
  112056. var lights = this._babylonScene.lights;
  112057. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  112058. var light = lights_1[_i];
  112059. var generator = light.getShadowGenerator();
  112060. if (generator) {
  112061. promises.push(generator.forceCompilationAsync());
  112062. }
  112063. }
  112064. return Promise.all(promises).then(function () {
  112065. _this._parent._endPerformanceCounter("Compile shadow generators");
  112066. });
  112067. };
  112068. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  112069. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  112070. var name_5 = _a[_i];
  112071. var extension = this._extensions[name_5];
  112072. if (extension.enabled) {
  112073. var promise = actionAsync(extension);
  112074. if (promise) {
  112075. return promise;
  112076. }
  112077. }
  112078. }
  112079. return null;
  112080. };
  112081. GLTFLoader._ExtensionNames = new Array();
  112082. GLTFLoader._ExtensionFactories = {};
  112083. return GLTFLoader;
  112084. }());
  112085. GLTF2.GLTFLoader = GLTFLoader;
  112086. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  112087. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112088. })(BABYLON || (BABYLON = {}));
  112089. //# sourceMappingURL=babylon.glTFLoader.js.map
  112090. var BABYLON;
  112091. (function (BABYLON) {
  112092. var GLTF2;
  112093. (function (GLTF2) {
  112094. /**
  112095. * Abstract class that can be implemented to extend existing glTF loader behavior.
  112096. */
  112097. var GLTFLoaderExtension = /** @class */ (function () {
  112098. /**
  112099. * Creates new GLTFLoaderExtension
  112100. * @param loader defines the GLTFLoader to use
  112101. */
  112102. function GLTFLoaderExtension(loader) {
  112103. /**
  112104. * Gets or sets a boolean indicating if the extension is enabled
  112105. */
  112106. this.enabled = true;
  112107. this._loader = loader;
  112108. }
  112109. /**
  112110. * Release all resources
  112111. */
  112112. GLTFLoaderExtension.prototype.dispose = function () {
  112113. delete this._loader;
  112114. };
  112115. // #region Overridable Methods
  112116. /**
  112117. * Override this method to modify the default behavior for loading scenes.
  112118. * @hidden
  112119. */
  112120. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  112121. /**
  112122. * Override this method to modify the default behavior for loading nodes.
  112123. * @hidden
  112124. */
  112125. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  112126. /**
  112127. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  112128. * @hidden
  112129. */
  112130. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  112131. /**
  112132. * Override this method to modify the default behavior for loading materials.
  112133. * @hidden
  112134. */
  112135. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  112136. /**
  112137. * Override this method to modify the default behavior for loading material properties.
  112138. * @hidden
  112139. */
  112140. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  112141. /**
  112142. * Override this method to modify the default behavior for loading texture infos.
  112143. * @hidden
  112144. */
  112145. GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };
  112146. /**
  112147. * Override this method to modify the default behavior for loading textures.
  112148. * @hidden
  112149. */
  112150. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };
  112151. /**
  112152. * Override this method to modify the default behavior for loading uris.
  112153. * @hidden
  112154. */
  112155. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  112156. // #endregion
  112157. /**
  112158. * Helper method called by a loader extension to load an glTF extension.
  112159. * @hidden
  112160. */
  112161. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  112162. if (!property.extensions) {
  112163. return null;
  112164. }
  112165. var extensions = property.extensions;
  112166. var extension = extensions[this.name];
  112167. if (!extension) {
  112168. return null;
  112169. }
  112170. // Clear out the extension before executing the action to avoid infinite recursion.
  112171. delete extensions[this.name];
  112172. try {
  112173. return actionAsync(context + "/extensions/" + this.name, extension);
  112174. }
  112175. finally {
  112176. // Restore the extension after executing the action.
  112177. extensions[this.name] = extension;
  112178. }
  112179. };
  112180. /**
  112181. * Helper method called by the loader to allow extensions to override loading scenes.
  112182. * @hidden
  112183. */
  112184. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  112185. if (!property.extras) {
  112186. return null;
  112187. }
  112188. var extras = property.extras;
  112189. var value = extras[this.name];
  112190. if (value === undefined) {
  112191. return null;
  112192. }
  112193. // Clear out the extras value before executing the action to avoid infinite recursion.
  112194. delete extras[this.name];
  112195. try {
  112196. return actionAsync(context + "/extras/" + this.name, value);
  112197. }
  112198. finally {
  112199. // Restore the extras value after executing the action.
  112200. extras[this.name] = value;
  112201. }
  112202. };
  112203. /**
  112204. * Helper method called by the loader to allow extensions to override loading scenes.
  112205. * @hidden
  112206. */
  112207. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  112208. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  112209. };
  112210. /**
  112211. * Helper method called by the loader to allow extensions to override loading nodes.
  112212. * @hidden
  112213. */
  112214. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  112215. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  112216. };
  112217. /**
  112218. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  112219. * @hidden
  112220. */
  112221. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  112222. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  112223. };
  112224. /**
  112225. * Helper method called by the loader to allow extensions to override loading materials.
  112226. * @hidden
  112227. */
  112228. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  112229. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  112230. };
  112231. /**
  112232. * Helper method called by the loader to allow extensions to override loading material properties.
  112233. * @hidden
  112234. */
  112235. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  112236. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  112237. };
  112238. /**
  112239. * Helper method called by the loader to allow extensions to override loading texture infos.
  112240. * @hidden
  112241. */
  112242. GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {
  112243. return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });
  112244. };
  112245. /**
  112246. * Helper method called by the loader to allow extensions to override loading textures.
  112247. * @hidden
  112248. */
  112249. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {
  112250. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });
  112251. };
  112252. /**
  112253. * Helper method called by the loader to allow extensions to override loading uris.
  112254. * @hidden
  112255. */
  112256. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  112257. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  112258. };
  112259. return GLTFLoaderExtension;
  112260. }());
  112261. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  112262. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112263. })(BABYLON || (BABYLON = {}));
  112264. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  112265. var BABYLON;
  112266. (function (BABYLON) {
  112267. var GLTF2;
  112268. (function (GLTF2) {
  112269. var Extensions;
  112270. (function (Extensions) {
  112271. var NAME = "MSFT_lod";
  112272. /**
  112273. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  112274. */
  112275. var MSFT_lod = /** @class */ (function (_super) {
  112276. __extends(MSFT_lod, _super);
  112277. function MSFT_lod(loader) {
  112278. var _this = _super.call(this, loader) || this;
  112279. _this.name = NAME;
  112280. /**
  112281. * Maximum number of LODs to load, starting from the lowest LOD.
  112282. */
  112283. _this.maxLODsToLoad = Number.MAX_VALUE;
  112284. /**
  112285. * Observable raised when all node LODs of one level are loaded.
  112286. * The event data is the index of the loaded LOD starting from zero.
  112287. * Dispose the loader to cancel the loading of the next level of LODs.
  112288. */
  112289. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  112290. /**
  112291. * Observable raised when all material LODs of one level are loaded.
  112292. * The event data is the index of the loaded LOD starting from zero.
  112293. * Dispose the loader to cancel the loading of the next level of LODs.
  112294. */
  112295. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  112296. _this._nodeIndexLOD = null;
  112297. _this._nodeSignalLODs = new Array();
  112298. _this._nodePromiseLODs = new Array();
  112299. _this._materialIndexLOD = null;
  112300. _this._materialSignalLODs = new Array();
  112301. _this._materialPromiseLODs = new Array();
  112302. _this._loader._readyPromise.then(function () {
  112303. var _loop_1 = function (indexLOD) {
  112304. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  112305. if (indexLOD !== 0) {
  112306. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  112307. }
  112308. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  112309. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  112310. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  112311. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  112312. _this._nodeSignalLODs[indexLOD].resolve();
  112313. }
  112314. });
  112315. _this._loader._completePromises.push(promise);
  112316. };
  112317. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  112318. _loop_1(indexLOD);
  112319. }
  112320. var _loop_2 = function (indexLOD) {
  112321. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  112322. if (indexLOD !== 0) {
  112323. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  112324. }
  112325. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  112326. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  112327. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  112328. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  112329. _this._materialSignalLODs[indexLOD].resolve();
  112330. }
  112331. });
  112332. _this._loader._completePromises.push(promise);
  112333. };
  112334. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  112335. _loop_2(indexLOD);
  112336. }
  112337. });
  112338. return _this;
  112339. }
  112340. MSFT_lod.prototype.dispose = function () {
  112341. _super.prototype.dispose.call(this);
  112342. this._nodeIndexLOD = null;
  112343. this._nodeSignalLODs.length = 0;
  112344. this._nodePromiseLODs.length = 0;
  112345. this._materialIndexLOD = null;
  112346. this._materialSignalLODs.length = 0;
  112347. this._materialPromiseLODs.length = 0;
  112348. this.onMaterialLODsLoadedObservable.clear();
  112349. this.onNodeLODsLoadedObservable.clear();
  112350. };
  112351. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  112352. var _this = this;
  112353. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  112354. var firstPromise;
  112355. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  112356. _this._loader._parent._logOpen("" + extensionContext);
  112357. var _loop_3 = function (indexLOD) {
  112358. var nodeLOD = nodeLODs[indexLOD];
  112359. if (indexLOD !== 0) {
  112360. _this._nodeIndexLOD = indexLOD;
  112361. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  112362. }
  112363. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  112364. if (indexLOD !== 0) {
  112365. var previousNodeLOD = nodeLODs[indexLOD - 1];
  112366. if (previousNodeLOD._babylonMesh) {
  112367. previousNodeLOD._babylonMesh.dispose();
  112368. delete previousNodeLOD._babylonMesh;
  112369. _this._disposeUnusedMaterials();
  112370. }
  112371. }
  112372. });
  112373. if (indexLOD === 0) {
  112374. firstPromise = promise;
  112375. }
  112376. else {
  112377. _this._nodeIndexLOD = null;
  112378. }
  112379. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  112380. _this._nodePromiseLODs[indexLOD].push(promise);
  112381. };
  112382. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  112383. _loop_3(indexLOD);
  112384. }
  112385. _this._loader._parent._logClose();
  112386. return firstPromise;
  112387. });
  112388. };
  112389. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  112390. var _this = this;
  112391. // Don't load material LODs if already loading a node LOD.
  112392. if (this._nodeIndexLOD) {
  112393. return null;
  112394. }
  112395. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  112396. var firstPromise;
  112397. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  112398. _this._loader._parent._logOpen("" + extensionContext);
  112399. var _loop_4 = function (indexLOD) {
  112400. var materialLOD = materialLODs[indexLOD];
  112401. if (indexLOD !== 0) {
  112402. _this._materialIndexLOD = indexLOD;
  112403. }
  112404. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  112405. if (indexLOD !== 0) {
  112406. var babylonDataLOD = materialLOD._babylonData;
  112407. assign(babylonDataLOD[babylonDrawMode].material);
  112408. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  112409. if (previousBabylonDataLOD[babylonDrawMode]) {
  112410. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  112411. delete previousBabylonDataLOD[babylonDrawMode];
  112412. }
  112413. }
  112414. });
  112415. if (indexLOD === 0) {
  112416. firstPromise = promise;
  112417. }
  112418. else {
  112419. _this._materialIndexLOD = null;
  112420. }
  112421. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  112422. _this._materialPromiseLODs[indexLOD].push(promise);
  112423. };
  112424. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  112425. _loop_4(indexLOD);
  112426. }
  112427. _this._loader._parent._logClose();
  112428. return firstPromise;
  112429. });
  112430. };
  112431. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  112432. var _this = this;
  112433. // Defer the loading of uris if loading a material or node LOD.
  112434. if (this._materialIndexLOD !== null) {
  112435. this._loader._parent._log("deferred");
  112436. var previousIndexLOD = this._materialIndexLOD - 1;
  112437. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  112438. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  112439. return _this._loader._loadUriAsync(context, uri);
  112440. });
  112441. }
  112442. else if (this._nodeIndexLOD !== null) {
  112443. this._loader._parent._log("deferred");
  112444. var previousIndexLOD = this._nodeIndexLOD - 1;
  112445. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  112446. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  112447. return _this._loader._loadUriAsync(context, uri);
  112448. });
  112449. }
  112450. return null;
  112451. };
  112452. /**
  112453. * Gets an array of LOD properties from lowest to highest.
  112454. */
  112455. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  112456. if (this.maxLODsToLoad <= 0) {
  112457. throw new Error("maxLODsToLoad must be greater than zero");
  112458. }
  112459. var properties = new Array();
  112460. for (var i = ids.length - 1; i >= 0; i--) {
  112461. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  112462. if (properties.length === this.maxLODsToLoad) {
  112463. return properties;
  112464. }
  112465. }
  112466. properties.push(property);
  112467. return properties;
  112468. };
  112469. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  112470. var materials = this._loader._gltf.materials;
  112471. if (materials) {
  112472. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  112473. var material = materials_1[_i];
  112474. if (material._babylonData) {
  112475. for (var drawMode in material._babylonData) {
  112476. var babylonData = material._babylonData[drawMode];
  112477. if (babylonData.meshes.length === 0) {
  112478. babylonData.material.dispose(false, true);
  112479. delete material._babylonData[drawMode];
  112480. }
  112481. }
  112482. }
  112483. }
  112484. }
  112485. };
  112486. return MSFT_lod;
  112487. }(GLTF2.GLTFLoaderExtension));
  112488. Extensions.MSFT_lod = MSFT_lod;
  112489. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  112490. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112491. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112492. })(BABYLON || (BABYLON = {}));
  112493. //# sourceMappingURL=MSFT_lod.js.map
  112494. var BABYLON;
  112495. (function (BABYLON) {
  112496. var GLTF2;
  112497. (function (GLTF2) {
  112498. var Extensions;
  112499. (function (Extensions) {
  112500. var NAME = "MSFT_minecraftMesh";
  112501. /** @hidden */
  112502. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  112503. __extends(MSFT_minecraftMesh, _super);
  112504. function MSFT_minecraftMesh() {
  112505. var _this = _super !== null && _super.apply(this, arguments) || this;
  112506. _this.name = NAME;
  112507. return _this;
  112508. }
  112509. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  112510. var _this = this;
  112511. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  112512. if (value) {
  112513. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  112514. if (babylonMaterial.needAlphaBlending()) {
  112515. babylonMaterial.forceDepthWrite = true;
  112516. babylonMaterial.separateCullingPass = true;
  112517. }
  112518. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  112519. babylonMaterial.twoSidedLighting = true;
  112520. assign(babylonMaterial);
  112521. });
  112522. }
  112523. return null;
  112524. });
  112525. };
  112526. return MSFT_minecraftMesh;
  112527. }(GLTF2.GLTFLoaderExtension));
  112528. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  112529. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  112530. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112531. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112532. })(BABYLON || (BABYLON = {}));
  112533. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  112534. var BABYLON;
  112535. (function (BABYLON) {
  112536. var GLTF2;
  112537. (function (GLTF2) {
  112538. var Extensions;
  112539. (function (Extensions) {
  112540. var NAME = "MSFT_sRGBFactors";
  112541. /** @hidden */
  112542. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  112543. __extends(MSFT_sRGBFactors, _super);
  112544. function MSFT_sRGBFactors() {
  112545. var _this = _super !== null && _super.apply(this, arguments) || this;
  112546. _this.name = NAME;
  112547. return _this;
  112548. }
  112549. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  112550. var _this = this;
  112551. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  112552. if (value) {
  112553. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  112554. if (!babylonMaterial.albedoTexture) {
  112555. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  112556. }
  112557. if (!babylonMaterial.reflectivityTexture) {
  112558. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  112559. }
  112560. assign(babylonMaterial);
  112561. });
  112562. }
  112563. return null;
  112564. });
  112565. };
  112566. return MSFT_sRGBFactors;
  112567. }(GLTF2.GLTFLoaderExtension));
  112568. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  112569. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  112570. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112571. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112572. })(BABYLON || (BABYLON = {}));
  112573. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  112574. var BABYLON;
  112575. (function (BABYLON) {
  112576. var GLTF2;
  112577. (function (GLTF2) {
  112578. var Extensions;
  112579. (function (Extensions) {
  112580. var NAME = "KHR_draco_mesh_compression";
  112581. /**
  112582. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  112583. */
  112584. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  112585. __extends(KHR_draco_mesh_compression, _super);
  112586. function KHR_draco_mesh_compression(loader) {
  112587. var _this = _super.call(this, loader) || this;
  112588. _this.name = NAME;
  112589. _this._dracoCompression = null;
  112590. // Disable extension if decoder is not available.
  112591. if (!BABYLON.DracoCompression.DecoderAvailable) {
  112592. _this.enabled = false;
  112593. }
  112594. return _this;
  112595. }
  112596. KHR_draco_mesh_compression.prototype.dispose = function () {
  112597. if (this._dracoCompression) {
  112598. this._dracoCompression.dispose();
  112599. }
  112600. _super.prototype.dispose.call(this);
  112601. };
  112602. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  112603. var _this = this;
  112604. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  112605. if (primitive.mode != undefined) {
  112606. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  112607. primitive.mode !== 4 /* TRIANGLES */) {
  112608. throw new Error(context + ": Unsupported mode " + primitive.mode);
  112609. }
  112610. // TODO: handle triangle strips
  112611. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  112612. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  112613. }
  112614. }
  112615. var attributes = {};
  112616. var loadAttribute = function (name, kind) {
  112617. var uniqueId = extension.attributes[name];
  112618. if (uniqueId == undefined) {
  112619. return;
  112620. }
  112621. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  112622. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  112623. babylonMesh._delayInfo.push(kind);
  112624. }
  112625. attributes[kind] = uniqueId;
  112626. };
  112627. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  112628. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  112629. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  112630. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  112631. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  112632. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  112633. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  112634. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  112635. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  112636. if (!bufferView._dracoBabylonGeometry) {
  112637. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  112638. if (!_this._dracoCompression) {
  112639. _this._dracoCompression = new BABYLON.DracoCompression();
  112640. }
  112641. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  112642. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  112643. babylonVertexData.applyToGeometry(babylonGeometry);
  112644. return babylonGeometry;
  112645. }).catch(function (error) {
  112646. throw new Error(context + ": " + error.message);
  112647. });
  112648. });
  112649. }
  112650. return bufferView._dracoBabylonGeometry;
  112651. });
  112652. };
  112653. return KHR_draco_mesh_compression;
  112654. }(GLTF2.GLTFLoaderExtension));
  112655. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  112656. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  112657. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112658. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112659. })(BABYLON || (BABYLON = {}));
  112660. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  112661. var BABYLON;
  112662. (function (BABYLON) {
  112663. var GLTF2;
  112664. (function (GLTF2) {
  112665. var Extensions;
  112666. (function (Extensions) {
  112667. var NAME = "KHR_materials_pbrSpecularGlossiness";
  112668. /**
  112669. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  112670. */
  112671. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  112672. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  112673. function KHR_materials_pbrSpecularGlossiness() {
  112674. var _this = _super !== null && _super.apply(this, arguments) || this;
  112675. _this.name = NAME;
  112676. return _this;
  112677. }
  112678. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  112679. var _this = this;
  112680. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  112681. var promises = new Array();
  112682. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  112683. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  112684. return Promise.all(promises).then(function () { });
  112685. });
  112686. };
  112687. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  112688. var promises = new Array();
  112689. if (properties.diffuseFactor) {
  112690. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  112691. babylonMaterial.alpha = properties.diffuseFactor[3];
  112692. }
  112693. else {
  112694. babylonMaterial.albedoColor = BABYLON.Color3.White();
  112695. }
  112696. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  112697. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  112698. if (properties.diffuseTexture) {
  112699. promises.push(this._loader._loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  112700. babylonMaterial.albedoTexture = texture;
  112701. }));
  112702. }
  112703. if (properties.specularGlossinessTexture) {
  112704. promises.push(this._loader._loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  112705. babylonMaterial.reflectivityTexture = texture;
  112706. }));
  112707. babylonMaterial.reflectivityTexture.hasAlpha = true;
  112708. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  112709. }
  112710. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  112711. return Promise.all(promises).then(function () { });
  112712. };
  112713. return KHR_materials_pbrSpecularGlossiness;
  112714. }(GLTF2.GLTFLoaderExtension));
  112715. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  112716. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  112717. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112718. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112719. })(BABYLON || (BABYLON = {}));
  112720. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  112721. var BABYLON;
  112722. (function (BABYLON) {
  112723. var GLTF2;
  112724. (function (GLTF2) {
  112725. var Extensions;
  112726. (function (Extensions) {
  112727. var NAME = "KHR_materials_unlit";
  112728. /**
  112729. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  112730. */
  112731. var KHR_materials_unlit = /** @class */ (function (_super) {
  112732. __extends(KHR_materials_unlit, _super);
  112733. function KHR_materials_unlit() {
  112734. var _this = _super !== null && _super.apply(this, arguments) || this;
  112735. _this.name = NAME;
  112736. return _this;
  112737. }
  112738. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  112739. var _this = this;
  112740. return this._loadExtensionAsync(context, material, function () {
  112741. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  112742. });
  112743. };
  112744. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  112745. var promises = new Array();
  112746. babylonMaterial.unlit = true;
  112747. // Ensure metallic workflow
  112748. babylonMaterial.metallic = 1;
  112749. babylonMaterial.roughness = 1;
  112750. var properties = material.pbrMetallicRoughness;
  112751. if (properties) {
  112752. if (properties.baseColorFactor) {
  112753. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  112754. babylonMaterial.alpha = properties.baseColorFactor[3];
  112755. }
  112756. else {
  112757. babylonMaterial.albedoColor = BABYLON.Color3.White();
  112758. }
  112759. if (properties.baseColorTexture) {
  112760. promises.push(this._loader._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  112761. babylonMaterial.albedoTexture = texture;
  112762. }));
  112763. }
  112764. }
  112765. if (material.doubleSided) {
  112766. babylonMaterial.backFaceCulling = false;
  112767. babylonMaterial.twoSidedLighting = true;
  112768. }
  112769. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  112770. return Promise.all(promises).then(function () { });
  112771. };
  112772. return KHR_materials_unlit;
  112773. }(GLTF2.GLTFLoaderExtension));
  112774. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  112775. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  112776. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112777. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112778. })(BABYLON || (BABYLON = {}));
  112779. //# sourceMappingURL=KHR_materials_unlit.js.map
  112780. var BABYLON;
  112781. (function (BABYLON) {
  112782. var GLTF2;
  112783. (function (GLTF2) {
  112784. var Extensions;
  112785. (function (Extensions) {
  112786. var NAME = "KHR_lights";
  112787. var LightType;
  112788. (function (LightType) {
  112789. LightType["AMBIENT"] = "ambient";
  112790. LightType["DIRECTIONAL"] = "directional";
  112791. LightType["POINT"] = "point";
  112792. LightType["SPOT"] = "spot";
  112793. })(LightType || (LightType = {}));
  112794. /**
  112795. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  112796. */
  112797. var KHR_lights = /** @class */ (function (_super) {
  112798. __extends(KHR_lights, _super);
  112799. function KHR_lights() {
  112800. var _this = _super !== null && _super.apply(this, arguments) || this;
  112801. _this.name = NAME;
  112802. return _this;
  112803. }
  112804. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  112805. var _this = this;
  112806. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  112807. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  112808. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112809. if (light.type !== LightType.AMBIENT) {
  112810. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  112811. }
  112812. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  112813. return promise;
  112814. });
  112815. };
  112816. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  112817. var _this = this;
  112818. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  112819. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  112820. var babylonLight;
  112821. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112822. var name = node._babylonMesh.name;
  112823. switch (light.type) {
  112824. case LightType.AMBIENT: {
  112825. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  112826. }
  112827. case LightType.DIRECTIONAL: {
  112828. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  112829. break;
  112830. }
  112831. case LightType.POINT: {
  112832. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  112833. break;
  112834. }
  112835. case LightType.SPOT: {
  112836. // TODO: support inner and outer cone angles
  112837. //const innerConeAngle = spotLight.innerConeAngle || 0;
  112838. var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;
  112839. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  112840. break;
  112841. }
  112842. default: {
  112843. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  112844. }
  112845. }
  112846. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  112847. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  112848. babylonLight.parent = node._babylonMesh;
  112849. return promise;
  112850. });
  112851. };
  112852. Object.defineProperty(KHR_lights.prototype, "_lights", {
  112853. get: function () {
  112854. var extensions = this._loader._gltf.extensions;
  112855. if (!extensions || !extensions[this.name]) {
  112856. throw new Error("#/extensions: '" + this.name + "' not found");
  112857. }
  112858. var extension = extensions[this.name];
  112859. return extension.lights;
  112860. },
  112861. enumerable: true,
  112862. configurable: true
  112863. });
  112864. return KHR_lights;
  112865. }(GLTF2.GLTFLoaderExtension));
  112866. Extensions.KHR_lights = KHR_lights;
  112867. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  112868. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112869. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112870. })(BABYLON || (BABYLON = {}));
  112871. var BABYLON;
  112872. (function (BABYLON) {
  112873. var GLTF2;
  112874. (function (GLTF2) {
  112875. var Extensions;
  112876. (function (Extensions) {
  112877. var NAME = "KHR_texture_transform";
  112878. /**
  112879. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  112880. */
  112881. var KHR_texture_transform = /** @class */ (function (_super) {
  112882. __extends(KHR_texture_transform, _super);
  112883. function KHR_texture_transform() {
  112884. var _this = _super !== null && _super.apply(this, arguments) || this;
  112885. _this.name = NAME;
  112886. return _this;
  112887. }
  112888. KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  112889. var _this = this;
  112890. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  112891. return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  112892. if (extension.offset) {
  112893. babylonTexture.uOffset = extension.offset[0];
  112894. babylonTexture.vOffset = extension.offset[1];
  112895. }
  112896. // Always rotate around the origin.
  112897. babylonTexture.uRotationCenter = 0;
  112898. babylonTexture.vRotationCenter = 0;
  112899. if (extension.rotation) {
  112900. babylonTexture.wAng = -extension.rotation;
  112901. }
  112902. if (extension.scale) {
  112903. babylonTexture.uScale = extension.scale[0];
  112904. babylonTexture.vScale = extension.scale[1];
  112905. }
  112906. if (extension.texCoord != undefined) {
  112907. babylonTexture.coordinatesIndex = extension.texCoord;
  112908. }
  112909. assign(babylonTexture);
  112910. });
  112911. });
  112912. };
  112913. return KHR_texture_transform;
  112914. }(GLTF2.GLTFLoaderExtension));
  112915. Extensions.KHR_texture_transform = KHR_texture_transform;
  112916. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  112917. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112918. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112919. })(BABYLON || (BABYLON = {}));
  112920. var BABYLON;
  112921. (function (BABYLON) {
  112922. var GLTF2;
  112923. (function (GLTF2) {
  112924. var Extensions;
  112925. (function (Extensions) {
  112926. var NAME = "EXT_lights_imageBased";
  112927. /**
  112928. * [Specification](TODO) (Experimental)
  112929. */
  112930. var EXT_lights_imageBased = /** @class */ (function (_super) {
  112931. __extends(EXT_lights_imageBased, _super);
  112932. function EXT_lights_imageBased() {
  112933. var _this = _super !== null && _super.apply(this, arguments) || this;
  112934. _this.name = NAME;
  112935. return _this;
  112936. }
  112937. EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {
  112938. var _this = this;
  112939. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  112940. var promises = new Array();
  112941. promises.push(_this._loader._loadSceneAsync(context, scene));
  112942. _this._loader._parent._logOpen("" + extensionContext);
  112943. var light = GLTF2.GLTFLoader._GetProperty(extensionContext + "/light", _this._lights, extension.light);
  112944. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  112945. _this._loader._babylonScene.environmentTexture = texture;
  112946. }));
  112947. _this._loader._parent._logClose();
  112948. return Promise.all(promises).then(function () { });
  112949. });
  112950. };
  112951. EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {
  112952. var _this = this;
  112953. if (!light._loaded) {
  112954. var promises = new Array();
  112955. this._loader._parent._logOpen("" + context);
  112956. var imageData_1 = new Array(light.specularImages.length);
  112957. var _loop_1 = function (mipmap) {
  112958. var faces = light.specularImages[mipmap];
  112959. imageData_1[mipmap] = new Array(faces.length);
  112960. var _loop_2 = function (face) {
  112961. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  112962. this_1._loader._parent._logOpen("" + specularImageContext);
  112963. var index = faces[face];
  112964. var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);
  112965. promises.push(this_1._loader._loadImageAsync("#/images/" + index, image).then(function (data) {
  112966. imageData_1[mipmap][face] = data;
  112967. }));
  112968. this_1._loader._parent._logClose();
  112969. };
  112970. for (var face = 0; face < faces.length; face++) {
  112971. _loop_2(face);
  112972. }
  112973. };
  112974. var this_1 = this;
  112975. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  112976. _loop_1(mipmap);
  112977. }
  112978. this._loader._parent._logClose();
  112979. light._loaded = Promise.all(promises).then(function () {
  112980. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, light.specularImageSize);
  112981. light._babylonTexture = babylonTexture;
  112982. if (light.intensity != undefined) {
  112983. babylonTexture.level = light.intensity;
  112984. }
  112985. if (light.rotation) {
  112986. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  112987. // Invert the rotation so that positive rotation is counter-clockwise.
  112988. if (!_this._loader._babylonScene.useRightHandedSystem) {
  112989. rotation = BABYLON.Quaternion.Inverse(rotation);
  112990. }
  112991. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  112992. }
  112993. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  112994. sphericalHarmonics.scale(light.intensity);
  112995. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  112996. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  112997. // Compute the lod generation scale to fit exactly to the number of levels available.
  112998. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  112999. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  113000. });
  113001. }
  113002. return light._loaded.then(function () {
  113003. return light._babylonTexture;
  113004. });
  113005. };
  113006. Object.defineProperty(EXT_lights_imageBased.prototype, "_lights", {
  113007. get: function () {
  113008. var extensions = this._loader._gltf.extensions;
  113009. if (!extensions || !extensions[this.name]) {
  113010. throw new Error("#/extensions: '" + this.name + "' not found");
  113011. }
  113012. var extension = extensions[this.name];
  113013. return extension.lights;
  113014. },
  113015. enumerable: true,
  113016. configurable: true
  113017. });
  113018. return EXT_lights_imageBased;
  113019. }(GLTF2.GLTFLoaderExtension));
  113020. Extensions.EXT_lights_imageBased = EXT_lights_imageBased;
  113021. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });
  113022. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  113023. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  113024. })(BABYLON || (BABYLON = {}));
  113025. return BABYLON;
  113026. });
  113027. /***/ }),
  113028. /* 14 */
  113029. /***/ (function(module, exports, __webpack_require__) {
  113030. "use strict";
  113031. function __export(m) {
  113032. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  113033. }
  113034. Object.defineProperty(exports, "__esModule", { value: true });
  113035. __export(__webpack_require__(11));
  113036. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  113037. /***/ }),
  113038. /* 15 */
  113039. /***/ (function(module, exports, __webpack_require__) {
  113040. "use strict";
  113041. Object.defineProperty(exports, "__esModule", { value: true });
  113042. var babylonjs_1 = __webpack_require__(0);
  113043. /**
  113044. * A minimal WebGL cubemap descriptor
  113045. */
  113046. var TextureCube = /** @class */ (function () {
  113047. /**
  113048. * constructor
  113049. * @param internalFormat WebGL pixel format for the texture on the GPU
  113050. * @param type WebGL pixel type of the supplied data and texture on the GPU
  113051. * @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
  113052. */
  113053. function TextureCube(internalFormat, type, source) {
  113054. if (source === void 0) { source = []; }
  113055. this.internalFormat = internalFormat;
  113056. this.type = type;
  113057. this.source = source;
  113058. }
  113059. Object.defineProperty(TextureCube.prototype, "Width", {
  113060. /**
  113061. * Returns the width of a face of the texture or 0 if not available
  113062. */
  113063. get: function () {
  113064. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  113065. },
  113066. enumerable: true,
  113067. configurable: true
  113068. });
  113069. Object.defineProperty(TextureCube.prototype, "Height", {
  113070. /**
  113071. * Returns the height of a face of the texture or 0 if not available
  113072. */
  113073. get: function () {
  113074. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  113075. },
  113076. enumerable: true,
  113077. configurable: true
  113078. });
  113079. return TextureCube;
  113080. }());
  113081. exports.TextureCube = TextureCube;
  113082. /**
  113083. * A static class providing methods to aid working with Bablyon textures.
  113084. */
  113085. var TextureUtils = /** @class */ (function () {
  113086. function TextureUtils() {
  113087. }
  113088. /**
  113089. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  113090. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  113091. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  113092. * @param scene A Babylon Scene instance
  113093. * @param textureCube A Spectre TextureCube object
  113094. * @param parameters WebGL texture sampling parameters
  113095. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  113096. * @param environment Specifies that the texture will be used as an environment
  113097. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  113098. * @return Babylon cube texture
  113099. */
  113100. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  113101. if (environment === void 0) { environment = false; }
  113102. if (singleLod === void 0) { singleLod = false; }
  113103. if (!textureCube)
  113104. throw new Error("no texture cube provided");
  113105. var parameters;
  113106. if (environment) {
  113107. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  113108. }
  113109. else {
  113110. parameters = {
  113111. magFilter: 9728 /* NEAREST */,
  113112. minFilter: 9728 /* NEAREST */,
  113113. wrapS: 33071 /* CLAMP_TO_EDGE */,
  113114. wrapT: 33071 /* CLAMP_TO_EDGE */
  113115. };
  113116. }
  113117. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  113118. var babylonTexture = textureCube[key];
  113119. if (!babylonTexture) {
  113120. //initialize babylon texture
  113121. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  113122. if (environment) {
  113123. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  113124. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  113125. }
  113126. babylonTexture.gammaSpace = false;
  113127. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  113128. var glTexture_1 = internalTexture_1._webGLTexture;
  113129. //babylon properties
  113130. internalTexture_1.isCube = true;
  113131. internalTexture_1.generateMipMaps = false;
  113132. babylonTexture._texture = internalTexture_1;
  113133. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  113134. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  113135. var texturesUploaded_1 = 0;
  113136. var textureComplete = function () {
  113137. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  113138. };
  113139. var uploadFace = function (i, level, face) {
  113140. if (!glTexture_1)
  113141. return;
  113142. if (i === 0 && level === 0) {
  113143. internalTexture_1.width = face.width;
  113144. internalTexture_1.height = face.height;
  113145. }
  113146. var gl = (scene.getEngine())._gl;
  113147. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  113148. scene.getEngine()._unpackFlipY(false);
  113149. if (face instanceof HTMLElement || face instanceof ImageData) {
  113150. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  113151. }
  113152. else {
  113153. var textureData = face;
  113154. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  113155. }
  113156. texturesUploaded_1++;
  113157. if (textureComplete()) {
  113158. //generate mipmaps
  113159. if (automaticMipmaps) {
  113160. var w = face.width;
  113161. var h = face.height;
  113162. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  113163. if (isPot) {
  113164. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  113165. }
  113166. }
  113167. // Upload Separate lods in case there is no support for texture lod.
  113168. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  113169. var mipSlices = 3;
  113170. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  113171. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  113172. var lod = textureCube[lodKey];
  113173. //initialize lod texture if it doesn't already exist
  113174. if (lod == null && textureCube.Width) {
  113175. //compute LOD from even spacing in smoothness (matching shader calculation)
  113176. var smoothness = i_1 / (mipSlices - 1);
  113177. var roughness = 1 - smoothness;
  113178. var kMinimumVariance = 0.0005;
  113179. var alphaG = roughness * roughness + kMinimumVariance;
  113180. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  113181. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  113182. var maxLODIndex = textureCube.source.length - 1;
  113183. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  113184. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  113185. if (i_1 === 0) {
  113186. internalTexture_1._lodTextureLow = lod;
  113187. }
  113188. else if (i_1 === 1) {
  113189. internalTexture_1._lodTextureMid = lod;
  113190. }
  113191. else {
  113192. internalTexture_1._lodTextureHigh = lod;
  113193. }
  113194. textureCube[lodKey] = lod;
  113195. }
  113196. }
  113197. }
  113198. internalTexture_1.isReady = true;
  113199. }
  113200. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  113201. scene.getEngine().resetTextureCache();
  113202. };
  113203. var _loop_1 = function (i) {
  113204. var faces = textureCube.source[i];
  113205. var _loop_2 = function (j) {
  113206. var face = faces[j];
  113207. if (face instanceof HTMLImageElement && !face.complete) {
  113208. face.addEventListener('load', function () {
  113209. uploadFace(j, i, face);
  113210. }, false);
  113211. }
  113212. else {
  113213. uploadFace(j, i, face);
  113214. }
  113215. };
  113216. for (var j = 0; j < faces.length; j++) {
  113217. _loop_2(j);
  113218. }
  113219. };
  113220. for (var i = 0; i <= maxMipLevel_1; i++) {
  113221. _loop_1(i);
  113222. }
  113223. scene.getEngine().resetTextureCache();
  113224. babylonTexture.isReady = function () {
  113225. return textureComplete();
  113226. };
  113227. textureCube[key] = babylonTexture;
  113228. }
  113229. return babylonTexture;
  113230. };
  113231. /**
  113232. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  113233. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  113234. * @param parameters Spectre SamplingParameters to apply
  113235. */
  113236. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  113237. var scene = babylonTexture.getScene();
  113238. if (!scene)
  113239. return;
  113240. var gl = (scene.getEngine())._gl;
  113241. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  113242. var internalTexture = babylonTexture._texture;
  113243. if (!internalTexture)
  113244. return;
  113245. var glTexture = internalTexture._webGLTexture;
  113246. gl.bindTexture(target, glTexture);
  113247. if (parameters.magFilter != null)
  113248. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  113249. if (parameters.minFilter != null)
  113250. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  113251. if (parameters.wrapS != null)
  113252. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  113253. if (parameters.wrapT != null)
  113254. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  113255. //set babylon wrap modes from sampling parameter
  113256. switch (parameters.wrapS) {
  113257. case 10497 /* REPEAT */:
  113258. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  113259. break;
  113260. case 33071 /* CLAMP_TO_EDGE */:
  113261. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  113262. break;
  113263. case 33648 /* MIRRORED_REPEAT */:
  113264. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  113265. break;
  113266. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  113267. }
  113268. switch (parameters.wrapT) {
  113269. case 10497 /* REPEAT */:
  113270. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  113271. break;
  113272. case 33071 /* CLAMP_TO_EDGE */:
  113273. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  113274. break;
  113275. case 33648 /* MIRRORED_REPEAT */:
  113276. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  113277. break;
  113278. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  113279. }
  113280. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  113281. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  113282. if (anisotropicExt) {
  113283. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  113284. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  113285. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  113286. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  113287. }
  113288. }
  113289. gl.bindTexture(target, null);
  113290. scene.getEngine().resetTextureCache();
  113291. };
  113292. /**
  113293. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  113294. */
  113295. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  113296. /**
  113297. * Controls anisotropic filtering for deserialized textures.
  113298. */
  113299. TextureUtils.MaxAnisotropy = 4;
  113300. TextureUtils._EnvironmentSampling = {
  113301. magFilter: 9729 /* LINEAR */,
  113302. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  113303. wrapS: 33071 /* CLAMP_TO_EDGE */,
  113304. wrapT: 33071 /* CLAMP_TO_EDGE */,
  113305. maxAnisotropy: 1
  113306. };
  113307. TextureUtils._EnvironmentSingleMipSampling = {
  113308. magFilter: 9729 /* LINEAR */,
  113309. minFilter: 9729 /* LINEAR */,
  113310. wrapS: 33071 /* CLAMP_TO_EDGE */,
  113311. wrapT: 33071 /* CLAMP_TO_EDGE */,
  113312. maxAnisotropy: 1
  113313. };
  113314. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  113315. /**
  113316. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  113317. */
  113318. TextureUtils.EnvironmentLODScale = 0.8;
  113319. /**
  113320. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  113321. */
  113322. TextureUtils.EnvironmentLODOffset = 1.0;
  113323. return TextureUtils;
  113324. }());
  113325. exports.TextureUtils = TextureUtils;
  113326. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx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QUFhLEVBQUUscUJBQXFCLENBQUMsQ0FBQztnQkFDOUUsRUFBRSxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUUsY0FBYyxDQUFDLDBCQUEwQixFQUFFLGFBQWEsQ0FBQyxDQUFDO2dCQUNuRixjQUFjLENBQUMseUJBQXlCLEdBQUcsYUFBYSxDQUFDO2FBQzVEO1NBQ0o7UUFFRCxFQUFFLENBQUMsV0FBVyxDQUFDLE1BQU0sRUFBRSxJQUFJLENBQUMsQ0FBQztRQUM3QixLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsaUJBQWlCLEVBQUUsQ0FBQztJQUMxQyxDQUFDO0lBN05EOztPQUVHO0lBQ1csb0NBQXVCLEdBQUcsbUJBQW1CLENBQUM7SUFFNUQ7O09BRUc7SUFDVywwQkFBYSxHQUFHLENBQUMsQ0FBQztJQXVOakIsaUNBQW9CLEdBQXVCO1FBQ3RELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsaUNBQXVDO1FBQ2hELEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFYSwwQ0FBNkIsR0FBdUI7UUFDL0QsU0FBUyxtQkFBeUI7UUFDbEMsU0FBUyxtQkFBeUI7UUFDbEMsS0FBSywyQkFBK0I7UUFDcEMsS0FBSywyQkFBK0I7UUFDcEMsYUFBYSxFQUFFLENBQUM7S0FDbkIsQ0FBQztJQUVGLGdGQUFnRjtJQUNoRjs7T0FFRztJQUNXLGdDQUFtQixHQUFHLEdBQUcsQ0FBQztJQUN4Qzs7T0FFRztJQUNXLGlDQUFvQixHQUFHLEdBQUcsQ0FBQztJQUM3QyxtQkFBQztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  113327. /***/ }),
  113328. /* 16 */
  113329. /***/ (function(module, exports, __webpack_require__) {
  113330. "use strict";
  113331. Object.defineProperty(exports, "__esModule", { value: true });
  113332. var extended_1 = __webpack_require__(62);
  113333. var cache = {};
  113334. /**
  113335. *
  113336. * @param name the name of the custom optimizer configuration
  113337. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  113338. */
  113339. function getCustomOptimizerByName(name, upgrade) {
  113340. if (!cache[name]) {
  113341. switch (name) {
  113342. case 'extended':
  113343. if (upgrade) {
  113344. return extended_1.extendedUpgrade;
  113345. }
  113346. else {
  113347. return extended_1.extendedDegrade;
  113348. }
  113349. }
  113350. }
  113351. return cache[name];
  113352. }
  113353. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  113354. function registerCustomOptimizer(name, optimizer) {
  113355. cache[name] = optimizer;
  113356. }
  113357. exports.registerCustomOptimizer = registerCustomOptimizer;
  113358. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDO0FBRUQsaUNBQXdDLElBQVksRUFBRSxTQUFrRDtJQUNwRyxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsU0FBUyxDQUFDO0FBQzVCLENBQUM7QUFGRCwwREFFQyJ9
  113359. /***/ }),
  113360. /* 17 */
  113361. /***/ (function(module, exports, __webpack_require__) {
  113362. /**!
  113363. @license
  113364. handlebars v4.0.11
  113365. Copyright (C) 2011-2017 by Yehuda Katz
  113366. Permission is hereby granted, free of charge, to any person obtaining a copy
  113367. of this software and associated documentation files (the "Software"), to deal
  113368. in the Software without restriction, including without limitation the rights
  113369. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  113370. copies of the Software, and to permit persons to whom the Software is
  113371. furnished to do so, subject to the following conditions:
  113372. The above copyright notice and this permission notice shall be included in
  113373. all copies or substantial portions of the Software.
  113374. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  113375. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  113376. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  113377. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  113378. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  113379. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  113380. THE SOFTWARE.
  113381. */
  113382. (function webpackUniversalModuleDefinition(root, factory) {
  113383. if(true)
  113384. module.exports = factory();
  113385. else if(typeof define === 'function' && define.amd)
  113386. define([], factory);
  113387. else if(typeof exports === 'object')
  113388. exports["Handlebars"] = factory();
  113389. else
  113390. root["Handlebars"] = factory();
  113391. })(this, function() {
  113392. return /******/ (function(modules) { // webpackBootstrap
  113393. /******/ // The module cache
  113394. /******/ var installedModules = {};
  113395. /******/ // The require function
  113396. /******/ function __webpack_require__(moduleId) {
  113397. /******/ // Check if module is in cache
  113398. /******/ if(installedModules[moduleId])
  113399. /******/ return installedModules[moduleId].exports;
  113400. /******/ // Create a new module (and put it into the cache)
  113401. /******/ var module = installedModules[moduleId] = {
  113402. /******/ exports: {},
  113403. /******/ id: moduleId,
  113404. /******/ loaded: false
  113405. /******/ };
  113406. /******/ // Execute the module function
  113407. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  113408. /******/ // Flag the module as loaded
  113409. /******/ module.loaded = true;
  113410. /******/ // Return the exports of the module
  113411. /******/ return module.exports;
  113412. /******/ }
  113413. /******/ // expose the modules object (__webpack_modules__)
  113414. /******/ __webpack_require__.m = modules;
  113415. /******/ // expose the module cache
  113416. /******/ __webpack_require__.c = installedModules;
  113417. /******/ // __webpack_public_path__
  113418. /******/ __webpack_require__.p = "";
  113419. /******/ // Load entry module and return exports
  113420. /******/ return __webpack_require__(0);
  113421. /******/ })
  113422. /************************************************************************/
  113423. /******/ ([
  113424. /* 0 */
  113425. /***/ (function(module, exports, __webpack_require__) {
  113426. 'use strict';
  113427. var _interopRequireDefault = __webpack_require__(1)['default'];
  113428. exports.__esModule = true;
  113429. var _handlebarsRuntime = __webpack_require__(2);
  113430. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  113431. // Compiler imports
  113432. var _handlebarsCompilerAst = __webpack_require__(35);
  113433. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  113434. var _handlebarsCompilerBase = __webpack_require__(36);
  113435. var _handlebarsCompilerCompiler = __webpack_require__(41);
  113436. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  113437. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  113438. var _handlebarsCompilerVisitor = __webpack_require__(39);
  113439. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  113440. var _handlebarsNoConflict = __webpack_require__(34);
  113441. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113442. var _create = _handlebarsRuntime2['default'].create;
  113443. function create() {
  113444. var hb = _create();
  113445. hb.compile = function (input, options) {
  113446. return _handlebarsCompilerCompiler.compile(input, options, hb);
  113447. };
  113448. hb.precompile = function (input, options) {
  113449. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  113450. };
  113451. hb.AST = _handlebarsCompilerAst2['default'];
  113452. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  113453. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  113454. hb.Parser = _handlebarsCompilerBase.parser;
  113455. hb.parse = _handlebarsCompilerBase.parse;
  113456. return hb;
  113457. }
  113458. var inst = create();
  113459. inst.create = create;
  113460. _handlebarsNoConflict2['default'](inst);
  113461. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  113462. inst['default'] = inst;
  113463. exports['default'] = inst;
  113464. module.exports = exports['default'];
  113465. /***/ }),
  113466. /* 1 */
  113467. /***/ (function(module, exports) {
  113468. "use strict";
  113469. exports["default"] = function (obj) {
  113470. return obj && obj.__esModule ? obj : {
  113471. "default": obj
  113472. };
  113473. };
  113474. exports.__esModule = true;
  113475. /***/ }),
  113476. /* 2 */
  113477. /***/ (function(module, exports, __webpack_require__) {
  113478. 'use strict';
  113479. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113480. var _interopRequireDefault = __webpack_require__(1)['default'];
  113481. exports.__esModule = true;
  113482. var _handlebarsBase = __webpack_require__(4);
  113483. var base = _interopRequireWildcard(_handlebarsBase);
  113484. // Each of these augment the Handlebars object. No need to setup here.
  113485. // (This is done to easily share code between commonjs and browse envs)
  113486. var _handlebarsSafeString = __webpack_require__(21);
  113487. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  113488. var _handlebarsException = __webpack_require__(6);
  113489. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  113490. var _handlebarsUtils = __webpack_require__(5);
  113491. var Utils = _interopRequireWildcard(_handlebarsUtils);
  113492. var _handlebarsRuntime = __webpack_require__(22);
  113493. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  113494. var _handlebarsNoConflict = __webpack_require__(34);
  113495. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113496. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  113497. function create() {
  113498. var hb = new base.HandlebarsEnvironment();
  113499. Utils.extend(hb, base);
  113500. hb.SafeString = _handlebarsSafeString2['default'];
  113501. hb.Exception = _handlebarsException2['default'];
  113502. hb.Utils = Utils;
  113503. hb.escapeExpression = Utils.escapeExpression;
  113504. hb.VM = runtime;
  113505. hb.template = function (spec) {
  113506. return runtime.template(spec, hb);
  113507. };
  113508. return hb;
  113509. }
  113510. var inst = create();
  113511. inst.create = create;
  113512. _handlebarsNoConflict2['default'](inst);
  113513. inst['default'] = inst;
  113514. exports['default'] = inst;
  113515. module.exports = exports['default'];
  113516. /***/ }),
  113517. /* 3 */
  113518. /***/ (function(module, exports) {
  113519. "use strict";
  113520. exports["default"] = function (obj) {
  113521. if (obj && obj.__esModule) {
  113522. return obj;
  113523. } else {
  113524. var newObj = {};
  113525. if (obj != null) {
  113526. for (var key in obj) {
  113527. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  113528. }
  113529. }
  113530. newObj["default"] = obj;
  113531. return newObj;
  113532. }
  113533. };
  113534. exports.__esModule = true;
  113535. /***/ }),
  113536. /* 4 */
  113537. /***/ (function(module, exports, __webpack_require__) {
  113538. 'use strict';
  113539. var _interopRequireDefault = __webpack_require__(1)['default'];
  113540. exports.__esModule = true;
  113541. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  113542. var _utils = __webpack_require__(5);
  113543. var _exception = __webpack_require__(6);
  113544. var _exception2 = _interopRequireDefault(_exception);
  113545. var _helpers = __webpack_require__(10);
  113546. var _decorators = __webpack_require__(18);
  113547. var _logger = __webpack_require__(20);
  113548. var _logger2 = _interopRequireDefault(_logger);
  113549. var VERSION = '4.0.11';
  113550. exports.VERSION = VERSION;
  113551. var COMPILER_REVISION = 7;
  113552. exports.COMPILER_REVISION = COMPILER_REVISION;
  113553. var REVISION_CHANGES = {
  113554. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  113555. 2: '== 1.0.0-rc.3',
  113556. 3: '== 1.0.0-rc.4',
  113557. 4: '== 1.x.x',
  113558. 5: '== 2.0.0-alpha.x',
  113559. 6: '>= 2.0.0-beta.1',
  113560. 7: '>= 4.0.0'
  113561. };
  113562. exports.REVISION_CHANGES = REVISION_CHANGES;
  113563. var objectType = '[object Object]';
  113564. function HandlebarsEnvironment(helpers, partials, decorators) {
  113565. this.helpers = helpers || {};
  113566. this.partials = partials || {};
  113567. this.decorators = decorators || {};
  113568. _helpers.registerDefaultHelpers(this);
  113569. _decorators.registerDefaultDecorators(this);
  113570. }
  113571. HandlebarsEnvironment.prototype = {
  113572. constructor: HandlebarsEnvironment,
  113573. logger: _logger2['default'],
  113574. log: _logger2['default'].log,
  113575. registerHelper: function registerHelper(name, fn) {
  113576. if (_utils.toString.call(name) === objectType) {
  113577. if (fn) {
  113578. throw new _exception2['default']('Arg not supported with multiple helpers');
  113579. }
  113580. _utils.extend(this.helpers, name);
  113581. } else {
  113582. this.helpers[name] = fn;
  113583. }
  113584. },
  113585. unregisterHelper: function unregisterHelper(name) {
  113586. delete this.helpers[name];
  113587. },
  113588. registerPartial: function registerPartial(name, partial) {
  113589. if (_utils.toString.call(name) === objectType) {
  113590. _utils.extend(this.partials, name);
  113591. } else {
  113592. if (typeof partial === 'undefined') {
  113593. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  113594. }
  113595. this.partials[name] = partial;
  113596. }
  113597. },
  113598. unregisterPartial: function unregisterPartial(name) {
  113599. delete this.partials[name];
  113600. },
  113601. registerDecorator: function registerDecorator(name, fn) {
  113602. if (_utils.toString.call(name) === objectType) {
  113603. if (fn) {
  113604. throw new _exception2['default']('Arg not supported with multiple decorators');
  113605. }
  113606. _utils.extend(this.decorators, name);
  113607. } else {
  113608. this.decorators[name] = fn;
  113609. }
  113610. },
  113611. unregisterDecorator: function unregisterDecorator(name) {
  113612. delete this.decorators[name];
  113613. }
  113614. };
  113615. var log = _logger2['default'].log;
  113616. exports.log = log;
  113617. exports.createFrame = _utils.createFrame;
  113618. exports.logger = _logger2['default'];
  113619. /***/ }),
  113620. /* 5 */
  113621. /***/ (function(module, exports) {
  113622. 'use strict';
  113623. exports.__esModule = true;
  113624. exports.extend = extend;
  113625. exports.indexOf = indexOf;
  113626. exports.escapeExpression = escapeExpression;
  113627. exports.isEmpty = isEmpty;
  113628. exports.createFrame = createFrame;
  113629. exports.blockParams = blockParams;
  113630. exports.appendContextPath = appendContextPath;
  113631. var escape = {
  113632. '&': '&amp;',
  113633. '<': '&lt;',
  113634. '>': '&gt;',
  113635. '"': '&quot;',
  113636. "'": '&#x27;',
  113637. '`': '&#x60;',
  113638. '=': '&#x3D;'
  113639. };
  113640. var badChars = /[&<>"'`=]/g,
  113641. possible = /[&<>"'`=]/;
  113642. function escapeChar(chr) {
  113643. return escape[chr];
  113644. }
  113645. function extend(obj /* , ...source */) {
  113646. for (var i = 1; i < arguments.length; i++) {
  113647. for (var key in arguments[i]) {
  113648. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  113649. obj[key] = arguments[i][key];
  113650. }
  113651. }
  113652. }
  113653. return obj;
  113654. }
  113655. var toString = Object.prototype.toString;
  113656. exports.toString = toString;
  113657. // Sourced from lodash
  113658. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  113659. /* eslint-disable func-style */
  113660. var isFunction = function isFunction(value) {
  113661. return typeof value === 'function';
  113662. };
  113663. // fallback for older versions of Chrome and Safari
  113664. /* istanbul ignore next */
  113665. if (isFunction(/x/)) {
  113666. exports.isFunction = isFunction = function (value) {
  113667. return typeof value === 'function' && toString.call(value) === '[object Function]';
  113668. };
  113669. }
  113670. exports.isFunction = isFunction;
  113671. /* eslint-enable func-style */
  113672. /* istanbul ignore next */
  113673. var isArray = Array.isArray || function (value) {
  113674. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  113675. };
  113676. exports.isArray = isArray;
  113677. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  113678. function indexOf(array, value) {
  113679. for (var i = 0, len = array.length; i < len; i++) {
  113680. if (array[i] === value) {
  113681. return i;
  113682. }
  113683. }
  113684. return -1;
  113685. }
  113686. function escapeExpression(string) {
  113687. if (typeof string !== 'string') {
  113688. // don't escape SafeStrings, since they're already safe
  113689. if (string && string.toHTML) {
  113690. return string.toHTML();
  113691. } else if (string == null) {
  113692. return '';
  113693. } else if (!string) {
  113694. return string + '';
  113695. }
  113696. // Force a string conversion as this will be done by the append regardless and
  113697. // the regex test will do this transparently behind the scenes, causing issues if
  113698. // an object's to string has escaped characters in it.
  113699. string = '' + string;
  113700. }
  113701. if (!possible.test(string)) {
  113702. return string;
  113703. }
  113704. return string.replace(badChars, escapeChar);
  113705. }
  113706. function isEmpty(value) {
  113707. if (!value && value !== 0) {
  113708. return true;
  113709. } else if (isArray(value) && value.length === 0) {
  113710. return true;
  113711. } else {
  113712. return false;
  113713. }
  113714. }
  113715. function createFrame(object) {
  113716. var frame = extend({}, object);
  113717. frame._parent = object;
  113718. return frame;
  113719. }
  113720. function blockParams(params, ids) {
  113721. params.path = ids;
  113722. return params;
  113723. }
  113724. function appendContextPath(contextPath, id) {
  113725. return (contextPath ? contextPath + '.' : '') + id;
  113726. }
  113727. /***/ }),
  113728. /* 6 */
  113729. /***/ (function(module, exports, __webpack_require__) {
  113730. 'use strict';
  113731. var _Object$defineProperty = __webpack_require__(7)['default'];
  113732. exports.__esModule = true;
  113733. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  113734. function Exception(message, node) {
  113735. var loc = node && node.loc,
  113736. line = undefined,
  113737. column = undefined;
  113738. if (loc) {
  113739. line = loc.start.line;
  113740. column = loc.start.column;
  113741. message += ' - ' + line + ':' + column;
  113742. }
  113743. var tmp = Error.prototype.constructor.call(this, message);
  113744. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  113745. for (var idx = 0; idx < errorProps.length; idx++) {
  113746. this[errorProps[idx]] = tmp[errorProps[idx]];
  113747. }
  113748. /* istanbul ignore else */
  113749. if (Error.captureStackTrace) {
  113750. Error.captureStackTrace(this, Exception);
  113751. }
  113752. try {
  113753. if (loc) {
  113754. this.lineNumber = line;
  113755. // Work around issue under safari where we can't directly set the column value
  113756. /* istanbul ignore next */
  113757. if (_Object$defineProperty) {
  113758. Object.defineProperty(this, 'column', {
  113759. value: column,
  113760. enumerable: true
  113761. });
  113762. } else {
  113763. this.column = column;
  113764. }
  113765. }
  113766. } catch (nop) {
  113767. /* Ignore if the browser is very particular */
  113768. }
  113769. }
  113770. Exception.prototype = new Error();
  113771. exports['default'] = Exception;
  113772. module.exports = exports['default'];
  113773. /***/ }),
  113774. /* 7 */
  113775. /***/ (function(module, exports, __webpack_require__) {
  113776. module.exports = { "default": __webpack_require__(8), __esModule: true };
  113777. /***/ }),
  113778. /* 8 */
  113779. /***/ (function(module, exports, __webpack_require__) {
  113780. var $ = __webpack_require__(9);
  113781. module.exports = function defineProperty(it, key, desc){
  113782. return $.setDesc(it, key, desc);
  113783. };
  113784. /***/ }),
  113785. /* 9 */
  113786. /***/ (function(module, exports) {
  113787. var $Object = Object;
  113788. module.exports = {
  113789. create: $Object.create,
  113790. getProto: $Object.getPrototypeOf,
  113791. isEnum: {}.propertyIsEnumerable,
  113792. getDesc: $Object.getOwnPropertyDescriptor,
  113793. setDesc: $Object.defineProperty,
  113794. setDescs: $Object.defineProperties,
  113795. getKeys: $Object.keys,
  113796. getNames: $Object.getOwnPropertyNames,
  113797. getSymbols: $Object.getOwnPropertySymbols,
  113798. each: [].forEach
  113799. };
  113800. /***/ }),
  113801. /* 10 */
  113802. /***/ (function(module, exports, __webpack_require__) {
  113803. 'use strict';
  113804. var _interopRequireDefault = __webpack_require__(1)['default'];
  113805. exports.__esModule = true;
  113806. exports.registerDefaultHelpers = registerDefaultHelpers;
  113807. var _helpersBlockHelperMissing = __webpack_require__(11);
  113808. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  113809. var _helpersEach = __webpack_require__(12);
  113810. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  113811. var _helpersHelperMissing = __webpack_require__(13);
  113812. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  113813. var _helpersIf = __webpack_require__(14);
  113814. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  113815. var _helpersLog = __webpack_require__(15);
  113816. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  113817. var _helpersLookup = __webpack_require__(16);
  113818. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  113819. var _helpersWith = __webpack_require__(17);
  113820. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  113821. function registerDefaultHelpers(instance) {
  113822. _helpersBlockHelperMissing2['default'](instance);
  113823. _helpersEach2['default'](instance);
  113824. _helpersHelperMissing2['default'](instance);
  113825. _helpersIf2['default'](instance);
  113826. _helpersLog2['default'](instance);
  113827. _helpersLookup2['default'](instance);
  113828. _helpersWith2['default'](instance);
  113829. }
  113830. /***/ }),
  113831. /* 11 */
  113832. /***/ (function(module, exports, __webpack_require__) {
  113833. 'use strict';
  113834. exports.__esModule = true;
  113835. var _utils = __webpack_require__(5);
  113836. exports['default'] = function (instance) {
  113837. instance.registerHelper('blockHelperMissing', function (context, options) {
  113838. var inverse = options.inverse,
  113839. fn = options.fn;
  113840. if (context === true) {
  113841. return fn(this);
  113842. } else if (context === false || context == null) {
  113843. return inverse(this);
  113844. } else if (_utils.isArray(context)) {
  113845. if (context.length > 0) {
  113846. if (options.ids) {
  113847. options.ids = [options.name];
  113848. }
  113849. return instance.helpers.each(context, options);
  113850. } else {
  113851. return inverse(this);
  113852. }
  113853. } else {
  113854. if (options.data && options.ids) {
  113855. var data = _utils.createFrame(options.data);
  113856. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  113857. options = { data: data };
  113858. }
  113859. return fn(context, options);
  113860. }
  113861. });
  113862. };
  113863. module.exports = exports['default'];
  113864. /***/ }),
  113865. /* 12 */
  113866. /***/ (function(module, exports, __webpack_require__) {
  113867. 'use strict';
  113868. var _interopRequireDefault = __webpack_require__(1)['default'];
  113869. exports.__esModule = true;
  113870. var _utils = __webpack_require__(5);
  113871. var _exception = __webpack_require__(6);
  113872. var _exception2 = _interopRequireDefault(_exception);
  113873. exports['default'] = function (instance) {
  113874. instance.registerHelper('each', function (context, options) {
  113875. if (!options) {
  113876. throw new _exception2['default']('Must pass iterator to #each');
  113877. }
  113878. var fn = options.fn,
  113879. inverse = options.inverse,
  113880. i = 0,
  113881. ret = '',
  113882. data = undefined,
  113883. contextPath = undefined;
  113884. if (options.data && options.ids) {
  113885. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  113886. }
  113887. if (_utils.isFunction(context)) {
  113888. context = context.call(this);
  113889. }
  113890. if (options.data) {
  113891. data = _utils.createFrame(options.data);
  113892. }
  113893. function execIteration(field, index, last) {
  113894. if (data) {
  113895. data.key = field;
  113896. data.index = index;
  113897. data.first = index === 0;
  113898. data.last = !!last;
  113899. if (contextPath) {
  113900. data.contextPath = contextPath + field;
  113901. }
  113902. }
  113903. ret = ret + fn(context[field], {
  113904. data: data,
  113905. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  113906. });
  113907. }
  113908. if (context && typeof context === 'object') {
  113909. if (_utils.isArray(context)) {
  113910. for (var j = context.length; i < j; i++) {
  113911. if (i in context) {
  113912. execIteration(i, i, i === context.length - 1);
  113913. }
  113914. }
  113915. } else {
  113916. var priorKey = undefined;
  113917. for (var key in context) {
  113918. if (context.hasOwnProperty(key)) {
  113919. // We're running the iterations one step out of sync so we can detect
  113920. // the last iteration without have to scan the object twice and create
  113921. // an itermediate keys array.
  113922. if (priorKey !== undefined) {
  113923. execIteration(priorKey, i - 1);
  113924. }
  113925. priorKey = key;
  113926. i++;
  113927. }
  113928. }
  113929. if (priorKey !== undefined) {
  113930. execIteration(priorKey, i - 1, true);
  113931. }
  113932. }
  113933. }
  113934. if (i === 0) {
  113935. ret = inverse(this);
  113936. }
  113937. return ret;
  113938. });
  113939. };
  113940. module.exports = exports['default'];
  113941. /***/ }),
  113942. /* 13 */
  113943. /***/ (function(module, exports, __webpack_require__) {
  113944. 'use strict';
  113945. var _interopRequireDefault = __webpack_require__(1)['default'];
  113946. exports.__esModule = true;
  113947. var _exception = __webpack_require__(6);
  113948. var _exception2 = _interopRequireDefault(_exception);
  113949. exports['default'] = function (instance) {
  113950. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  113951. if (arguments.length === 1) {
  113952. // A missing field in a {{foo}} construct.
  113953. return undefined;
  113954. } else {
  113955. // Someone is actually trying to call something, blow up.
  113956. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  113957. }
  113958. });
  113959. };
  113960. module.exports = exports['default'];
  113961. /***/ }),
  113962. /* 14 */
  113963. /***/ (function(module, exports, __webpack_require__) {
  113964. 'use strict';
  113965. exports.__esModule = true;
  113966. var _utils = __webpack_require__(5);
  113967. exports['default'] = function (instance) {
  113968. instance.registerHelper('if', function (conditional, options) {
  113969. if (_utils.isFunction(conditional)) {
  113970. conditional = conditional.call(this);
  113971. }
  113972. // Default behavior is to render the positive path if the value is truthy and not empty.
  113973. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  113974. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  113975. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  113976. return options.inverse(this);
  113977. } else {
  113978. return options.fn(this);
  113979. }
  113980. });
  113981. instance.registerHelper('unless', function (conditional, options) {
  113982. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  113983. });
  113984. };
  113985. module.exports = exports['default'];
  113986. /***/ }),
  113987. /* 15 */
  113988. /***/ (function(module, exports) {
  113989. 'use strict';
  113990. exports.__esModule = true;
  113991. exports['default'] = function (instance) {
  113992. instance.registerHelper('log', function () /* message, options */{
  113993. var args = [undefined],
  113994. options = arguments[arguments.length - 1];
  113995. for (var i = 0; i < arguments.length - 1; i++) {
  113996. args.push(arguments[i]);
  113997. }
  113998. var level = 1;
  113999. if (options.hash.level != null) {
  114000. level = options.hash.level;
  114001. } else if (options.data && options.data.level != null) {
  114002. level = options.data.level;
  114003. }
  114004. args[0] = level;
  114005. instance.log.apply(instance, args);
  114006. });
  114007. };
  114008. module.exports = exports['default'];
  114009. /***/ }),
  114010. /* 16 */
  114011. /***/ (function(module, exports) {
  114012. 'use strict';
  114013. exports.__esModule = true;
  114014. exports['default'] = function (instance) {
  114015. instance.registerHelper('lookup', function (obj, field) {
  114016. return obj && obj[field];
  114017. });
  114018. };
  114019. module.exports = exports['default'];
  114020. /***/ }),
  114021. /* 17 */
  114022. /***/ (function(module, exports, __webpack_require__) {
  114023. 'use strict';
  114024. exports.__esModule = true;
  114025. var _utils = __webpack_require__(5);
  114026. exports['default'] = function (instance) {
  114027. instance.registerHelper('with', function (context, options) {
  114028. if (_utils.isFunction(context)) {
  114029. context = context.call(this);
  114030. }
  114031. var fn = options.fn;
  114032. if (!_utils.isEmpty(context)) {
  114033. var data = options.data;
  114034. if (options.data && options.ids) {
  114035. data = _utils.createFrame(options.data);
  114036. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  114037. }
  114038. return fn(context, {
  114039. data: data,
  114040. blockParams: _utils.blockParams([context], [data && data.contextPath])
  114041. });
  114042. } else {
  114043. return options.inverse(this);
  114044. }
  114045. });
  114046. };
  114047. module.exports = exports['default'];
  114048. /***/ }),
  114049. /* 18 */
  114050. /***/ (function(module, exports, __webpack_require__) {
  114051. 'use strict';
  114052. var _interopRequireDefault = __webpack_require__(1)['default'];
  114053. exports.__esModule = true;
  114054. exports.registerDefaultDecorators = registerDefaultDecorators;
  114055. var _decoratorsInline = __webpack_require__(19);
  114056. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  114057. function registerDefaultDecorators(instance) {
  114058. _decoratorsInline2['default'](instance);
  114059. }
  114060. /***/ }),
  114061. /* 19 */
  114062. /***/ (function(module, exports, __webpack_require__) {
  114063. 'use strict';
  114064. exports.__esModule = true;
  114065. var _utils = __webpack_require__(5);
  114066. exports['default'] = function (instance) {
  114067. instance.registerDecorator('inline', function (fn, props, container, options) {
  114068. var ret = fn;
  114069. if (!props.partials) {
  114070. props.partials = {};
  114071. ret = function (context, options) {
  114072. // Create a new partials stack frame prior to exec.
  114073. var original = container.partials;
  114074. container.partials = _utils.extend({}, original, props.partials);
  114075. var ret = fn(context, options);
  114076. container.partials = original;
  114077. return ret;
  114078. };
  114079. }
  114080. props.partials[options.args[0]] = options.fn;
  114081. return ret;
  114082. });
  114083. };
  114084. module.exports = exports['default'];
  114085. /***/ }),
  114086. /* 20 */
  114087. /***/ (function(module, exports, __webpack_require__) {
  114088. 'use strict';
  114089. exports.__esModule = true;
  114090. var _utils = __webpack_require__(5);
  114091. var logger = {
  114092. methodMap: ['debug', 'info', 'warn', 'error'],
  114093. level: 'info',
  114094. // Maps a given level value to the `methodMap` indexes above.
  114095. lookupLevel: function lookupLevel(level) {
  114096. if (typeof level === 'string') {
  114097. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  114098. if (levelMap >= 0) {
  114099. level = levelMap;
  114100. } else {
  114101. level = parseInt(level, 10);
  114102. }
  114103. }
  114104. return level;
  114105. },
  114106. // Can be overridden in the host environment
  114107. log: function log(level) {
  114108. level = logger.lookupLevel(level);
  114109. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  114110. var method = logger.methodMap[level];
  114111. if (!console[method]) {
  114112. // eslint-disable-line no-console
  114113. method = 'log';
  114114. }
  114115. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  114116. message[_key - 1] = arguments[_key];
  114117. }
  114118. console[method].apply(console, message); // eslint-disable-line no-console
  114119. }
  114120. }
  114121. };
  114122. exports['default'] = logger;
  114123. module.exports = exports['default'];
  114124. /***/ }),
  114125. /* 21 */
  114126. /***/ (function(module, exports) {
  114127. // Build out our basic SafeString type
  114128. 'use strict';
  114129. exports.__esModule = true;
  114130. function SafeString(string) {
  114131. this.string = string;
  114132. }
  114133. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  114134. return '' + this.string;
  114135. };
  114136. exports['default'] = SafeString;
  114137. module.exports = exports['default'];
  114138. /***/ }),
  114139. /* 22 */
  114140. /***/ (function(module, exports, __webpack_require__) {
  114141. 'use strict';
  114142. var _Object$seal = __webpack_require__(23)['default'];
  114143. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114144. var _interopRequireDefault = __webpack_require__(1)['default'];
  114145. exports.__esModule = true;
  114146. exports.checkRevision = checkRevision;
  114147. exports.template = template;
  114148. exports.wrapProgram = wrapProgram;
  114149. exports.resolvePartial = resolvePartial;
  114150. exports.invokePartial = invokePartial;
  114151. exports.noop = noop;
  114152. var _utils = __webpack_require__(5);
  114153. var Utils = _interopRequireWildcard(_utils);
  114154. var _exception = __webpack_require__(6);
  114155. var _exception2 = _interopRequireDefault(_exception);
  114156. var _base = __webpack_require__(4);
  114157. function checkRevision(compilerInfo) {
  114158. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  114159. currentRevision = _base.COMPILER_REVISION;
  114160. if (compilerRevision !== currentRevision) {
  114161. if (compilerRevision < currentRevision) {
  114162. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  114163. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  114164. 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 + ').');
  114165. } else {
  114166. // Use the embedded version info since the runtime doesn't know about this revision yet
  114167. 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] + ').');
  114168. }
  114169. }
  114170. }
  114171. function template(templateSpec, env) {
  114172. /* istanbul ignore next */
  114173. if (!env) {
  114174. throw new _exception2['default']('No environment passed to template');
  114175. }
  114176. if (!templateSpec || !templateSpec.main) {
  114177. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  114178. }
  114179. templateSpec.main.decorator = templateSpec.main_d;
  114180. // Note: Using env.VM references rather than local var references throughout this section to allow
  114181. // for external users to override these as psuedo-supported APIs.
  114182. env.VM.checkRevision(templateSpec.compiler);
  114183. function invokePartialWrapper(partial, context, options) {
  114184. if (options.hash) {
  114185. context = Utils.extend({}, context, options.hash);
  114186. if (options.ids) {
  114187. options.ids[0] = true;
  114188. }
  114189. }
  114190. partial = env.VM.resolvePartial.call(this, partial, context, options);
  114191. var result = env.VM.invokePartial.call(this, partial, context, options);
  114192. if (result == null && env.compile) {
  114193. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  114194. result = options.partials[options.name](context, options);
  114195. }
  114196. if (result != null) {
  114197. if (options.indent) {
  114198. var lines = result.split('\n');
  114199. for (var i = 0, l = lines.length; i < l; i++) {
  114200. if (!lines[i] && i + 1 === l) {
  114201. break;
  114202. }
  114203. lines[i] = options.indent + lines[i];
  114204. }
  114205. result = lines.join('\n');
  114206. }
  114207. return result;
  114208. } else {
  114209. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  114210. }
  114211. }
  114212. // Just add water
  114213. var container = {
  114214. strict: function strict(obj, name) {
  114215. if (!(name in obj)) {
  114216. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  114217. }
  114218. return obj[name];
  114219. },
  114220. lookup: function lookup(depths, name) {
  114221. var len = depths.length;
  114222. for (var i = 0; i < len; i++) {
  114223. if (depths[i] && depths[i][name] != null) {
  114224. return depths[i][name];
  114225. }
  114226. }
  114227. },
  114228. lambda: function lambda(current, context) {
  114229. return typeof current === 'function' ? current.call(context) : current;
  114230. },
  114231. escapeExpression: Utils.escapeExpression,
  114232. invokePartial: invokePartialWrapper,
  114233. fn: function fn(i) {
  114234. var ret = templateSpec[i];
  114235. ret.decorator = templateSpec[i + '_d'];
  114236. return ret;
  114237. },
  114238. programs: [],
  114239. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  114240. var programWrapper = this.programs[i],
  114241. fn = this.fn(i);
  114242. if (data || depths || blockParams || declaredBlockParams) {
  114243. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  114244. } else if (!programWrapper) {
  114245. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  114246. }
  114247. return programWrapper;
  114248. },
  114249. data: function data(value, depth) {
  114250. while (value && depth--) {
  114251. value = value._parent;
  114252. }
  114253. return value;
  114254. },
  114255. merge: function merge(param, common) {
  114256. var obj = param || common;
  114257. if (param && common && param !== common) {
  114258. obj = Utils.extend({}, common, param);
  114259. }
  114260. return obj;
  114261. },
  114262. // An empty object to use as replacement for null-contexts
  114263. nullContext: _Object$seal({}),
  114264. noop: env.VM.noop,
  114265. compilerInfo: templateSpec.compiler
  114266. };
  114267. function ret(context) {
  114268. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114269. var data = options.data;
  114270. ret._setup(options);
  114271. if (!options.partial && templateSpec.useData) {
  114272. data = initData(context, data);
  114273. }
  114274. var depths = undefined,
  114275. blockParams = templateSpec.useBlockParams ? [] : undefined;
  114276. if (templateSpec.useDepths) {
  114277. if (options.depths) {
  114278. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  114279. } else {
  114280. depths = [context];
  114281. }
  114282. }
  114283. function main(context /*, options*/) {
  114284. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  114285. }
  114286. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  114287. return main(context, options);
  114288. }
  114289. ret.isTop = true;
  114290. ret._setup = function (options) {
  114291. if (!options.partial) {
  114292. container.helpers = container.merge(options.helpers, env.helpers);
  114293. if (templateSpec.usePartial) {
  114294. container.partials = container.merge(options.partials, env.partials);
  114295. }
  114296. if (templateSpec.usePartial || templateSpec.useDecorators) {
  114297. container.decorators = container.merge(options.decorators, env.decorators);
  114298. }
  114299. } else {
  114300. container.helpers = options.helpers;
  114301. container.partials = options.partials;
  114302. container.decorators = options.decorators;
  114303. }
  114304. };
  114305. ret._child = function (i, data, blockParams, depths) {
  114306. if (templateSpec.useBlockParams && !blockParams) {
  114307. throw new _exception2['default']('must pass block params');
  114308. }
  114309. if (templateSpec.useDepths && !depths) {
  114310. throw new _exception2['default']('must pass parent depths');
  114311. }
  114312. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  114313. };
  114314. return ret;
  114315. }
  114316. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  114317. function prog(context) {
  114318. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114319. var currentDepths = depths;
  114320. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  114321. currentDepths = [context].concat(depths);
  114322. }
  114323. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  114324. }
  114325. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  114326. prog.program = i;
  114327. prog.depth = depths ? depths.length : 0;
  114328. prog.blockParams = declaredBlockParams || 0;
  114329. return prog;
  114330. }
  114331. function resolvePartial(partial, context, options) {
  114332. if (!partial) {
  114333. if (options.name === '@partial-block') {
  114334. partial = options.data['partial-block'];
  114335. } else {
  114336. partial = options.partials[options.name];
  114337. }
  114338. } else if (!partial.call && !options.name) {
  114339. // This is a dynamic partial that returned a string
  114340. options.name = partial;
  114341. partial = options.partials[partial];
  114342. }
  114343. return partial;
  114344. }
  114345. function invokePartial(partial, context, options) {
  114346. // Use the current closure context to save the partial-block if this partial
  114347. var currentPartialBlock = options.data && options.data['partial-block'];
  114348. options.partial = true;
  114349. if (options.ids) {
  114350. options.data.contextPath = options.ids[0] || options.data.contextPath;
  114351. }
  114352. var partialBlock = undefined;
  114353. if (options.fn && options.fn !== noop) {
  114354. (function () {
  114355. options.data = _base.createFrame(options.data);
  114356. // Wrapper function to get access to currentPartialBlock from the closure
  114357. var fn = options.fn;
  114358. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  114359. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114360. // Restore the partial-block from the closure for the execution of the block
  114361. // i.e. the part inside the block of the partial call.
  114362. options.data = _base.createFrame(options.data);
  114363. options.data['partial-block'] = currentPartialBlock;
  114364. return fn(context, options);
  114365. };
  114366. if (fn.partials) {
  114367. options.partials = Utils.extend({}, options.partials, fn.partials);
  114368. }
  114369. })();
  114370. }
  114371. if (partial === undefined && partialBlock) {
  114372. partial = partialBlock;
  114373. }
  114374. if (partial === undefined) {
  114375. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  114376. } else if (partial instanceof Function) {
  114377. return partial(context, options);
  114378. }
  114379. }
  114380. function noop() {
  114381. return '';
  114382. }
  114383. function initData(context, data) {
  114384. if (!data || !('root' in data)) {
  114385. data = data ? _base.createFrame(data) : {};
  114386. data.root = context;
  114387. }
  114388. return data;
  114389. }
  114390. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  114391. if (fn.decorator) {
  114392. var props = {};
  114393. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  114394. Utils.extend(prog, props);
  114395. }
  114396. return prog;
  114397. }
  114398. /***/ }),
  114399. /* 23 */
  114400. /***/ (function(module, exports, __webpack_require__) {
  114401. module.exports = { "default": __webpack_require__(24), __esModule: true };
  114402. /***/ }),
  114403. /* 24 */
  114404. /***/ (function(module, exports, __webpack_require__) {
  114405. __webpack_require__(25);
  114406. module.exports = __webpack_require__(30).Object.seal;
  114407. /***/ }),
  114408. /* 25 */
  114409. /***/ (function(module, exports, __webpack_require__) {
  114410. // 19.1.2.17 Object.seal(O)
  114411. var isObject = __webpack_require__(26);
  114412. __webpack_require__(27)('seal', function($seal){
  114413. return function seal(it){
  114414. return $seal && isObject(it) ? $seal(it) : it;
  114415. };
  114416. });
  114417. /***/ }),
  114418. /* 26 */
  114419. /***/ (function(module, exports) {
  114420. module.exports = function(it){
  114421. return typeof it === 'object' ? it !== null : typeof it === 'function';
  114422. };
  114423. /***/ }),
  114424. /* 27 */
  114425. /***/ (function(module, exports, __webpack_require__) {
  114426. // most Object methods by ES6 should accept primitives
  114427. var $export = __webpack_require__(28)
  114428. , core = __webpack_require__(30)
  114429. , fails = __webpack_require__(33);
  114430. module.exports = function(KEY, exec){
  114431. var fn = (core.Object || {})[KEY] || Object[KEY]
  114432. , exp = {};
  114433. exp[KEY] = exec(fn);
  114434. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  114435. };
  114436. /***/ }),
  114437. /* 28 */
  114438. /***/ (function(module, exports, __webpack_require__) {
  114439. var global = __webpack_require__(29)
  114440. , core = __webpack_require__(30)
  114441. , ctx = __webpack_require__(31)
  114442. , PROTOTYPE = 'prototype';
  114443. var $export = function(type, name, source){
  114444. var IS_FORCED = type & $export.F
  114445. , IS_GLOBAL = type & $export.G
  114446. , IS_STATIC = type & $export.S
  114447. , IS_PROTO = type & $export.P
  114448. , IS_BIND = type & $export.B
  114449. , IS_WRAP = type & $export.W
  114450. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  114451. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  114452. , key, own, out;
  114453. if(IS_GLOBAL)source = name;
  114454. for(key in source){
  114455. // contains in native
  114456. own = !IS_FORCED && target && key in target;
  114457. if(own && key in exports)continue;
  114458. // export native or passed
  114459. out = own ? target[key] : source[key];
  114460. // prevent global pollution for namespaces
  114461. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  114462. // bind timers to global for call from export context
  114463. : IS_BIND && own ? ctx(out, global)
  114464. // wrap global constructors for prevent change them in library
  114465. : IS_WRAP && target[key] == out ? (function(C){
  114466. var F = function(param){
  114467. return this instanceof C ? new C(param) : C(param);
  114468. };
  114469. F[PROTOTYPE] = C[PROTOTYPE];
  114470. return F;
  114471. // make static versions for prototype methods
  114472. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  114473. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  114474. }
  114475. };
  114476. // type bitmap
  114477. $export.F = 1; // forced
  114478. $export.G = 2; // global
  114479. $export.S = 4; // static
  114480. $export.P = 8; // proto
  114481. $export.B = 16; // bind
  114482. $export.W = 32; // wrap
  114483. module.exports = $export;
  114484. /***/ }),
  114485. /* 29 */
  114486. /***/ (function(module, exports) {
  114487. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  114488. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  114489. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  114490. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  114491. /***/ }),
  114492. /* 30 */
  114493. /***/ (function(module, exports) {
  114494. var core = module.exports = {version: '1.2.6'};
  114495. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  114496. /***/ }),
  114497. /* 31 */
  114498. /***/ (function(module, exports, __webpack_require__) {
  114499. // optional / simple context binding
  114500. var aFunction = __webpack_require__(32);
  114501. module.exports = function(fn, that, length){
  114502. aFunction(fn);
  114503. if(that === undefined)return fn;
  114504. switch(length){
  114505. case 1: return function(a){
  114506. return fn.call(that, a);
  114507. };
  114508. case 2: return function(a, b){
  114509. return fn.call(that, a, b);
  114510. };
  114511. case 3: return function(a, b, c){
  114512. return fn.call(that, a, b, c);
  114513. };
  114514. }
  114515. return function(/* ...args */){
  114516. return fn.apply(that, arguments);
  114517. };
  114518. };
  114519. /***/ }),
  114520. /* 32 */
  114521. /***/ (function(module, exports) {
  114522. module.exports = function(it){
  114523. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  114524. return it;
  114525. };
  114526. /***/ }),
  114527. /* 33 */
  114528. /***/ (function(module, exports) {
  114529. module.exports = function(exec){
  114530. try {
  114531. return !!exec();
  114532. } catch(e){
  114533. return true;
  114534. }
  114535. };
  114536. /***/ }),
  114537. /* 34 */
  114538. /***/ (function(module, exports) {
  114539. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  114540. 'use strict';
  114541. exports.__esModule = true;
  114542. exports['default'] = function (Handlebars) {
  114543. /* istanbul ignore next */
  114544. var root = typeof global !== 'undefined' ? global : window,
  114545. $Handlebars = root.Handlebars;
  114546. /* istanbul ignore next */
  114547. Handlebars.noConflict = function () {
  114548. if (root.Handlebars === Handlebars) {
  114549. root.Handlebars = $Handlebars;
  114550. }
  114551. return Handlebars;
  114552. };
  114553. };
  114554. module.exports = exports['default'];
  114555. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  114556. /***/ }),
  114557. /* 35 */
  114558. /***/ (function(module, exports) {
  114559. 'use strict';
  114560. exports.__esModule = true;
  114561. var AST = {
  114562. // Public API used to evaluate derived attributes regarding AST nodes
  114563. helpers: {
  114564. // a mustache is definitely a helper if:
  114565. // * it is an eligible helper, and
  114566. // * it has at least one parameter or hash segment
  114567. helperExpression: function helperExpression(node) {
  114568. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  114569. },
  114570. scopedId: function scopedId(path) {
  114571. return (/^\.|this\b/.test(path.original)
  114572. );
  114573. },
  114574. // an ID is simple if it only has one part, and that part is not
  114575. // `..` or `this`.
  114576. simpleId: function simpleId(path) {
  114577. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  114578. }
  114579. }
  114580. };
  114581. // Must be exported as an object rather than the root of the module as the jison lexer
  114582. // must modify the object to operate properly.
  114583. exports['default'] = AST;
  114584. module.exports = exports['default'];
  114585. /***/ }),
  114586. /* 36 */
  114587. /***/ (function(module, exports, __webpack_require__) {
  114588. 'use strict';
  114589. var _interopRequireDefault = __webpack_require__(1)['default'];
  114590. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114591. exports.__esModule = true;
  114592. exports.parse = parse;
  114593. var _parser = __webpack_require__(37);
  114594. var _parser2 = _interopRequireDefault(_parser);
  114595. var _whitespaceControl = __webpack_require__(38);
  114596. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  114597. var _helpers = __webpack_require__(40);
  114598. var Helpers = _interopRequireWildcard(_helpers);
  114599. var _utils = __webpack_require__(5);
  114600. exports.parser = _parser2['default'];
  114601. var yy = {};
  114602. _utils.extend(yy, Helpers);
  114603. function parse(input, options) {
  114604. // Just return if an already-compiled AST was passed in.
  114605. if (input.type === 'Program') {
  114606. return input;
  114607. }
  114608. _parser2['default'].yy = yy;
  114609. // Altering the shared object here, but this is ok as parser is a sync operation
  114610. yy.locInfo = function (locInfo) {
  114611. return new yy.SourceLocation(options && options.srcName, locInfo);
  114612. };
  114613. var strip = new _whitespaceControl2['default'](options);
  114614. return strip.accept(_parser2['default'].parse(input));
  114615. }
  114616. /***/ }),
  114617. /* 37 */
  114618. /***/ (function(module, exports) {
  114619. // File ignored in coverage tests via setting in .istanbul.yml
  114620. /* Jison generated parser */
  114621. "use strict";
  114622. exports.__esModule = true;
  114623. var handlebars = (function () {
  114624. var parser = { trace: function trace() {},
  114625. yy: {},
  114626. 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 },
  114627. 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" },
  114628. 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]],
  114629. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  114630. /**/) {
  114631. var $0 = $$.length - 1;
  114632. switch (yystate) {
  114633. case 1:
  114634. return $$[$0 - 1];
  114635. break;
  114636. case 2:
  114637. this.$ = yy.prepareProgram($$[$0]);
  114638. break;
  114639. case 3:
  114640. this.$ = $$[$0];
  114641. break;
  114642. case 4:
  114643. this.$ = $$[$0];
  114644. break;
  114645. case 5:
  114646. this.$ = $$[$0];
  114647. break;
  114648. case 6:
  114649. this.$ = $$[$0];
  114650. break;
  114651. case 7:
  114652. this.$ = $$[$0];
  114653. break;
  114654. case 8:
  114655. this.$ = $$[$0];
  114656. break;
  114657. case 9:
  114658. this.$ = {
  114659. type: 'CommentStatement',
  114660. value: yy.stripComment($$[$0]),
  114661. strip: yy.stripFlags($$[$0], $$[$0]),
  114662. loc: yy.locInfo(this._$)
  114663. };
  114664. break;
  114665. case 10:
  114666. this.$ = {
  114667. type: 'ContentStatement',
  114668. original: $$[$0],
  114669. value: $$[$0],
  114670. loc: yy.locInfo(this._$)
  114671. };
  114672. break;
  114673. case 11:
  114674. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114675. break;
  114676. case 12:
  114677. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  114678. break;
  114679. case 13:
  114680. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  114681. break;
  114682. case 14:
  114683. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  114684. break;
  114685. case 15:
  114686. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114687. break;
  114688. case 16:
  114689. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114690. break;
  114691. case 17:
  114692. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114693. break;
  114694. case 18:
  114695. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  114696. break;
  114697. case 19:
  114698. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  114699. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  114700. program.chained = true;
  114701. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  114702. break;
  114703. case 20:
  114704. this.$ = $$[$0];
  114705. break;
  114706. case 21:
  114707. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  114708. break;
  114709. case 22:
  114710. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114711. break;
  114712. case 23:
  114713. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114714. break;
  114715. case 24:
  114716. this.$ = {
  114717. type: 'PartialStatement',
  114718. name: $$[$0 - 3],
  114719. params: $$[$0 - 2],
  114720. hash: $$[$0 - 1],
  114721. indent: '',
  114722. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  114723. loc: yy.locInfo(this._$)
  114724. };
  114725. break;
  114726. case 25:
  114727. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114728. break;
  114729. case 26:
  114730. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  114731. break;
  114732. case 27:
  114733. this.$ = $$[$0];
  114734. break;
  114735. case 28:
  114736. this.$ = $$[$0];
  114737. break;
  114738. case 29:
  114739. this.$ = {
  114740. type: 'SubExpression',
  114741. path: $$[$0 - 3],
  114742. params: $$[$0 - 2],
  114743. hash: $$[$0 - 1],
  114744. loc: yy.locInfo(this._$)
  114745. };
  114746. break;
  114747. case 30:
  114748. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  114749. break;
  114750. case 31:
  114751. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  114752. break;
  114753. case 32:
  114754. this.$ = yy.id($$[$0 - 1]);
  114755. break;
  114756. case 33:
  114757. this.$ = $$[$0];
  114758. break;
  114759. case 34:
  114760. this.$ = $$[$0];
  114761. break;
  114762. case 35:
  114763. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  114764. break;
  114765. case 36:
  114766. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  114767. break;
  114768. case 37:
  114769. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  114770. break;
  114771. case 38:
  114772. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  114773. break;
  114774. case 39:
  114775. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  114776. break;
  114777. case 40:
  114778. this.$ = $$[$0];
  114779. break;
  114780. case 41:
  114781. this.$ = $$[$0];
  114782. break;
  114783. case 42:
  114784. this.$ = yy.preparePath(true, $$[$0], this._$);
  114785. break;
  114786. case 43:
  114787. this.$ = yy.preparePath(false, $$[$0], this._$);
  114788. break;
  114789. case 44:
  114790. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  114791. break;
  114792. case 45:
  114793. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  114794. break;
  114795. case 46:
  114796. this.$ = [];
  114797. break;
  114798. case 47:
  114799. $$[$0 - 1].push($$[$0]);
  114800. break;
  114801. case 48:
  114802. this.$ = [$$[$0]];
  114803. break;
  114804. case 49:
  114805. $$[$0 - 1].push($$[$0]);
  114806. break;
  114807. case 50:
  114808. this.$ = [];
  114809. break;
  114810. case 51:
  114811. $$[$0 - 1].push($$[$0]);
  114812. break;
  114813. case 58:
  114814. this.$ = [];
  114815. break;
  114816. case 59:
  114817. $$[$0 - 1].push($$[$0]);
  114818. break;
  114819. case 64:
  114820. this.$ = [];
  114821. break;
  114822. case 65:
  114823. $$[$0 - 1].push($$[$0]);
  114824. break;
  114825. case 70:
  114826. this.$ = [];
  114827. break;
  114828. case 71:
  114829. $$[$0 - 1].push($$[$0]);
  114830. break;
  114831. case 78:
  114832. this.$ = [];
  114833. break;
  114834. case 79:
  114835. $$[$0 - 1].push($$[$0]);
  114836. break;
  114837. case 82:
  114838. this.$ = [];
  114839. break;
  114840. case 83:
  114841. $$[$0 - 1].push($$[$0]);
  114842. break;
  114843. case 86:
  114844. this.$ = [];
  114845. break;
  114846. case 87:
  114847. $$[$0 - 1].push($$[$0]);
  114848. break;
  114849. case 90:
  114850. this.$ = [];
  114851. break;
  114852. case 91:
  114853. $$[$0 - 1].push($$[$0]);
  114854. break;
  114855. case 94:
  114856. this.$ = [];
  114857. break;
  114858. case 95:
  114859. $$[$0 - 1].push($$[$0]);
  114860. break;
  114861. case 98:
  114862. this.$ = [$$[$0]];
  114863. break;
  114864. case 99:
  114865. $$[$0 - 1].push($$[$0]);
  114866. break;
  114867. case 100:
  114868. this.$ = [$$[$0]];
  114869. break;
  114870. case 101:
  114871. $$[$0 - 1].push($$[$0]);
  114872. break;
  114873. }
  114874. },
  114875. 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] }],
  114876. 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] },
  114877. parseError: function parseError(str, hash) {
  114878. throw new Error(str);
  114879. },
  114880. parse: function parse(input) {
  114881. var self = this,
  114882. stack = [0],
  114883. vstack = [null],
  114884. lstack = [],
  114885. table = this.table,
  114886. yytext = "",
  114887. yylineno = 0,
  114888. yyleng = 0,
  114889. recovering = 0,
  114890. TERROR = 2,
  114891. EOF = 1;
  114892. this.lexer.setInput(input);
  114893. this.lexer.yy = this.yy;
  114894. this.yy.lexer = this.lexer;
  114895. this.yy.parser = this;
  114896. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  114897. var yyloc = this.lexer.yylloc;
  114898. lstack.push(yyloc);
  114899. var ranges = this.lexer.options && this.lexer.options.ranges;
  114900. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  114901. function popStack(n) {
  114902. stack.length = stack.length - 2 * n;
  114903. vstack.length = vstack.length - n;
  114904. lstack.length = lstack.length - n;
  114905. }
  114906. function lex() {
  114907. var token;
  114908. token = self.lexer.lex() || 1;
  114909. if (typeof token !== "number") {
  114910. token = self.symbols_[token] || token;
  114911. }
  114912. return token;
  114913. }
  114914. var symbol,
  114915. preErrorSymbol,
  114916. state,
  114917. action,
  114918. a,
  114919. r,
  114920. yyval = {},
  114921. p,
  114922. len,
  114923. newState,
  114924. expected;
  114925. while (true) {
  114926. state = stack[stack.length - 1];
  114927. if (this.defaultActions[state]) {
  114928. action = this.defaultActions[state];
  114929. } else {
  114930. if (symbol === null || typeof symbol == "undefined") {
  114931. symbol = lex();
  114932. }
  114933. action = table[state] && table[state][symbol];
  114934. }
  114935. if (typeof action === "undefined" || !action.length || !action[0]) {
  114936. var errStr = "";
  114937. if (!recovering) {
  114938. expected = [];
  114939. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  114940. expected.push("'" + this.terminals_[p] + "'");
  114941. }
  114942. if (this.lexer.showPosition) {
  114943. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  114944. } else {
  114945. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  114946. }
  114947. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  114948. }
  114949. }
  114950. if (action[0] instanceof Array && action.length > 1) {
  114951. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  114952. }
  114953. switch (action[0]) {
  114954. case 1:
  114955. stack.push(symbol);
  114956. vstack.push(this.lexer.yytext);
  114957. lstack.push(this.lexer.yylloc);
  114958. stack.push(action[1]);
  114959. symbol = null;
  114960. if (!preErrorSymbol) {
  114961. yyleng = this.lexer.yyleng;
  114962. yytext = this.lexer.yytext;
  114963. yylineno = this.lexer.yylineno;
  114964. yyloc = this.lexer.yylloc;
  114965. if (recovering > 0) recovering--;
  114966. } else {
  114967. symbol = preErrorSymbol;
  114968. preErrorSymbol = null;
  114969. }
  114970. break;
  114971. case 2:
  114972. len = this.productions_[action[1]][1];
  114973. yyval.$ = vstack[vstack.length - len];
  114974. 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 };
  114975. if (ranges) {
  114976. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  114977. }
  114978. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  114979. if (typeof r !== "undefined") {
  114980. return r;
  114981. }
  114982. if (len) {
  114983. stack = stack.slice(0, -1 * len * 2);
  114984. vstack = vstack.slice(0, -1 * len);
  114985. lstack = lstack.slice(0, -1 * len);
  114986. }
  114987. stack.push(this.productions_[action[1]][0]);
  114988. vstack.push(yyval.$);
  114989. lstack.push(yyval._$);
  114990. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  114991. stack.push(newState);
  114992. break;
  114993. case 3:
  114994. return true;
  114995. }
  114996. }
  114997. return true;
  114998. }
  114999. };
  115000. /* Jison generated lexer */
  115001. var lexer = (function () {
  115002. var lexer = { EOF: 1,
  115003. parseError: function parseError(str, hash) {
  115004. if (this.yy.parser) {
  115005. this.yy.parser.parseError(str, hash);
  115006. } else {
  115007. throw new Error(str);
  115008. }
  115009. },
  115010. setInput: function setInput(input) {
  115011. this._input = input;
  115012. this._more = this._less = this.done = false;
  115013. this.yylineno = this.yyleng = 0;
  115014. this.yytext = this.matched = this.match = '';
  115015. this.conditionStack = ['INITIAL'];
  115016. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  115017. if (this.options.ranges) this.yylloc.range = [0, 0];
  115018. this.offset = 0;
  115019. return this;
  115020. },
  115021. input: function input() {
  115022. var ch = this._input[0];
  115023. this.yytext += ch;
  115024. this.yyleng++;
  115025. this.offset++;
  115026. this.match += ch;
  115027. this.matched += ch;
  115028. var lines = ch.match(/(?:\r\n?|\n).*/g);
  115029. if (lines) {
  115030. this.yylineno++;
  115031. this.yylloc.last_line++;
  115032. } else {
  115033. this.yylloc.last_column++;
  115034. }
  115035. if (this.options.ranges) this.yylloc.range[1]++;
  115036. this._input = this._input.slice(1);
  115037. return ch;
  115038. },
  115039. unput: function unput(ch) {
  115040. var len = ch.length;
  115041. var lines = ch.split(/(?:\r\n?|\n)/g);
  115042. this._input = ch + this._input;
  115043. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  115044. //this.yyleng -= len;
  115045. this.offset -= len;
  115046. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  115047. this.match = this.match.substr(0, this.match.length - 1);
  115048. this.matched = this.matched.substr(0, this.matched.length - 1);
  115049. if (lines.length - 1) this.yylineno -= lines.length - 1;
  115050. var r = this.yylloc.range;
  115051. this.yylloc = { first_line: this.yylloc.first_line,
  115052. last_line: this.yylineno + 1,
  115053. first_column: this.yylloc.first_column,
  115054. 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
  115055. };
  115056. if (this.options.ranges) {
  115057. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  115058. }
  115059. return this;
  115060. },
  115061. more: function more() {
  115062. this._more = true;
  115063. return this;
  115064. },
  115065. less: function less(n) {
  115066. this.unput(this.match.slice(n));
  115067. },
  115068. pastInput: function pastInput() {
  115069. var past = this.matched.substr(0, this.matched.length - this.match.length);
  115070. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  115071. },
  115072. upcomingInput: function upcomingInput() {
  115073. var next = this.match;
  115074. if (next.length < 20) {
  115075. next += this._input.substr(0, 20 - next.length);
  115076. }
  115077. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  115078. },
  115079. showPosition: function showPosition() {
  115080. var pre = this.pastInput();
  115081. var c = new Array(pre.length + 1).join("-");
  115082. return pre + this.upcomingInput() + "\n" + c + "^";
  115083. },
  115084. next: function next() {
  115085. if (this.done) {
  115086. return this.EOF;
  115087. }
  115088. if (!this._input) this.done = true;
  115089. var token, match, tempMatch, index, col, lines;
  115090. if (!this._more) {
  115091. this.yytext = '';
  115092. this.match = '';
  115093. }
  115094. var rules = this._currentRules();
  115095. for (var i = 0; i < rules.length; i++) {
  115096. tempMatch = this._input.match(this.rules[rules[i]]);
  115097. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  115098. match = tempMatch;
  115099. index = i;
  115100. if (!this.options.flex) break;
  115101. }
  115102. }
  115103. if (match) {
  115104. lines = match[0].match(/(?:\r\n?|\n).*/g);
  115105. if (lines) this.yylineno += lines.length;
  115106. this.yylloc = { first_line: this.yylloc.last_line,
  115107. last_line: this.yylineno + 1,
  115108. first_column: this.yylloc.last_column,
  115109. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  115110. this.yytext += match[0];
  115111. this.match += match[0];
  115112. this.matches = match;
  115113. this.yyleng = this.yytext.length;
  115114. if (this.options.ranges) {
  115115. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  115116. }
  115117. this._more = false;
  115118. this._input = this._input.slice(match[0].length);
  115119. this.matched += match[0];
  115120. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  115121. if (this.done && this._input) this.done = false;
  115122. if (token) return token;else return;
  115123. }
  115124. if (this._input === "") {
  115125. return this.EOF;
  115126. } else {
  115127. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  115128. }
  115129. },
  115130. lex: function lex() {
  115131. var r = this.next();
  115132. if (typeof r !== 'undefined') {
  115133. return r;
  115134. } else {
  115135. return this.lex();
  115136. }
  115137. },
  115138. begin: function begin(condition) {
  115139. this.conditionStack.push(condition);
  115140. },
  115141. popState: function popState() {
  115142. return this.conditionStack.pop();
  115143. },
  115144. _currentRules: function _currentRules() {
  115145. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  115146. },
  115147. topState: function topState() {
  115148. return this.conditionStack[this.conditionStack.length - 2];
  115149. },
  115150. pushState: function begin(condition) {
  115151. this.begin(condition);
  115152. } };
  115153. lexer.options = {};
  115154. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  115155. /**/) {
  115156. function strip(start, end) {
  115157. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  115158. }
  115159. var YYSTATE = YY_START;
  115160. switch ($avoiding_name_collisions) {
  115161. case 0:
  115162. if (yy_.yytext.slice(-2) === "\\\\") {
  115163. strip(0, 1);
  115164. this.begin("mu");
  115165. } else if (yy_.yytext.slice(-1) === "\\") {
  115166. strip(0, 1);
  115167. this.begin("emu");
  115168. } else {
  115169. this.begin("mu");
  115170. }
  115171. if (yy_.yytext) return 15;
  115172. break;
  115173. case 1:
  115174. return 15;
  115175. break;
  115176. case 2:
  115177. this.popState();
  115178. return 15;
  115179. break;
  115180. case 3:
  115181. this.begin('raw');return 15;
  115182. break;
  115183. case 4:
  115184. this.popState();
  115185. // Should be using `this.topState()` below, but it currently
  115186. // returns the second top instead of the first top. Opened an
  115187. // issue about it at https://github.com/zaach/jison/issues/291
  115188. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  115189. return 15;
  115190. } else {
  115191. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  115192. return 'END_RAW_BLOCK';
  115193. }
  115194. break;
  115195. case 5:
  115196. return 15;
  115197. break;
  115198. case 6:
  115199. this.popState();
  115200. return 14;
  115201. break;
  115202. case 7:
  115203. return 65;
  115204. break;
  115205. case 8:
  115206. return 68;
  115207. break;
  115208. case 9:
  115209. return 19;
  115210. break;
  115211. case 10:
  115212. this.popState();
  115213. this.begin('raw');
  115214. return 23;
  115215. break;
  115216. case 11:
  115217. return 55;
  115218. break;
  115219. case 12:
  115220. return 60;
  115221. break;
  115222. case 13:
  115223. return 29;
  115224. break;
  115225. case 14:
  115226. return 47;
  115227. break;
  115228. case 15:
  115229. this.popState();return 44;
  115230. break;
  115231. case 16:
  115232. this.popState();return 44;
  115233. break;
  115234. case 17:
  115235. return 34;
  115236. break;
  115237. case 18:
  115238. return 39;
  115239. break;
  115240. case 19:
  115241. return 51;
  115242. break;
  115243. case 20:
  115244. return 48;
  115245. break;
  115246. case 21:
  115247. this.unput(yy_.yytext);
  115248. this.popState();
  115249. this.begin('com');
  115250. break;
  115251. case 22:
  115252. this.popState();
  115253. return 14;
  115254. break;
  115255. case 23:
  115256. return 48;
  115257. break;
  115258. case 24:
  115259. return 73;
  115260. break;
  115261. case 25:
  115262. return 72;
  115263. break;
  115264. case 26:
  115265. return 72;
  115266. break;
  115267. case 27:
  115268. return 87;
  115269. break;
  115270. case 28:
  115271. // ignore whitespace
  115272. break;
  115273. case 29:
  115274. this.popState();return 54;
  115275. break;
  115276. case 30:
  115277. this.popState();return 33;
  115278. break;
  115279. case 31:
  115280. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  115281. break;
  115282. case 32:
  115283. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  115284. break;
  115285. case 33:
  115286. return 85;
  115287. break;
  115288. case 34:
  115289. return 82;
  115290. break;
  115291. case 35:
  115292. return 82;
  115293. break;
  115294. case 36:
  115295. return 83;
  115296. break;
  115297. case 37:
  115298. return 84;
  115299. break;
  115300. case 38:
  115301. return 81;
  115302. break;
  115303. case 39:
  115304. return 75;
  115305. break;
  115306. case 40:
  115307. return 77;
  115308. break;
  115309. case 41:
  115310. return 72;
  115311. break;
  115312. case 42:
  115313. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  115314. break;
  115315. case 43:
  115316. return 'INVALID';
  115317. break;
  115318. case 44:
  115319. return 5;
  115320. break;
  115321. }
  115322. };
  115323. 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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  115324. 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 } };
  115325. return lexer;
  115326. })();
  115327. parser.lexer = lexer;
  115328. function Parser() {
  115329. this.yy = {};
  115330. }Parser.prototype = parser;parser.Parser = Parser;
  115331. return new Parser();
  115332. })();exports["default"] = handlebars;
  115333. module.exports = exports["default"];
  115334. /***/ }),
  115335. /* 38 */
  115336. /***/ (function(module, exports, __webpack_require__) {
  115337. 'use strict';
  115338. var _interopRequireDefault = __webpack_require__(1)['default'];
  115339. exports.__esModule = true;
  115340. var _visitor = __webpack_require__(39);
  115341. var _visitor2 = _interopRequireDefault(_visitor);
  115342. function WhitespaceControl() {
  115343. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  115344. this.options = options;
  115345. }
  115346. WhitespaceControl.prototype = new _visitor2['default']();
  115347. WhitespaceControl.prototype.Program = function (program) {
  115348. var doStandalone = !this.options.ignoreStandalone;
  115349. var isRoot = !this.isRootSeen;
  115350. this.isRootSeen = true;
  115351. var body = program.body;
  115352. for (var i = 0, l = body.length; i < l; i++) {
  115353. var current = body[i],
  115354. strip = this.accept(current);
  115355. if (!strip) {
  115356. continue;
  115357. }
  115358. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  115359. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  115360. openStandalone = strip.openStandalone && _isPrevWhitespace,
  115361. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  115362. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  115363. if (strip.close) {
  115364. omitRight(body, i, true);
  115365. }
  115366. if (strip.open) {
  115367. omitLeft(body, i, true);
  115368. }
  115369. if (doStandalone && inlineStandalone) {
  115370. omitRight(body, i);
  115371. if (omitLeft(body, i)) {
  115372. // If we are on a standalone node, save the indent info for partials
  115373. if (current.type === 'PartialStatement') {
  115374. // Pull out the whitespace from the final line
  115375. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  115376. }
  115377. }
  115378. }
  115379. if (doStandalone && openStandalone) {
  115380. omitRight((current.program || current.inverse).body);
  115381. // Strip out the previous content node if it's whitespace only
  115382. omitLeft(body, i);
  115383. }
  115384. if (doStandalone && closeStandalone) {
  115385. // Always strip the next node
  115386. omitRight(body, i);
  115387. omitLeft((current.inverse || current.program).body);
  115388. }
  115389. }
  115390. return program;
  115391. };
  115392. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  115393. this.accept(block.program);
  115394. this.accept(block.inverse);
  115395. // Find the inverse program that is involed with whitespace stripping.
  115396. var program = block.program || block.inverse,
  115397. inverse = block.program && block.inverse,
  115398. firstInverse = inverse,
  115399. lastInverse = inverse;
  115400. if (inverse && inverse.chained) {
  115401. firstInverse = inverse.body[0].program;
  115402. // Walk the inverse chain to find the last inverse that is actually in the chain.
  115403. while (lastInverse.chained) {
  115404. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  115405. }
  115406. }
  115407. var strip = {
  115408. open: block.openStrip.open,
  115409. close: block.closeStrip.close,
  115410. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  115411. // so our parent can determine if we actually are standalone
  115412. openStandalone: isNextWhitespace(program.body),
  115413. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  115414. };
  115415. if (block.openStrip.close) {
  115416. omitRight(program.body, null, true);
  115417. }
  115418. if (inverse) {
  115419. var inverseStrip = block.inverseStrip;
  115420. if (inverseStrip.open) {
  115421. omitLeft(program.body, null, true);
  115422. }
  115423. if (inverseStrip.close) {
  115424. omitRight(firstInverse.body, null, true);
  115425. }
  115426. if (block.closeStrip.open) {
  115427. omitLeft(lastInverse.body, null, true);
  115428. }
  115429. // Find standalone else statments
  115430. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  115431. omitLeft(program.body);
  115432. omitRight(firstInverse.body);
  115433. }
  115434. } else if (block.closeStrip.open) {
  115435. omitLeft(program.body, null, true);
  115436. }
  115437. return strip;
  115438. };
  115439. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  115440. return mustache.strip;
  115441. };
  115442. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  115443. /* istanbul ignore next */
  115444. var strip = node.strip || {};
  115445. return {
  115446. inlineStandalone: true,
  115447. open: strip.open,
  115448. close: strip.close
  115449. };
  115450. };
  115451. function isPrevWhitespace(body, i, isRoot) {
  115452. if (i === undefined) {
  115453. i = body.length;
  115454. }
  115455. // Nodes that end with newlines are considered whitespace (but are special
  115456. // cased for strip operations)
  115457. var prev = body[i - 1],
  115458. sibling = body[i - 2];
  115459. if (!prev) {
  115460. return isRoot;
  115461. }
  115462. if (prev.type === 'ContentStatement') {
  115463. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  115464. }
  115465. }
  115466. function isNextWhitespace(body, i, isRoot) {
  115467. if (i === undefined) {
  115468. i = -1;
  115469. }
  115470. var next = body[i + 1],
  115471. sibling = body[i + 2];
  115472. if (!next) {
  115473. return isRoot;
  115474. }
  115475. if (next.type === 'ContentStatement') {
  115476. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  115477. }
  115478. }
  115479. // Marks the node to the right of the position as omitted.
  115480. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  115481. //
  115482. // If i is undefined, then the first child will be marked as such.
  115483. //
  115484. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115485. // content is met.
  115486. function omitRight(body, i, multiple) {
  115487. var current = body[i == null ? 0 : i + 1];
  115488. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  115489. return;
  115490. }
  115491. var original = current.value;
  115492. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  115493. current.rightStripped = current.value !== original;
  115494. }
  115495. // Marks the node to the left of the position as omitted.
  115496. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  115497. //
  115498. // If i is undefined then the last child will be marked as such.
  115499. //
  115500. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115501. // content is met.
  115502. function omitLeft(body, i, multiple) {
  115503. var current = body[i == null ? body.length - 1 : i - 1];
  115504. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  115505. return;
  115506. }
  115507. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  115508. var original = current.value;
  115509. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  115510. current.leftStripped = current.value !== original;
  115511. return current.leftStripped;
  115512. }
  115513. exports['default'] = WhitespaceControl;
  115514. module.exports = exports['default'];
  115515. /***/ }),
  115516. /* 39 */
  115517. /***/ (function(module, exports, __webpack_require__) {
  115518. 'use strict';
  115519. var _interopRequireDefault = __webpack_require__(1)['default'];
  115520. exports.__esModule = true;
  115521. var _exception = __webpack_require__(6);
  115522. var _exception2 = _interopRequireDefault(_exception);
  115523. function Visitor() {
  115524. this.parents = [];
  115525. }
  115526. Visitor.prototype = {
  115527. constructor: Visitor,
  115528. mutating: false,
  115529. // Visits a given value. If mutating, will replace the value if necessary.
  115530. acceptKey: function acceptKey(node, name) {
  115531. var value = this.accept(node[name]);
  115532. if (this.mutating) {
  115533. // Hacky sanity check: This may have a few false positives for type for the helper
  115534. // methods but will generally do the right thing without a lot of overhead.
  115535. if (value && !Visitor.prototype[value.type]) {
  115536. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  115537. }
  115538. node[name] = value;
  115539. }
  115540. },
  115541. // Performs an accept operation with added sanity check to ensure
  115542. // required keys are not removed.
  115543. acceptRequired: function acceptRequired(node, name) {
  115544. this.acceptKey(node, name);
  115545. if (!node[name]) {
  115546. throw new _exception2['default'](node.type + ' requires ' + name);
  115547. }
  115548. },
  115549. // Traverses a given array. If mutating, empty respnses will be removed
  115550. // for child elements.
  115551. acceptArray: function acceptArray(array) {
  115552. for (var i = 0, l = array.length; i < l; i++) {
  115553. this.acceptKey(array, i);
  115554. if (!array[i]) {
  115555. array.splice(i, 1);
  115556. i--;
  115557. l--;
  115558. }
  115559. }
  115560. },
  115561. accept: function accept(object) {
  115562. if (!object) {
  115563. return;
  115564. }
  115565. /* istanbul ignore next: Sanity code */
  115566. if (!this[object.type]) {
  115567. throw new _exception2['default']('Unknown type: ' + object.type, object);
  115568. }
  115569. if (this.current) {
  115570. this.parents.unshift(this.current);
  115571. }
  115572. this.current = object;
  115573. var ret = this[object.type](object);
  115574. this.current = this.parents.shift();
  115575. if (!this.mutating || ret) {
  115576. return ret;
  115577. } else if (ret !== false) {
  115578. return object;
  115579. }
  115580. },
  115581. Program: function Program(program) {
  115582. this.acceptArray(program.body);
  115583. },
  115584. MustacheStatement: visitSubExpression,
  115585. Decorator: visitSubExpression,
  115586. BlockStatement: visitBlock,
  115587. DecoratorBlock: visitBlock,
  115588. PartialStatement: visitPartial,
  115589. PartialBlockStatement: function PartialBlockStatement(partial) {
  115590. visitPartial.call(this, partial);
  115591. this.acceptKey(partial, 'program');
  115592. },
  115593. ContentStatement: function ContentStatement() /* content */{},
  115594. CommentStatement: function CommentStatement() /* comment */{},
  115595. SubExpression: visitSubExpression,
  115596. PathExpression: function PathExpression() /* path */{},
  115597. StringLiteral: function StringLiteral() /* string */{},
  115598. NumberLiteral: function NumberLiteral() /* number */{},
  115599. BooleanLiteral: function BooleanLiteral() /* bool */{},
  115600. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  115601. NullLiteral: function NullLiteral() /* literal */{},
  115602. Hash: function Hash(hash) {
  115603. this.acceptArray(hash.pairs);
  115604. },
  115605. HashPair: function HashPair(pair) {
  115606. this.acceptRequired(pair, 'value');
  115607. }
  115608. };
  115609. function visitSubExpression(mustache) {
  115610. this.acceptRequired(mustache, 'path');
  115611. this.acceptArray(mustache.params);
  115612. this.acceptKey(mustache, 'hash');
  115613. }
  115614. function visitBlock(block) {
  115615. visitSubExpression.call(this, block);
  115616. this.acceptKey(block, 'program');
  115617. this.acceptKey(block, 'inverse');
  115618. }
  115619. function visitPartial(partial) {
  115620. this.acceptRequired(partial, 'name');
  115621. this.acceptArray(partial.params);
  115622. this.acceptKey(partial, 'hash');
  115623. }
  115624. exports['default'] = Visitor;
  115625. module.exports = exports['default'];
  115626. /***/ }),
  115627. /* 40 */
  115628. /***/ (function(module, exports, __webpack_require__) {
  115629. 'use strict';
  115630. var _interopRequireDefault = __webpack_require__(1)['default'];
  115631. exports.__esModule = true;
  115632. exports.SourceLocation = SourceLocation;
  115633. exports.id = id;
  115634. exports.stripFlags = stripFlags;
  115635. exports.stripComment = stripComment;
  115636. exports.preparePath = preparePath;
  115637. exports.prepareMustache = prepareMustache;
  115638. exports.prepareRawBlock = prepareRawBlock;
  115639. exports.prepareBlock = prepareBlock;
  115640. exports.prepareProgram = prepareProgram;
  115641. exports.preparePartialBlock = preparePartialBlock;
  115642. var _exception = __webpack_require__(6);
  115643. var _exception2 = _interopRequireDefault(_exception);
  115644. function validateClose(open, close) {
  115645. close = close.path ? close.path.original : close;
  115646. if (open.path.original !== close) {
  115647. var errorNode = { loc: open.path.loc };
  115648. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  115649. }
  115650. }
  115651. function SourceLocation(source, locInfo) {
  115652. this.source = source;
  115653. this.start = {
  115654. line: locInfo.first_line,
  115655. column: locInfo.first_column
  115656. };
  115657. this.end = {
  115658. line: locInfo.last_line,
  115659. column: locInfo.last_column
  115660. };
  115661. }
  115662. function id(token) {
  115663. if (/^\[.*\]$/.test(token)) {
  115664. return token.substr(1, token.length - 2);
  115665. } else {
  115666. return token;
  115667. }
  115668. }
  115669. function stripFlags(open, close) {
  115670. return {
  115671. open: open.charAt(2) === '~',
  115672. close: close.charAt(close.length - 3) === '~'
  115673. };
  115674. }
  115675. function stripComment(comment) {
  115676. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  115677. }
  115678. function preparePath(data, parts, loc) {
  115679. loc = this.locInfo(loc);
  115680. var original = data ? '@' : '',
  115681. dig = [],
  115682. depth = 0,
  115683. depthString = '';
  115684. for (var i = 0, l = parts.length; i < l; i++) {
  115685. var part = parts[i].part,
  115686. // If we have [] syntax then we do not treat path references as operators,
  115687. // i.e. foo.[this] resolves to approximately context.foo['this']
  115688. isLiteral = parts[i].original !== part;
  115689. original += (parts[i].separator || '') + part;
  115690. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  115691. if (dig.length > 0) {
  115692. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  115693. } else if (part === '..') {
  115694. depth++;
  115695. depthString += '../';
  115696. }
  115697. } else {
  115698. dig.push(part);
  115699. }
  115700. }
  115701. return {
  115702. type: 'PathExpression',
  115703. data: data,
  115704. depth: depth,
  115705. parts: dig,
  115706. original: original,
  115707. loc: loc
  115708. };
  115709. }
  115710. function prepareMustache(path, params, hash, open, strip, locInfo) {
  115711. // Must use charAt to support IE pre-10
  115712. var escapeFlag = open.charAt(3) || open.charAt(2),
  115713. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  115714. var decorator = /\*/.test(open);
  115715. return {
  115716. type: decorator ? 'Decorator' : 'MustacheStatement',
  115717. path: path,
  115718. params: params,
  115719. hash: hash,
  115720. escaped: escaped,
  115721. strip: strip,
  115722. loc: this.locInfo(locInfo)
  115723. };
  115724. }
  115725. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  115726. validateClose(openRawBlock, close);
  115727. locInfo = this.locInfo(locInfo);
  115728. var program = {
  115729. type: 'Program',
  115730. body: contents,
  115731. strip: {},
  115732. loc: locInfo
  115733. };
  115734. return {
  115735. type: 'BlockStatement',
  115736. path: openRawBlock.path,
  115737. params: openRawBlock.params,
  115738. hash: openRawBlock.hash,
  115739. program: program,
  115740. openStrip: {},
  115741. inverseStrip: {},
  115742. closeStrip: {},
  115743. loc: locInfo
  115744. };
  115745. }
  115746. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  115747. if (close && close.path) {
  115748. validateClose(openBlock, close);
  115749. }
  115750. var decorator = /\*/.test(openBlock.open);
  115751. program.blockParams = openBlock.blockParams;
  115752. var inverse = undefined,
  115753. inverseStrip = undefined;
  115754. if (inverseAndProgram) {
  115755. if (decorator) {
  115756. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  115757. }
  115758. if (inverseAndProgram.chain) {
  115759. inverseAndProgram.program.body[0].closeStrip = close.strip;
  115760. }
  115761. inverseStrip = inverseAndProgram.strip;
  115762. inverse = inverseAndProgram.program;
  115763. }
  115764. if (inverted) {
  115765. inverted = inverse;
  115766. inverse = program;
  115767. program = inverted;
  115768. }
  115769. return {
  115770. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  115771. path: openBlock.path,
  115772. params: openBlock.params,
  115773. hash: openBlock.hash,
  115774. program: program,
  115775. inverse: inverse,
  115776. openStrip: openBlock.strip,
  115777. inverseStrip: inverseStrip,
  115778. closeStrip: close && close.strip,
  115779. loc: this.locInfo(locInfo)
  115780. };
  115781. }
  115782. function prepareProgram(statements, loc) {
  115783. if (!loc && statements.length) {
  115784. var firstLoc = statements[0].loc,
  115785. lastLoc = statements[statements.length - 1].loc;
  115786. /* istanbul ignore else */
  115787. if (firstLoc && lastLoc) {
  115788. loc = {
  115789. source: firstLoc.source,
  115790. start: {
  115791. line: firstLoc.start.line,
  115792. column: firstLoc.start.column
  115793. },
  115794. end: {
  115795. line: lastLoc.end.line,
  115796. column: lastLoc.end.column
  115797. }
  115798. };
  115799. }
  115800. }
  115801. return {
  115802. type: 'Program',
  115803. body: statements,
  115804. strip: {},
  115805. loc: loc
  115806. };
  115807. }
  115808. function preparePartialBlock(open, program, close, locInfo) {
  115809. validateClose(open, close);
  115810. return {
  115811. type: 'PartialBlockStatement',
  115812. name: open.path,
  115813. params: open.params,
  115814. hash: open.hash,
  115815. program: program,
  115816. openStrip: open.strip,
  115817. closeStrip: close && close.strip,
  115818. loc: this.locInfo(locInfo)
  115819. };
  115820. }
  115821. /***/ }),
  115822. /* 41 */
  115823. /***/ (function(module, exports, __webpack_require__) {
  115824. /* eslint-disable new-cap */
  115825. 'use strict';
  115826. var _interopRequireDefault = __webpack_require__(1)['default'];
  115827. exports.__esModule = true;
  115828. exports.Compiler = Compiler;
  115829. exports.precompile = precompile;
  115830. exports.compile = compile;
  115831. var _exception = __webpack_require__(6);
  115832. var _exception2 = _interopRequireDefault(_exception);
  115833. var _utils = __webpack_require__(5);
  115834. var _ast = __webpack_require__(35);
  115835. var _ast2 = _interopRequireDefault(_ast);
  115836. var slice = [].slice;
  115837. function Compiler() {}
  115838. // the foundHelper register will disambiguate helper lookup from finding a
  115839. // function in a context. This is necessary for mustache compatibility, which
  115840. // requires that context functions in blocks are evaluated by blockHelperMissing,
  115841. // and then proceed as if the resulting value was provided to blockHelperMissing.
  115842. Compiler.prototype = {
  115843. compiler: Compiler,
  115844. equals: function equals(other) {
  115845. var len = this.opcodes.length;
  115846. if (other.opcodes.length !== len) {
  115847. return false;
  115848. }
  115849. for (var i = 0; i < len; i++) {
  115850. var opcode = this.opcodes[i],
  115851. otherOpcode = other.opcodes[i];
  115852. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  115853. return false;
  115854. }
  115855. }
  115856. // We know that length is the same between the two arrays because they are directly tied
  115857. // to the opcode behavior above.
  115858. len = this.children.length;
  115859. for (var i = 0; i < len; i++) {
  115860. if (!this.children[i].equals(other.children[i])) {
  115861. return false;
  115862. }
  115863. }
  115864. return true;
  115865. },
  115866. guid: 0,
  115867. compile: function compile(program, options) {
  115868. this.sourceNode = [];
  115869. this.opcodes = [];
  115870. this.children = [];
  115871. this.options = options;
  115872. this.stringParams = options.stringParams;
  115873. this.trackIds = options.trackIds;
  115874. options.blockParams = options.blockParams || [];
  115875. // These changes will propagate to the other compiler components
  115876. var knownHelpers = options.knownHelpers;
  115877. options.knownHelpers = {
  115878. 'helperMissing': true,
  115879. 'blockHelperMissing': true,
  115880. 'each': true,
  115881. 'if': true,
  115882. 'unless': true,
  115883. 'with': true,
  115884. 'log': true,
  115885. 'lookup': true
  115886. };
  115887. if (knownHelpers) {
  115888. for (var _name in knownHelpers) {
  115889. /* istanbul ignore else */
  115890. if (_name in knownHelpers) {
  115891. this.options.knownHelpers[_name] = knownHelpers[_name];
  115892. }
  115893. }
  115894. }
  115895. return this.accept(program);
  115896. },
  115897. compileProgram: function compileProgram(program) {
  115898. var childCompiler = new this.compiler(),
  115899. // eslint-disable-line new-cap
  115900. result = childCompiler.compile(program, this.options),
  115901. guid = this.guid++;
  115902. this.usePartial = this.usePartial || result.usePartial;
  115903. this.children[guid] = result;
  115904. this.useDepths = this.useDepths || result.useDepths;
  115905. return guid;
  115906. },
  115907. accept: function accept(node) {
  115908. /* istanbul ignore next: Sanity code */
  115909. if (!this[node.type]) {
  115910. throw new _exception2['default']('Unknown type: ' + node.type, node);
  115911. }
  115912. this.sourceNode.unshift(node);
  115913. var ret = this[node.type](node);
  115914. this.sourceNode.shift();
  115915. return ret;
  115916. },
  115917. Program: function Program(program) {
  115918. this.options.blockParams.unshift(program.blockParams);
  115919. var body = program.body,
  115920. bodyLength = body.length;
  115921. for (var i = 0; i < bodyLength; i++) {
  115922. this.accept(body[i]);
  115923. }
  115924. this.options.blockParams.shift();
  115925. this.isSimple = bodyLength === 1;
  115926. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  115927. return this;
  115928. },
  115929. BlockStatement: function BlockStatement(block) {
  115930. transformLiteralToPath(block);
  115931. var program = block.program,
  115932. inverse = block.inverse;
  115933. program = program && this.compileProgram(program);
  115934. inverse = inverse && this.compileProgram(inverse);
  115935. var type = this.classifySexpr(block);
  115936. if (type === 'helper') {
  115937. this.helperSexpr(block, program, inverse);
  115938. } else if (type === 'simple') {
  115939. this.simpleSexpr(block);
  115940. // now that the simple mustache is resolved, we need to
  115941. // evaluate it by executing `blockHelperMissing`
  115942. this.opcode('pushProgram', program);
  115943. this.opcode('pushProgram', inverse);
  115944. this.opcode('emptyHash');
  115945. this.opcode('blockValue', block.path.original);
  115946. } else {
  115947. this.ambiguousSexpr(block, program, inverse);
  115948. // now that the simple mustache is resolved, we need to
  115949. // evaluate it by executing `blockHelperMissing`
  115950. this.opcode('pushProgram', program);
  115951. this.opcode('pushProgram', inverse);
  115952. this.opcode('emptyHash');
  115953. this.opcode('ambiguousBlockValue');
  115954. }
  115955. this.opcode('append');
  115956. },
  115957. DecoratorBlock: function DecoratorBlock(decorator) {
  115958. var program = decorator.program && this.compileProgram(decorator.program);
  115959. var params = this.setupFullMustacheParams(decorator, program, undefined),
  115960. path = decorator.path;
  115961. this.useDecorators = true;
  115962. this.opcode('registerDecorator', params.length, path.original);
  115963. },
  115964. PartialStatement: function PartialStatement(partial) {
  115965. this.usePartial = true;
  115966. var program = partial.program;
  115967. if (program) {
  115968. program = this.compileProgram(partial.program);
  115969. }
  115970. var params = partial.params;
  115971. if (params.length > 1) {
  115972. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  115973. } else if (!params.length) {
  115974. if (this.options.explicitPartialContext) {
  115975. this.opcode('pushLiteral', 'undefined');
  115976. } else {
  115977. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  115978. }
  115979. }
  115980. var partialName = partial.name.original,
  115981. isDynamic = partial.name.type === 'SubExpression';
  115982. if (isDynamic) {
  115983. this.accept(partial.name);
  115984. }
  115985. this.setupFullMustacheParams(partial, program, undefined, true);
  115986. var indent = partial.indent || '';
  115987. if (this.options.preventIndent && indent) {
  115988. this.opcode('appendContent', indent);
  115989. indent = '';
  115990. }
  115991. this.opcode('invokePartial', isDynamic, partialName, indent);
  115992. this.opcode('append');
  115993. },
  115994. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  115995. this.PartialStatement(partialBlock);
  115996. },
  115997. MustacheStatement: function MustacheStatement(mustache) {
  115998. this.SubExpression(mustache);
  115999. if (mustache.escaped && !this.options.noEscape) {
  116000. this.opcode('appendEscaped');
  116001. } else {
  116002. this.opcode('append');
  116003. }
  116004. },
  116005. Decorator: function Decorator(decorator) {
  116006. this.DecoratorBlock(decorator);
  116007. },
  116008. ContentStatement: function ContentStatement(content) {
  116009. if (content.value) {
  116010. this.opcode('appendContent', content.value);
  116011. }
  116012. },
  116013. CommentStatement: function CommentStatement() {},
  116014. SubExpression: function SubExpression(sexpr) {
  116015. transformLiteralToPath(sexpr);
  116016. var type = this.classifySexpr(sexpr);
  116017. if (type === 'simple') {
  116018. this.simpleSexpr(sexpr);
  116019. } else if (type === 'helper') {
  116020. this.helperSexpr(sexpr);
  116021. } else {
  116022. this.ambiguousSexpr(sexpr);
  116023. }
  116024. },
  116025. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  116026. var path = sexpr.path,
  116027. name = path.parts[0],
  116028. isBlock = program != null || inverse != null;
  116029. this.opcode('getContext', path.depth);
  116030. this.opcode('pushProgram', program);
  116031. this.opcode('pushProgram', inverse);
  116032. path.strict = true;
  116033. this.accept(path);
  116034. this.opcode('invokeAmbiguous', name, isBlock);
  116035. },
  116036. simpleSexpr: function simpleSexpr(sexpr) {
  116037. var path = sexpr.path;
  116038. path.strict = true;
  116039. this.accept(path);
  116040. this.opcode('resolvePossibleLambda');
  116041. },
  116042. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  116043. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  116044. path = sexpr.path,
  116045. name = path.parts[0];
  116046. if (this.options.knownHelpers[name]) {
  116047. this.opcode('invokeKnownHelper', params.length, name);
  116048. } else if (this.options.knownHelpersOnly) {
  116049. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  116050. } else {
  116051. path.strict = true;
  116052. path.falsy = true;
  116053. this.accept(path);
  116054. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  116055. }
  116056. },
  116057. PathExpression: function PathExpression(path) {
  116058. this.addDepth(path.depth);
  116059. this.opcode('getContext', path.depth);
  116060. var name = path.parts[0],
  116061. scoped = _ast2['default'].helpers.scopedId(path),
  116062. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  116063. if (blockParamId) {
  116064. this.opcode('lookupBlockParam', blockParamId, path.parts);
  116065. } else if (!name) {
  116066. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  116067. this.opcode('pushContext');
  116068. } else if (path.data) {
  116069. this.options.data = true;
  116070. this.opcode('lookupData', path.depth, path.parts, path.strict);
  116071. } else {
  116072. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  116073. }
  116074. },
  116075. StringLiteral: function StringLiteral(string) {
  116076. this.opcode('pushString', string.value);
  116077. },
  116078. NumberLiteral: function NumberLiteral(number) {
  116079. this.opcode('pushLiteral', number.value);
  116080. },
  116081. BooleanLiteral: function BooleanLiteral(bool) {
  116082. this.opcode('pushLiteral', bool.value);
  116083. },
  116084. UndefinedLiteral: function UndefinedLiteral() {
  116085. this.opcode('pushLiteral', 'undefined');
  116086. },
  116087. NullLiteral: function NullLiteral() {
  116088. this.opcode('pushLiteral', 'null');
  116089. },
  116090. Hash: function Hash(hash) {
  116091. var pairs = hash.pairs,
  116092. i = 0,
  116093. l = pairs.length;
  116094. this.opcode('pushHash');
  116095. for (; i < l; i++) {
  116096. this.pushParam(pairs[i].value);
  116097. }
  116098. while (i--) {
  116099. this.opcode('assignToHash', pairs[i].key);
  116100. }
  116101. this.opcode('popHash');
  116102. },
  116103. // HELPERS
  116104. opcode: function opcode(name) {
  116105. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  116106. },
  116107. addDepth: function addDepth(depth) {
  116108. if (!depth) {
  116109. return;
  116110. }
  116111. this.useDepths = true;
  116112. },
  116113. classifySexpr: function classifySexpr(sexpr) {
  116114. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  116115. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  116116. // a mustache is an eligible helper if:
  116117. // * its id is simple (a single part, not `this` or `..`)
  116118. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  116119. // if a mustache is an eligible helper but not a definite
  116120. // helper, it is ambiguous, and will be resolved in a later
  116121. // pass or at runtime.
  116122. var isEligible = !isBlockParam && (isHelper || isSimple);
  116123. // if ambiguous, we can possibly resolve the ambiguity now
  116124. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  116125. if (isEligible && !isHelper) {
  116126. var _name2 = sexpr.path.parts[0],
  116127. options = this.options;
  116128. if (options.knownHelpers[_name2]) {
  116129. isHelper = true;
  116130. } else if (options.knownHelpersOnly) {
  116131. isEligible = false;
  116132. }
  116133. }
  116134. if (isHelper) {
  116135. return 'helper';
  116136. } else if (isEligible) {
  116137. return 'ambiguous';
  116138. } else {
  116139. return 'simple';
  116140. }
  116141. },
  116142. pushParams: function pushParams(params) {
  116143. for (var i = 0, l = params.length; i < l; i++) {
  116144. this.pushParam(params[i]);
  116145. }
  116146. },
  116147. pushParam: function pushParam(val) {
  116148. var value = val.value != null ? val.value : val.original || '';
  116149. if (this.stringParams) {
  116150. if (value.replace) {
  116151. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  116152. }
  116153. if (val.depth) {
  116154. this.addDepth(val.depth);
  116155. }
  116156. this.opcode('getContext', val.depth || 0);
  116157. this.opcode('pushStringParam', value, val.type);
  116158. if (val.type === 'SubExpression') {
  116159. // SubExpressions get evaluated and passed in
  116160. // in string params mode.
  116161. this.accept(val);
  116162. }
  116163. } else {
  116164. if (this.trackIds) {
  116165. var blockParamIndex = undefined;
  116166. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  116167. blockParamIndex = this.blockParamIndex(val.parts[0]);
  116168. }
  116169. if (blockParamIndex) {
  116170. var blockParamChild = val.parts.slice(1).join('.');
  116171. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  116172. } else {
  116173. value = val.original || value;
  116174. if (value.replace) {
  116175. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  116176. }
  116177. this.opcode('pushId', val.type, value);
  116178. }
  116179. }
  116180. this.accept(val);
  116181. }
  116182. },
  116183. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  116184. var params = sexpr.params;
  116185. this.pushParams(params);
  116186. this.opcode('pushProgram', program);
  116187. this.opcode('pushProgram', inverse);
  116188. if (sexpr.hash) {
  116189. this.accept(sexpr.hash);
  116190. } else {
  116191. this.opcode('emptyHash', omitEmpty);
  116192. }
  116193. return params;
  116194. },
  116195. blockParamIndex: function blockParamIndex(name) {
  116196. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  116197. var blockParams = this.options.blockParams[depth],
  116198. param = blockParams && _utils.indexOf(blockParams, name);
  116199. if (blockParams && param >= 0) {
  116200. return [depth, param];
  116201. }
  116202. }
  116203. }
  116204. };
  116205. function precompile(input, options, env) {
  116206. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116207. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  116208. }
  116209. options = options || {};
  116210. if (!('data' in options)) {
  116211. options.data = true;
  116212. }
  116213. if (options.compat) {
  116214. options.useDepths = true;
  116215. }
  116216. var ast = env.parse(input, options),
  116217. environment = new env.Compiler().compile(ast, options);
  116218. return new env.JavaScriptCompiler().compile(environment, options);
  116219. }
  116220. function compile(input, options, env) {
  116221. if (options === undefined) options = {};
  116222. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116223. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  116224. }
  116225. options = _utils.extend({}, options);
  116226. if (!('data' in options)) {
  116227. options.data = true;
  116228. }
  116229. if (options.compat) {
  116230. options.useDepths = true;
  116231. }
  116232. var compiled = undefined;
  116233. function compileInput() {
  116234. var ast = env.parse(input, options),
  116235. environment = new env.Compiler().compile(ast, options),
  116236. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  116237. return env.template(templateSpec);
  116238. }
  116239. // Template is only compiled on first use and cached after that point.
  116240. function ret(context, execOptions) {
  116241. if (!compiled) {
  116242. compiled = compileInput();
  116243. }
  116244. return compiled.call(this, context, execOptions);
  116245. }
  116246. ret._setup = function (setupOptions) {
  116247. if (!compiled) {
  116248. compiled = compileInput();
  116249. }
  116250. return compiled._setup(setupOptions);
  116251. };
  116252. ret._child = function (i, data, blockParams, depths) {
  116253. if (!compiled) {
  116254. compiled = compileInput();
  116255. }
  116256. return compiled._child(i, data, blockParams, depths);
  116257. };
  116258. return ret;
  116259. }
  116260. function argEquals(a, b) {
  116261. if (a === b) {
  116262. return true;
  116263. }
  116264. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  116265. for (var i = 0; i < a.length; i++) {
  116266. if (!argEquals(a[i], b[i])) {
  116267. return false;
  116268. }
  116269. }
  116270. return true;
  116271. }
  116272. }
  116273. function transformLiteralToPath(sexpr) {
  116274. if (!sexpr.path.parts) {
  116275. var literal = sexpr.path;
  116276. // Casting to string here to make false and 0 literal values play nicely with the rest
  116277. // of the system.
  116278. sexpr.path = {
  116279. type: 'PathExpression',
  116280. data: false,
  116281. depth: 0,
  116282. parts: [literal.original + ''],
  116283. original: literal.original + '',
  116284. loc: literal.loc
  116285. };
  116286. }
  116287. }
  116288. /***/ }),
  116289. /* 42 */
  116290. /***/ (function(module, exports, __webpack_require__) {
  116291. 'use strict';
  116292. var _interopRequireDefault = __webpack_require__(1)['default'];
  116293. exports.__esModule = true;
  116294. var _base = __webpack_require__(4);
  116295. var _exception = __webpack_require__(6);
  116296. var _exception2 = _interopRequireDefault(_exception);
  116297. var _utils = __webpack_require__(5);
  116298. var _codeGen = __webpack_require__(43);
  116299. var _codeGen2 = _interopRequireDefault(_codeGen);
  116300. function Literal(value) {
  116301. this.value = value;
  116302. }
  116303. function JavaScriptCompiler() {}
  116304. JavaScriptCompiler.prototype = {
  116305. // PUBLIC API: You can override these methods in a subclass to provide
  116306. // alternative compiled forms for name lookup and buffering semantics
  116307. nameLookup: function nameLookup(parent, name /* , type*/) {
  116308. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  116309. return [parent, '.', name];
  116310. } else {
  116311. return [parent, '[', JSON.stringify(name), ']'];
  116312. }
  116313. },
  116314. depthedLookup: function depthedLookup(name) {
  116315. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  116316. },
  116317. compilerInfo: function compilerInfo() {
  116318. var revision = _base.COMPILER_REVISION,
  116319. versions = _base.REVISION_CHANGES[revision];
  116320. return [revision, versions];
  116321. },
  116322. appendToBuffer: function appendToBuffer(source, location, explicit) {
  116323. // Force a source as this simplifies the merge logic.
  116324. if (!_utils.isArray(source)) {
  116325. source = [source];
  116326. }
  116327. source = this.source.wrap(source, location);
  116328. if (this.environment.isSimple) {
  116329. return ['return ', source, ';'];
  116330. } else if (explicit) {
  116331. // This is a case where the buffer operation occurs as a child of another
  116332. // construct, generally braces. We have to explicitly output these buffer
  116333. // operations to ensure that the emitted code goes in the correct location.
  116334. return ['buffer += ', source, ';'];
  116335. } else {
  116336. source.appendToBuffer = true;
  116337. return source;
  116338. }
  116339. },
  116340. initializeBuffer: function initializeBuffer() {
  116341. return this.quotedString('');
  116342. },
  116343. // END PUBLIC API
  116344. compile: function compile(environment, options, context, asObject) {
  116345. this.environment = environment;
  116346. this.options = options;
  116347. this.stringParams = this.options.stringParams;
  116348. this.trackIds = this.options.trackIds;
  116349. this.precompile = !asObject;
  116350. this.name = this.environment.name;
  116351. this.isChild = !!context;
  116352. this.context = context || {
  116353. decorators: [],
  116354. programs: [],
  116355. environments: []
  116356. };
  116357. this.preamble();
  116358. this.stackSlot = 0;
  116359. this.stackVars = [];
  116360. this.aliases = {};
  116361. this.registers = { list: [] };
  116362. this.hashes = [];
  116363. this.compileStack = [];
  116364. this.inlineStack = [];
  116365. this.blockParams = [];
  116366. this.compileChildren(environment, options);
  116367. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  116368. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  116369. var opcodes = environment.opcodes,
  116370. opcode = undefined,
  116371. firstLoc = undefined,
  116372. i = undefined,
  116373. l = undefined;
  116374. for (i = 0, l = opcodes.length; i < l; i++) {
  116375. opcode = opcodes[i];
  116376. this.source.currentLocation = opcode.loc;
  116377. firstLoc = firstLoc || opcode.loc;
  116378. this[opcode.opcode].apply(this, opcode.args);
  116379. }
  116380. // Flush any trailing content that might be pending.
  116381. this.source.currentLocation = firstLoc;
  116382. this.pushSource('');
  116383. /* istanbul ignore next */
  116384. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  116385. throw new _exception2['default']('Compile completed with content left on stack');
  116386. }
  116387. if (!this.decorators.isEmpty()) {
  116388. this.useDecorators = true;
  116389. this.decorators.prepend('var decorators = container.decorators;\n');
  116390. this.decorators.push('return fn;');
  116391. if (asObject) {
  116392. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  116393. } else {
  116394. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  116395. this.decorators.push('}\n');
  116396. this.decorators = this.decorators.merge();
  116397. }
  116398. } else {
  116399. this.decorators = undefined;
  116400. }
  116401. var fn = this.createFunctionContext(asObject);
  116402. if (!this.isChild) {
  116403. var ret = {
  116404. compiler: this.compilerInfo(),
  116405. main: fn
  116406. };
  116407. if (this.decorators) {
  116408. ret.main_d = this.decorators; // eslint-disable-line camelcase
  116409. ret.useDecorators = true;
  116410. }
  116411. var _context = this.context;
  116412. var programs = _context.programs;
  116413. var decorators = _context.decorators;
  116414. for (i = 0, l = programs.length; i < l; i++) {
  116415. if (programs[i]) {
  116416. ret[i] = programs[i];
  116417. if (decorators[i]) {
  116418. ret[i + '_d'] = decorators[i];
  116419. ret.useDecorators = true;
  116420. }
  116421. }
  116422. }
  116423. if (this.environment.usePartial) {
  116424. ret.usePartial = true;
  116425. }
  116426. if (this.options.data) {
  116427. ret.useData = true;
  116428. }
  116429. if (this.useDepths) {
  116430. ret.useDepths = true;
  116431. }
  116432. if (this.useBlockParams) {
  116433. ret.useBlockParams = true;
  116434. }
  116435. if (this.options.compat) {
  116436. ret.compat = true;
  116437. }
  116438. if (!asObject) {
  116439. ret.compiler = JSON.stringify(ret.compiler);
  116440. this.source.currentLocation = { start: { line: 1, column: 0 } };
  116441. ret = this.objectLiteral(ret);
  116442. if (options.srcName) {
  116443. ret = ret.toStringWithSourceMap({ file: options.destName });
  116444. ret.map = ret.map && ret.map.toString();
  116445. } else {
  116446. ret = ret.toString();
  116447. }
  116448. } else {
  116449. ret.compilerOptions = this.options;
  116450. }
  116451. return ret;
  116452. } else {
  116453. return fn;
  116454. }
  116455. },
  116456. preamble: function preamble() {
  116457. // track the last context pushed into place to allow skipping the
  116458. // getContext opcode when it would be a noop
  116459. this.lastContext = 0;
  116460. this.source = new _codeGen2['default'](this.options.srcName);
  116461. this.decorators = new _codeGen2['default'](this.options.srcName);
  116462. },
  116463. createFunctionContext: function createFunctionContext(asObject) {
  116464. var varDeclarations = '';
  116465. var locals = this.stackVars.concat(this.registers.list);
  116466. if (locals.length > 0) {
  116467. varDeclarations += ', ' + locals.join(', ');
  116468. }
  116469. // Generate minimizer alias mappings
  116470. //
  116471. // When using true SourceNodes, this will update all references to the given alias
  116472. // as the source nodes are reused in situ. For the non-source node compilation mode,
  116473. // aliases will not be used, but this case is already being run on the client and
  116474. // we aren't concern about minimizing the template size.
  116475. var aliasCount = 0;
  116476. for (var alias in this.aliases) {
  116477. // eslint-disable-line guard-for-in
  116478. var node = this.aliases[alias];
  116479. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  116480. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  116481. node.children[0] = 'alias' + aliasCount;
  116482. }
  116483. }
  116484. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  116485. if (this.useBlockParams || this.useDepths) {
  116486. params.push('blockParams');
  116487. }
  116488. if (this.useDepths) {
  116489. params.push('depths');
  116490. }
  116491. // Perform a second pass over the output to merge content when possible
  116492. var source = this.mergeSource(varDeclarations);
  116493. if (asObject) {
  116494. params.push(source);
  116495. return Function.apply(this, params);
  116496. } else {
  116497. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  116498. }
  116499. },
  116500. mergeSource: function mergeSource(varDeclarations) {
  116501. var isSimple = this.environment.isSimple,
  116502. appendOnly = !this.forceBuffer,
  116503. appendFirst = undefined,
  116504. sourceSeen = undefined,
  116505. bufferStart = undefined,
  116506. bufferEnd = undefined;
  116507. this.source.each(function (line) {
  116508. if (line.appendToBuffer) {
  116509. if (bufferStart) {
  116510. line.prepend(' + ');
  116511. } else {
  116512. bufferStart = line;
  116513. }
  116514. bufferEnd = line;
  116515. } else {
  116516. if (bufferStart) {
  116517. if (!sourceSeen) {
  116518. appendFirst = true;
  116519. } else {
  116520. bufferStart.prepend('buffer += ');
  116521. }
  116522. bufferEnd.add(';');
  116523. bufferStart = bufferEnd = undefined;
  116524. }
  116525. sourceSeen = true;
  116526. if (!isSimple) {
  116527. appendOnly = false;
  116528. }
  116529. }
  116530. });
  116531. if (appendOnly) {
  116532. if (bufferStart) {
  116533. bufferStart.prepend('return ');
  116534. bufferEnd.add(';');
  116535. } else if (!sourceSeen) {
  116536. this.source.push('return "";');
  116537. }
  116538. } else {
  116539. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  116540. if (bufferStart) {
  116541. bufferStart.prepend('return buffer + ');
  116542. bufferEnd.add(';');
  116543. } else {
  116544. this.source.push('return buffer;');
  116545. }
  116546. }
  116547. if (varDeclarations) {
  116548. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  116549. }
  116550. return this.source.merge();
  116551. },
  116552. // [blockValue]
  116553. //
  116554. // On stack, before: hash, inverse, program, value
  116555. // On stack, after: return value of blockHelperMissing
  116556. //
  116557. // The purpose of this opcode is to take a block of the form
  116558. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  116559. // replace it on the stack with the result of properly
  116560. // invoking blockHelperMissing.
  116561. blockValue: function blockValue(name) {
  116562. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116563. params = [this.contextName(0)];
  116564. this.setupHelperArgs(name, 0, params);
  116565. var blockName = this.popStack();
  116566. params.splice(1, 0, blockName);
  116567. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  116568. },
  116569. // [ambiguousBlockValue]
  116570. //
  116571. // On stack, before: hash, inverse, program, value
  116572. // Compiler value, before: lastHelper=value of last found helper, if any
  116573. // On stack, after, if no lastHelper: same as [blockValue]
  116574. // On stack, after, if lastHelper: value
  116575. ambiguousBlockValue: function ambiguousBlockValue() {
  116576. // We're being a bit cheeky and reusing the options value from the prior exec
  116577. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116578. params = [this.contextName(0)];
  116579. this.setupHelperArgs('', 0, params, true);
  116580. this.flushInline();
  116581. var current = this.topStack();
  116582. params.splice(1, 0, current);
  116583. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  116584. },
  116585. // [appendContent]
  116586. //
  116587. // On stack, before: ...
  116588. // On stack, after: ...
  116589. //
  116590. // Appends the string value of `content` to the current buffer
  116591. appendContent: function appendContent(content) {
  116592. if (this.pendingContent) {
  116593. content = this.pendingContent + content;
  116594. } else {
  116595. this.pendingLocation = this.source.currentLocation;
  116596. }
  116597. this.pendingContent = content;
  116598. },
  116599. // [append]
  116600. //
  116601. // On stack, before: value, ...
  116602. // On stack, after: ...
  116603. //
  116604. // Coerces `value` to a String and appends it to the current buffer.
  116605. //
  116606. // If `value` is truthy, or 0, it is coerced into a string and appended
  116607. // Otherwise, the empty string is appended
  116608. append: function append() {
  116609. if (this.isInline()) {
  116610. this.replaceStack(function (current) {
  116611. return [' != null ? ', current, ' : ""'];
  116612. });
  116613. this.pushSource(this.appendToBuffer(this.popStack()));
  116614. } else {
  116615. var local = this.popStack();
  116616. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  116617. if (this.environment.isSimple) {
  116618. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  116619. }
  116620. }
  116621. },
  116622. // [appendEscaped]
  116623. //
  116624. // On stack, before: value, ...
  116625. // On stack, after: ...
  116626. //
  116627. // Escape `value` and append it to the buffer
  116628. appendEscaped: function appendEscaped() {
  116629. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  116630. },
  116631. // [getContext]
  116632. //
  116633. // On stack, before: ...
  116634. // On stack, after: ...
  116635. // Compiler value, after: lastContext=depth
  116636. //
  116637. // Set the value of the `lastContext` compiler value to the depth
  116638. getContext: function getContext(depth) {
  116639. this.lastContext = depth;
  116640. },
  116641. // [pushContext]
  116642. //
  116643. // On stack, before: ...
  116644. // On stack, after: currentContext, ...
  116645. //
  116646. // Pushes the value of the current context onto the stack.
  116647. pushContext: function pushContext() {
  116648. this.pushStackLiteral(this.contextName(this.lastContext));
  116649. },
  116650. // [lookupOnContext]
  116651. //
  116652. // On stack, before: ...
  116653. // On stack, after: currentContext[name], ...
  116654. //
  116655. // Looks up the value of `name` on the current context and pushes
  116656. // it onto the stack.
  116657. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  116658. var i = 0;
  116659. if (!scoped && this.options.compat && !this.lastContext) {
  116660. // The depthed query is expected to handle the undefined logic for the root level that
  116661. // is implemented below, so we evaluate that directly in compat mode
  116662. this.push(this.depthedLookup(parts[i++]));
  116663. } else {
  116664. this.pushContext();
  116665. }
  116666. this.resolvePath('context', parts, i, falsy, strict);
  116667. },
  116668. // [lookupBlockParam]
  116669. //
  116670. // On stack, before: ...
  116671. // On stack, after: blockParam[name], ...
  116672. //
  116673. // Looks up the value of `parts` on the given block param and pushes
  116674. // it onto the stack.
  116675. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  116676. this.useBlockParams = true;
  116677. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  116678. this.resolvePath('context', parts, 1);
  116679. },
  116680. // [lookupData]
  116681. //
  116682. // On stack, before: ...
  116683. // On stack, after: data, ...
  116684. //
  116685. // Push the data lookup operator
  116686. lookupData: function lookupData(depth, parts, strict) {
  116687. if (!depth) {
  116688. this.pushStackLiteral('data');
  116689. } else {
  116690. this.pushStackLiteral('container.data(data, ' + depth + ')');
  116691. }
  116692. this.resolvePath('data', parts, 0, true, strict);
  116693. },
  116694. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  116695. // istanbul ignore next
  116696. var _this = this;
  116697. if (this.options.strict || this.options.assumeObjects) {
  116698. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  116699. return;
  116700. }
  116701. var len = parts.length;
  116702. for (; i < len; i++) {
  116703. /* eslint-disable no-loop-func */
  116704. this.replaceStack(function (current) {
  116705. var lookup = _this.nameLookup(current, parts[i], type);
  116706. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  116707. // needs to have the special handling for these values.
  116708. if (!falsy) {
  116709. return [' != null ? ', lookup, ' : ', current];
  116710. } else {
  116711. // Otherwise we can use generic falsy handling
  116712. return [' && ', lookup];
  116713. }
  116714. });
  116715. /* eslint-enable no-loop-func */
  116716. }
  116717. },
  116718. // [resolvePossibleLambda]
  116719. //
  116720. // On stack, before: value, ...
  116721. // On stack, after: resolved value, ...
  116722. //
  116723. // If the `value` is a lambda, replace it on the stack by
  116724. // the return value of the lambda
  116725. resolvePossibleLambda: function resolvePossibleLambda() {
  116726. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  116727. },
  116728. // [pushStringParam]
  116729. //
  116730. // On stack, before: ...
  116731. // On stack, after: string, currentContext, ...
  116732. //
  116733. // This opcode is designed for use in string mode, which
  116734. // provides the string value of a parameter along with its
  116735. // depth rather than resolving it immediately.
  116736. pushStringParam: function pushStringParam(string, type) {
  116737. this.pushContext();
  116738. this.pushString(type);
  116739. // If it's a subexpression, the string result
  116740. // will be pushed after this opcode.
  116741. if (type !== 'SubExpression') {
  116742. if (typeof string === 'string') {
  116743. this.pushString(string);
  116744. } else {
  116745. this.pushStackLiteral(string);
  116746. }
  116747. }
  116748. },
  116749. emptyHash: function emptyHash(omitEmpty) {
  116750. if (this.trackIds) {
  116751. this.push('{}'); // hashIds
  116752. }
  116753. if (this.stringParams) {
  116754. this.push('{}'); // hashContexts
  116755. this.push('{}'); // hashTypes
  116756. }
  116757. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  116758. },
  116759. pushHash: function pushHash() {
  116760. if (this.hash) {
  116761. this.hashes.push(this.hash);
  116762. }
  116763. this.hash = { values: [], types: [], contexts: [], ids: [] };
  116764. },
  116765. popHash: function popHash() {
  116766. var hash = this.hash;
  116767. this.hash = this.hashes.pop();
  116768. if (this.trackIds) {
  116769. this.push(this.objectLiteral(hash.ids));
  116770. }
  116771. if (this.stringParams) {
  116772. this.push(this.objectLiteral(hash.contexts));
  116773. this.push(this.objectLiteral(hash.types));
  116774. }
  116775. this.push(this.objectLiteral(hash.values));
  116776. },
  116777. // [pushString]
  116778. //
  116779. // On stack, before: ...
  116780. // On stack, after: quotedString(string), ...
  116781. //
  116782. // Push a quoted version of `string` onto the stack
  116783. pushString: function pushString(string) {
  116784. this.pushStackLiteral(this.quotedString(string));
  116785. },
  116786. // [pushLiteral]
  116787. //
  116788. // On stack, before: ...
  116789. // On stack, after: value, ...
  116790. //
  116791. // Pushes a value onto the stack. This operation prevents
  116792. // the compiler from creating a temporary variable to hold
  116793. // it.
  116794. pushLiteral: function pushLiteral(value) {
  116795. this.pushStackLiteral(value);
  116796. },
  116797. // [pushProgram]
  116798. //
  116799. // On stack, before: ...
  116800. // On stack, after: program(guid), ...
  116801. //
  116802. // Push a program expression onto the stack. This takes
  116803. // a compile-time guid and converts it into a runtime-accessible
  116804. // expression.
  116805. pushProgram: function pushProgram(guid) {
  116806. if (guid != null) {
  116807. this.pushStackLiteral(this.programExpression(guid));
  116808. } else {
  116809. this.pushStackLiteral(null);
  116810. }
  116811. },
  116812. // [registerDecorator]
  116813. //
  116814. // On stack, before: hash, program, params..., ...
  116815. // On stack, after: ...
  116816. //
  116817. // Pops off the decorator's parameters, invokes the decorator,
  116818. // and inserts the decorator into the decorators list.
  116819. registerDecorator: function registerDecorator(paramSize, name) {
  116820. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  116821. options = this.setupHelperArgs(name, paramSize);
  116822. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  116823. },
  116824. // [invokeHelper]
  116825. //
  116826. // On stack, before: hash, inverse, program, params..., ...
  116827. // On stack, after: result of helper invocation
  116828. //
  116829. // Pops off the helper's parameters, invokes the helper,
  116830. // and pushes the helper's return value onto the stack.
  116831. //
  116832. // If the helper is not found, `helperMissing` is called.
  116833. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  116834. var nonHelper = this.popStack(),
  116835. helper = this.setupHelper(paramSize, name),
  116836. simple = isSimple ? [helper.name, ' || '] : '';
  116837. var lookup = ['('].concat(simple, nonHelper);
  116838. if (!this.options.strict) {
  116839. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  116840. }
  116841. lookup.push(')');
  116842. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  116843. },
  116844. // [invokeKnownHelper]
  116845. //
  116846. // On stack, before: hash, inverse, program, params..., ...
  116847. // On stack, after: result of helper invocation
  116848. //
  116849. // This operation is used when the helper is known to exist,
  116850. // so a `helperMissing` fallback is not required.
  116851. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  116852. var helper = this.setupHelper(paramSize, name);
  116853. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  116854. },
  116855. // [invokeAmbiguous]
  116856. //
  116857. // On stack, before: hash, inverse, program, params..., ...
  116858. // On stack, after: result of disambiguation
  116859. //
  116860. // This operation is used when an expression like `{{foo}}`
  116861. // is provided, but we don't know at compile-time whether it
  116862. // is a helper or a path.
  116863. //
  116864. // This operation emits more code than the other options,
  116865. // and can be avoided by passing the `knownHelpers` and
  116866. // `knownHelpersOnly` flags at compile-time.
  116867. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  116868. this.useRegister('helper');
  116869. var nonHelper = this.popStack();
  116870. this.emptyHash();
  116871. var helper = this.setupHelper(0, name, helperCall);
  116872. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  116873. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  116874. if (!this.options.strict) {
  116875. lookup[0] = '(helper = ';
  116876. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  116877. }
  116878. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  116879. },
  116880. // [invokePartial]
  116881. //
  116882. // On stack, before: context, ...
  116883. // On stack after: result of partial invocation
  116884. //
  116885. // This operation pops off a context, invokes a partial with that context,
  116886. // and pushes the result of the invocation back.
  116887. invokePartial: function invokePartial(isDynamic, name, indent) {
  116888. var params = [],
  116889. options = this.setupParams(name, 1, params);
  116890. if (isDynamic) {
  116891. name = this.popStack();
  116892. delete options.name;
  116893. }
  116894. if (indent) {
  116895. options.indent = JSON.stringify(indent);
  116896. }
  116897. options.helpers = 'helpers';
  116898. options.partials = 'partials';
  116899. options.decorators = 'container.decorators';
  116900. if (!isDynamic) {
  116901. params.unshift(this.nameLookup('partials', name, 'partial'));
  116902. } else {
  116903. params.unshift(name);
  116904. }
  116905. if (this.options.compat) {
  116906. options.depths = 'depths';
  116907. }
  116908. options = this.objectLiteral(options);
  116909. params.push(options);
  116910. this.push(this.source.functionCall('container.invokePartial', '', params));
  116911. },
  116912. // [assignToHash]
  116913. //
  116914. // On stack, before: value, ..., hash, ...
  116915. // On stack, after: ..., hash, ...
  116916. //
  116917. // Pops a value off the stack and assigns it to the current hash
  116918. assignToHash: function assignToHash(key) {
  116919. var value = this.popStack(),
  116920. context = undefined,
  116921. type = undefined,
  116922. id = undefined;
  116923. if (this.trackIds) {
  116924. id = this.popStack();
  116925. }
  116926. if (this.stringParams) {
  116927. type = this.popStack();
  116928. context = this.popStack();
  116929. }
  116930. var hash = this.hash;
  116931. if (context) {
  116932. hash.contexts[key] = context;
  116933. }
  116934. if (type) {
  116935. hash.types[key] = type;
  116936. }
  116937. if (id) {
  116938. hash.ids[key] = id;
  116939. }
  116940. hash.values[key] = value;
  116941. },
  116942. pushId: function pushId(type, name, child) {
  116943. if (type === 'BlockParam') {
  116944. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  116945. } else if (type === 'PathExpression') {
  116946. this.pushString(name);
  116947. } else if (type === 'SubExpression') {
  116948. this.pushStackLiteral('true');
  116949. } else {
  116950. this.pushStackLiteral('null');
  116951. }
  116952. },
  116953. // HELPERS
  116954. compiler: JavaScriptCompiler,
  116955. compileChildren: function compileChildren(environment, options) {
  116956. var children = environment.children,
  116957. child = undefined,
  116958. compiler = undefined;
  116959. for (var i = 0, l = children.length; i < l; i++) {
  116960. child = children[i];
  116961. compiler = new this.compiler(); // eslint-disable-line new-cap
  116962. var existing = this.matchExistingProgram(child);
  116963. if (existing == null) {
  116964. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  116965. var index = this.context.programs.length;
  116966. child.index = index;
  116967. child.name = 'program' + index;
  116968. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  116969. this.context.decorators[index] = compiler.decorators;
  116970. this.context.environments[index] = child;
  116971. this.useDepths = this.useDepths || compiler.useDepths;
  116972. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  116973. child.useDepths = this.useDepths;
  116974. child.useBlockParams = this.useBlockParams;
  116975. } else {
  116976. child.index = existing.index;
  116977. child.name = 'program' + existing.index;
  116978. this.useDepths = this.useDepths || existing.useDepths;
  116979. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  116980. }
  116981. }
  116982. },
  116983. matchExistingProgram: function matchExistingProgram(child) {
  116984. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  116985. var environment = this.context.environments[i];
  116986. if (environment && environment.equals(child)) {
  116987. return environment;
  116988. }
  116989. }
  116990. },
  116991. programExpression: function programExpression(guid) {
  116992. var child = this.environment.children[guid],
  116993. programParams = [child.index, 'data', child.blockParams];
  116994. if (this.useBlockParams || this.useDepths) {
  116995. programParams.push('blockParams');
  116996. }
  116997. if (this.useDepths) {
  116998. programParams.push('depths');
  116999. }
  117000. return 'container.program(' + programParams.join(', ') + ')';
  117001. },
  117002. useRegister: function useRegister(name) {
  117003. if (!this.registers[name]) {
  117004. this.registers[name] = true;
  117005. this.registers.list.push(name);
  117006. }
  117007. },
  117008. push: function push(expr) {
  117009. if (!(expr instanceof Literal)) {
  117010. expr = this.source.wrap(expr);
  117011. }
  117012. this.inlineStack.push(expr);
  117013. return expr;
  117014. },
  117015. pushStackLiteral: function pushStackLiteral(item) {
  117016. this.push(new Literal(item));
  117017. },
  117018. pushSource: function pushSource(source) {
  117019. if (this.pendingContent) {
  117020. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  117021. this.pendingContent = undefined;
  117022. }
  117023. if (source) {
  117024. this.source.push(source);
  117025. }
  117026. },
  117027. replaceStack: function replaceStack(callback) {
  117028. var prefix = ['('],
  117029. stack = undefined,
  117030. createdStack = undefined,
  117031. usedLiteral = undefined;
  117032. /* istanbul ignore next */
  117033. if (!this.isInline()) {
  117034. throw new _exception2['default']('replaceStack on non-inline');
  117035. }
  117036. // We want to merge the inline statement into the replacement statement via ','
  117037. var top = this.popStack(true);
  117038. if (top instanceof Literal) {
  117039. // Literals do not need to be inlined
  117040. stack = [top.value];
  117041. prefix = ['(', stack];
  117042. usedLiteral = true;
  117043. } else {
  117044. // Get or create the current stack name for use by the inline
  117045. createdStack = true;
  117046. var _name = this.incrStack();
  117047. prefix = ['((', this.push(_name), ' = ', top, ')'];
  117048. stack = this.topStack();
  117049. }
  117050. var item = callback.call(this, stack);
  117051. if (!usedLiteral) {
  117052. this.popStack();
  117053. }
  117054. if (createdStack) {
  117055. this.stackSlot--;
  117056. }
  117057. this.push(prefix.concat(item, ')'));
  117058. },
  117059. incrStack: function incrStack() {
  117060. this.stackSlot++;
  117061. if (this.stackSlot > this.stackVars.length) {
  117062. this.stackVars.push('stack' + this.stackSlot);
  117063. }
  117064. return this.topStackName();
  117065. },
  117066. topStackName: function topStackName() {
  117067. return 'stack' + this.stackSlot;
  117068. },
  117069. flushInline: function flushInline() {
  117070. var inlineStack = this.inlineStack;
  117071. this.inlineStack = [];
  117072. for (var i = 0, len = inlineStack.length; i < len; i++) {
  117073. var entry = inlineStack[i];
  117074. /* istanbul ignore if */
  117075. if (entry instanceof Literal) {
  117076. this.compileStack.push(entry);
  117077. } else {
  117078. var stack = this.incrStack();
  117079. this.pushSource([stack, ' = ', entry, ';']);
  117080. this.compileStack.push(stack);
  117081. }
  117082. }
  117083. },
  117084. isInline: function isInline() {
  117085. return this.inlineStack.length;
  117086. },
  117087. popStack: function popStack(wrapped) {
  117088. var inline = this.isInline(),
  117089. item = (inline ? this.inlineStack : this.compileStack).pop();
  117090. if (!wrapped && item instanceof Literal) {
  117091. return item.value;
  117092. } else {
  117093. if (!inline) {
  117094. /* istanbul ignore next */
  117095. if (!this.stackSlot) {
  117096. throw new _exception2['default']('Invalid stack pop');
  117097. }
  117098. this.stackSlot--;
  117099. }
  117100. return item;
  117101. }
  117102. },
  117103. topStack: function topStack() {
  117104. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  117105. item = stack[stack.length - 1];
  117106. /* istanbul ignore if */
  117107. if (item instanceof Literal) {
  117108. return item.value;
  117109. } else {
  117110. return item;
  117111. }
  117112. },
  117113. contextName: function contextName(context) {
  117114. if (this.useDepths && context) {
  117115. return 'depths[' + context + ']';
  117116. } else {
  117117. return 'depth' + context;
  117118. }
  117119. },
  117120. quotedString: function quotedString(str) {
  117121. return this.source.quotedString(str);
  117122. },
  117123. objectLiteral: function objectLiteral(obj) {
  117124. return this.source.objectLiteral(obj);
  117125. },
  117126. aliasable: function aliasable(name) {
  117127. var ret = this.aliases[name];
  117128. if (ret) {
  117129. ret.referenceCount++;
  117130. return ret;
  117131. }
  117132. ret = this.aliases[name] = this.source.wrap(name);
  117133. ret.aliasable = true;
  117134. ret.referenceCount = 1;
  117135. return ret;
  117136. },
  117137. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  117138. var params = [],
  117139. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  117140. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  117141. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  117142. return {
  117143. params: params,
  117144. paramsInit: paramsInit,
  117145. name: foundHelper,
  117146. callParams: [callContext].concat(params)
  117147. };
  117148. },
  117149. setupParams: function setupParams(helper, paramSize, params) {
  117150. var options = {},
  117151. contexts = [],
  117152. types = [],
  117153. ids = [],
  117154. objectArgs = !params,
  117155. param = undefined;
  117156. if (objectArgs) {
  117157. params = [];
  117158. }
  117159. options.name = this.quotedString(helper);
  117160. options.hash = this.popStack();
  117161. if (this.trackIds) {
  117162. options.hashIds = this.popStack();
  117163. }
  117164. if (this.stringParams) {
  117165. options.hashTypes = this.popStack();
  117166. options.hashContexts = this.popStack();
  117167. }
  117168. var inverse = this.popStack(),
  117169. program = this.popStack();
  117170. // Avoid setting fn and inverse if neither are set. This allows
  117171. // helpers to do a check for `if (options.fn)`
  117172. if (program || inverse) {
  117173. options.fn = program || 'container.noop';
  117174. options.inverse = inverse || 'container.noop';
  117175. }
  117176. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  117177. // so we need to pop them off the stack in reverse order
  117178. var i = paramSize;
  117179. while (i--) {
  117180. param = this.popStack();
  117181. params[i] = param;
  117182. if (this.trackIds) {
  117183. ids[i] = this.popStack();
  117184. }
  117185. if (this.stringParams) {
  117186. types[i] = this.popStack();
  117187. contexts[i] = this.popStack();
  117188. }
  117189. }
  117190. if (objectArgs) {
  117191. options.args = this.source.generateArray(params);
  117192. }
  117193. if (this.trackIds) {
  117194. options.ids = this.source.generateArray(ids);
  117195. }
  117196. if (this.stringParams) {
  117197. options.types = this.source.generateArray(types);
  117198. options.contexts = this.source.generateArray(contexts);
  117199. }
  117200. if (this.options.data) {
  117201. options.data = 'data';
  117202. }
  117203. if (this.useBlockParams) {
  117204. options.blockParams = 'blockParams';
  117205. }
  117206. return options;
  117207. },
  117208. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  117209. var options = this.setupParams(helper, paramSize, params);
  117210. options = this.objectLiteral(options);
  117211. if (useRegister) {
  117212. this.useRegister('options');
  117213. params.push('options');
  117214. return ['options=', options];
  117215. } else if (params) {
  117216. params.push(options);
  117217. return '';
  117218. } else {
  117219. return options;
  117220. }
  117221. }
  117222. };
  117223. (function () {
  117224. 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(' ');
  117225. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  117226. for (var i = 0, l = reservedWords.length; i < l; i++) {
  117227. compilerWords[reservedWords[i]] = true;
  117228. }
  117229. })();
  117230. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  117231. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  117232. };
  117233. function strictLookup(requireTerminal, compiler, parts, type) {
  117234. var stack = compiler.popStack(),
  117235. i = 0,
  117236. len = parts.length;
  117237. if (requireTerminal) {
  117238. len--;
  117239. }
  117240. for (; i < len; i++) {
  117241. stack = compiler.nameLookup(stack, parts[i], type);
  117242. }
  117243. if (requireTerminal) {
  117244. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  117245. } else {
  117246. return stack;
  117247. }
  117248. }
  117249. exports['default'] = JavaScriptCompiler;
  117250. module.exports = exports['default'];
  117251. /***/ }),
  117252. /* 43 */
  117253. /***/ (function(module, exports, __webpack_require__) {
  117254. /* global define */
  117255. 'use strict';
  117256. exports.__esModule = true;
  117257. var _utils = __webpack_require__(5);
  117258. var SourceNode = undefined;
  117259. try {
  117260. /* istanbul ignore next */
  117261. if (false) {
  117262. // We don't support this in AMD environments. For these environments, we asusme that
  117263. // they are running on the browser and thus have no need for the source-map library.
  117264. var SourceMap = require('source-map');
  117265. SourceNode = SourceMap.SourceNode;
  117266. }
  117267. } catch (err) {}
  117268. /* NOP */
  117269. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  117270. if (!SourceNode) {
  117271. SourceNode = function (line, column, srcFile, chunks) {
  117272. this.src = '';
  117273. if (chunks) {
  117274. this.add(chunks);
  117275. }
  117276. };
  117277. /* istanbul ignore next */
  117278. SourceNode.prototype = {
  117279. add: function add(chunks) {
  117280. if (_utils.isArray(chunks)) {
  117281. chunks = chunks.join('');
  117282. }
  117283. this.src += chunks;
  117284. },
  117285. prepend: function prepend(chunks) {
  117286. if (_utils.isArray(chunks)) {
  117287. chunks = chunks.join('');
  117288. }
  117289. this.src = chunks + this.src;
  117290. },
  117291. toStringWithSourceMap: function toStringWithSourceMap() {
  117292. return { code: this.toString() };
  117293. },
  117294. toString: function toString() {
  117295. return this.src;
  117296. }
  117297. };
  117298. }
  117299. function castChunk(chunk, codeGen, loc) {
  117300. if (_utils.isArray(chunk)) {
  117301. var ret = [];
  117302. for (var i = 0, len = chunk.length; i < len; i++) {
  117303. ret.push(codeGen.wrap(chunk[i], loc));
  117304. }
  117305. return ret;
  117306. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  117307. // Handle primitives that the SourceNode will throw up on
  117308. return chunk + '';
  117309. }
  117310. return chunk;
  117311. }
  117312. function CodeGen(srcFile) {
  117313. this.srcFile = srcFile;
  117314. this.source = [];
  117315. }
  117316. CodeGen.prototype = {
  117317. isEmpty: function isEmpty() {
  117318. return !this.source.length;
  117319. },
  117320. prepend: function prepend(source, loc) {
  117321. this.source.unshift(this.wrap(source, loc));
  117322. },
  117323. push: function push(source, loc) {
  117324. this.source.push(this.wrap(source, loc));
  117325. },
  117326. merge: function merge() {
  117327. var source = this.empty();
  117328. this.each(function (line) {
  117329. source.add([' ', line, '\n']);
  117330. });
  117331. return source;
  117332. },
  117333. each: function each(iter) {
  117334. for (var i = 0, len = this.source.length; i < len; i++) {
  117335. iter(this.source[i]);
  117336. }
  117337. },
  117338. empty: function empty() {
  117339. var loc = this.currentLocation || { start: {} };
  117340. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  117341. },
  117342. wrap: function wrap(chunk) {
  117343. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  117344. if (chunk instanceof SourceNode) {
  117345. return chunk;
  117346. }
  117347. chunk = castChunk(chunk, this, loc);
  117348. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  117349. },
  117350. functionCall: function functionCall(fn, type, params) {
  117351. params = this.generateList(params);
  117352. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  117353. },
  117354. quotedString: function quotedString(str) {
  117355. 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
  117356. .replace(/\u2029/g, '\\u2029') + '"';
  117357. },
  117358. objectLiteral: function objectLiteral(obj) {
  117359. var pairs = [];
  117360. for (var key in obj) {
  117361. if (obj.hasOwnProperty(key)) {
  117362. var value = castChunk(obj[key], this);
  117363. if (value !== 'undefined') {
  117364. pairs.push([this.quotedString(key), ':', value]);
  117365. }
  117366. }
  117367. }
  117368. var ret = this.generateList(pairs);
  117369. ret.prepend('{');
  117370. ret.add('}');
  117371. return ret;
  117372. },
  117373. generateList: function generateList(entries) {
  117374. var ret = this.empty();
  117375. for (var i = 0, len = entries.length; i < len; i++) {
  117376. if (i) {
  117377. ret.add(',');
  117378. }
  117379. ret.add(castChunk(entries[i], this));
  117380. }
  117381. return ret;
  117382. },
  117383. generateArray: function generateArray(entries) {
  117384. var ret = this.generateList(entries);
  117385. ret.prepend('[');
  117386. ret.add(']');
  117387. return ret;
  117388. }
  117389. };
  117390. exports['default'] = CodeGen;
  117391. module.exports = exports['default'];
  117392. /***/ })
  117393. /******/ ])
  117394. });
  117395. ;
  117396. /***/ }),
  117397. /* 18 */
  117398. /***/ (function(module, exports, __webpack_require__) {
  117399. "use strict";
  117400. Object.defineProperty(exports, "__esModule", { value: true });
  117401. var Handlebars = __webpack_require__(17);
  117402. var AbstractViewerNavbarButton = /** @class */ (function () {
  117403. function AbstractViewerNavbarButton(buttonName, buttonClass, htmlTemplate) {
  117404. this.templateName = "navBar";
  117405. this.eventsToAttach = ['pointerdown'];
  117406. this._prepend = true;
  117407. this._buttonName = buttonName;
  117408. if (buttonClass) {
  117409. this._buttonClass = buttonClass;
  117410. }
  117411. else {
  117412. this._buttonClass = buttonName + '-button';
  117413. }
  117414. if (htmlTemplate) {
  117415. this._htmlTemplate = htmlTemplate;
  117416. }
  117417. else {
  117418. this._htmlTemplate = "\n<button class=\"" + this._buttonClass + "\">\n <span class=\"icon " + this._buttonName + "-icon\"></span>\n</button>\n";
  117419. }
  117420. }
  117421. AbstractViewerNavbarButton.prototype.interactionPredicate = function (event) {
  117422. var pointerDown = event.event;
  117423. if (pointerDown.button !== 0)
  117424. return false;
  117425. var element = event.event.target;
  117426. if (!element) {
  117427. return false;
  117428. }
  117429. var elementClasses = element.classList;
  117430. for (var i = 0; i < elementClasses.length; ++i) {
  117431. var className = elementClasses[i];
  117432. if (className.indexOf(this._buttonClass) !== -1) {
  117433. return true;
  117434. }
  117435. }
  117436. return false;
  117437. };
  117438. AbstractViewerNavbarButton.prototype.addHTMLTemplate = function (template) {
  117439. var element = this._generateHTMLElement(template);
  117440. var container = template.parent.querySelector("div.default-control");
  117441. if (container) {
  117442. if (this._prepend) {
  117443. container.insertBefore(element, container.firstChild);
  117444. }
  117445. else {
  117446. container.appendChild(element);
  117447. }
  117448. }
  117449. };
  117450. AbstractViewerNavbarButton.prototype._generateHTMLElement = function (template) {
  117451. var compiledTemplate = Handlebars.compile(this._htmlTemplate, { noEscape: (template.configuration.params && !!template.configuration.params.noEscape) });
  117452. var config = template.configuration.params || {};
  117453. var rawHtml = compiledTemplate(config);
  117454. var fragment;
  117455. try {
  117456. fragment = document.createRange().createContextualFragment(rawHtml);
  117457. }
  117458. catch (e) {
  117459. var test = document.createElement(this._buttonClass);
  117460. test.innerHTML = rawHtml;
  117461. fragment = test;
  117462. }
  117463. return fragment;
  117464. };
  117465. return AbstractViewerNavbarButton;
  117466. }());
  117467. exports.AbstractViewerNavbarButton = AbstractViewerNavbarButton;
  117468. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyVGVtcGxhdGVQbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy92aWV3ZXJUZW1wbGF0ZVBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVEQUF5RDtBQVl6RDtJQVNJLG9DQUFZLFVBQWtCLEVBQUUsV0FBb0IsRUFBRSxZQUFxQjtRQVAzRCxpQkFBWSxHQUFXLFFBQVEsQ0FBQztRQUNoQyxtQkFBYyxHQUFrQixDQUFDLGFBQWEsQ0FBQyxDQUFDO1FBQ3RELGFBQVEsR0FBWSxJQUFJLENBQUM7UUFNL0IsSUFBSSxDQUFDLFdBQVcsR0FBRyxVQUFVLENBQUM7UUFDOUIsSUFBSSxXQUFXLEVBQUU7WUFDYixJQUFJLENBQUMsWUFBWSxHQUFHLFdBQVcsQ0FBQztTQUNuQzthQUFNO1lBQ0gsSUFBSSxDQUFDLFlBQVksR0FBRyxVQUFVLEdBQUcsU0FBUyxDQUFDO1NBQzlDO1FBQ0QsSUFBSSxZQUFZLEVBQUU7WUFBRSxJQUFJLENBQUMsYUFBYSxHQUFHLFlBQVksQ0FBQTtTQUFFO2FBQ2xEO1lBQ0QsSUFBSSxDQUFD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QUNMLGlDQUFDO0FBQUQsQ0FBQyxBQTFFRCxJQTBFQztBQTFFcUIsZ0VBQTBCIn0=
  117469. /***/ }),
  117470. /* 19 */
  117471. /***/ (function(module, exports, __webpack_require__) {
  117472. module.exports = __webpack_require__(20);
  117473. /***/ }),
  117474. /* 20 */
  117475. /***/ (function(module, exports, __webpack_require__) {
  117476. "use strict";
  117477. function __export(m) {
  117478. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  117479. }
  117480. Object.defineProperty(exports, "__esModule", { value: true });
  117481. var mappers_1 = __webpack_require__(3);
  117482. exports.mapperManager = mappers_1.mapperManager;
  117483. var globals_1 = __webpack_require__(4);
  117484. exports.viewerGlobals = globals_1.viewerGlobals;
  117485. var viewerManager_1 = __webpack_require__(7);
  117486. exports.viewerManager = viewerManager_1.viewerManager;
  117487. var defaultViewer_1 = __webpack_require__(8);
  117488. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  117489. var viewer_1 = __webpack_require__(9);
  117490. exports.AbstractViewer = viewer_1.AbstractViewer;
  117491. var telemetryManager_1 = __webpack_require__(6);
  117492. exports.telemetryManager = telemetryManager_1.telemetryManager;
  117493. var modelLoader_1 = __webpack_require__(12);
  117494. exports.ModelLoader = modelLoader_1.ModelLoader;
  117495. var viewerModel_1 = __webpack_require__(5);
  117496. exports.ViewerModel = viewerModel_1.ViewerModel;
  117497. exports.ModelState = viewerModel_1.ModelState;
  117498. var viewerTemplatePlugin_1 = __webpack_require__(18);
  117499. exports.AbstractViewerNavbarButton = viewerTemplatePlugin_1.AbstractViewerNavbarButton;
  117500. var custom_1 = __webpack_require__(16);
  117501. exports.registerCustomOptimizer = custom_1.registerCustomOptimizer;
  117502. /**
  117503. * BabylonJS Viewer
  117504. *
  117505. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  117506. */
  117507. var BABYLON = __webpack_require__(0);
  117508. exports.BABYLON = BABYLON;
  117509. // load needed modules.
  117510. __webpack_require__(13);
  117511. __webpack_require__(66);
  117512. var initializer_1 = __webpack_require__(67);
  117513. exports.InitTags = initializer_1.InitTags;
  117514. // promise polyfill, if needed!
  117515. BABYLON.PromisePolyfill.Apply();
  117516. initializer_1.initListeners();
  117517. //deprectaed, here for backwards compatibility
  117518. var disableInit = globals_1.viewerGlobals.disableInit;
  117519. exports.disableInit = disableInit;
  117520. /**
  117521. * Dispose all viewers currently registered
  117522. */
  117523. function disposeAll() {
  117524. viewerManager_1.viewerManager.dispose();
  117525. mappers_1.mapperManager.dispose();
  117526. telemetryManager_1.telemetryManager.dispose();
  117527. }
  117528. exports.disposeAll = disposeAll;
  117529. var Version = globals_1.viewerGlobals.version;
  117530. exports.Version = Version;
  117531. console.log("Babylon.js viewer (v" + Version + ")");
  117532. // export publicliy all configuration interfaces
  117533. __export(__webpack_require__(14));
  117534. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUFnRHlFLHdCQWhEeEgsdUJBQWEsQ0FnRHdIO0FBL0M5SSxtREFBd0Q7QUErQ1ksd0JBL0MzRCx1QkFBYSxDQStDMkQ7QUE5Q2pGLHdEQUF1RDtBQThDMkQsd0JBOUN6Ryw2QkFBYSxDQThDeUc7QUE3Qy9ILHdEQUF1RDtBQTZDbEIsd0JBN0M1Qiw2QkFBYSxDQTZDNEI7QUE1Q2xELDBDQUFpRDtBQTRDRyx5QkE1QzNDLHVCQUFjLENBNEMyQztBQTNDbEUsZ0VBQStEO0FBMkNvQiwyQkEzQzFFLG1DQUFnQixDQTJDMEU7QUExQ25HLG9EQUFtRDtBQTBDeUcsc0JBMUNuSix5QkFBVyxDQTBDbUo7QUF6Q3ZLLG1EQUE4RDtBQXlDMkcsc0JBekNoSyx5QkFBVyxDQXlDZ0s7QUFBcUMscUJBekNuTSx3QkFBVSxDQXlDbU07QUF0Q25PLDBFQUErRTtBQXNDcUsscUNBdEMzTyxpREFBMEIsQ0FzQzJPO0FBckM5USw2Q0FBNkQ7QUFxQ21OLGtDQXJDdlEsZ0NBQXVCLENBcUN1UTtBQW5DdlM7Ozs7R0FJRztBQUVILG1DQUFxQztBQTZCNUIsMEJBQU87QUEzQmhCLHVCQUF1QjtBQUN2Qiw2QkFBMkI7QUFDM0IsaUJBQWU7QUFFZiw2Q0FBd0Q7QUF1QjdCLG1CQXZCSCxzQkFBUSxDQXVCRztBQXJCbkMsK0JBQStCO0FBQy9CLE9BQU8sQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7QUFDaEMsMkJBQWEsRUFBRSxDQUFDO0FBRWhCLDhDQUE4QztBQUM5QyxJQUFJLFdBQVcsR0FBWSx1QkFBYSxDQUFDLFdBQVcsQ0FBQztBQWdCZ0Qsa0NBQVc7QUFkaEg7O0dBRUc7QUFDSDtJQUNJLDZCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsdUJBQWEsQ0FBQyxPQUFPLEVBQUUsQ0FBQztJQUN4QixtQ0FBZ0IsQ0FBQyxPQUFPLEVBQUUsQ0FBQztBQUMvQixDQUFDO0FBTytJLGdDQUFVO0FBTDFKLElBQU0sT0FBTyxHQUFHLHVCQUFhLENBQUMsT0FBTyxDQUFDO0FBS3BCLDBCQUFPO0FBSHpCLE9BQU8sQ0FBQyxHQUFHLENBQUMsc0JBQXNCLEdBQUcsT0FBTyxHQUFHLEdBQUcsQ0FBQyxDQUFDO0FBSXBELGdEQUFnRDtBQUNoRCxxQ0FBZ0MifQ==
  117535. /***/ }),
  117536. /* 21 */
  117537. /***/ (function(module, exports) {
  117538. var g;
  117539. // This works in non-strict mode
  117540. g = (function() {
  117541. return this;
  117542. })();
  117543. try {
  117544. // This works if eval is allowed (see CSP)
  117545. g = g || Function("return this")() || (1,eval)("this");
  117546. } catch(e) {
  117547. // This works if the window reference is available
  117548. if(typeof window === "object")
  117549. g = window;
  117550. }
  117551. // g can still be undefined, but nothing to do about it...
  117552. // We return undefined, instead of nothing here, so it's
  117553. // easier to handle this case. if(!global) { ...}
  117554. module.exports = g;
  117555. /***/ }),
  117556. /* 22 */
  117557. /***/ (function(module, exports) {
  117558. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  117559. module.exports = CANNON;
  117560. /***/ }),
  117561. /* 23 */
  117562. /***/ (function(module, exports) {
  117563. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  117564. module.exports = OIMO;
  117565. /***/ }),
  117566. /* 24 */
  117567. /***/ (function(module, exports) {
  117568. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  117569. module.exports = earcut;
  117570. /***/ }),
  117571. /* 25 */
  117572. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  117573. "use strict";
  117574. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  117575. var isMergeableObject = function isMergeableObject(value) {
  117576. return isNonNullObject(value)
  117577. && !isSpecial(value)
  117578. };
  117579. function isNonNullObject(value) {
  117580. return !!value && typeof value === 'object'
  117581. }
  117582. function isSpecial(value) {
  117583. var stringValue = Object.prototype.toString.call(value);
  117584. return stringValue === '[object RegExp]'
  117585. || stringValue === '[object Date]'
  117586. || isReactElement(value)
  117587. }
  117588. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  117589. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  117590. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  117591. function isReactElement(value) {
  117592. return value.$$typeof === REACT_ELEMENT_TYPE
  117593. }
  117594. function emptyTarget(val) {
  117595. return Array.isArray(val) ? [] : {}
  117596. }
  117597. function cloneUnlessOtherwiseSpecified(value, options) {
  117598. return (options.clone !== false && options.isMergeableObject(value))
  117599. ? deepmerge(emptyTarget(value), value, options)
  117600. : value
  117601. }
  117602. function defaultArrayMerge(target, source, options) {
  117603. return target.concat(source).map(function(element) {
  117604. return cloneUnlessOtherwiseSpecified(element, options)
  117605. })
  117606. }
  117607. function mergeObject(target, source, options) {
  117608. var destination = {};
  117609. if (options.isMergeableObject(target)) {
  117610. Object.keys(target).forEach(function(key) {
  117611. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  117612. });
  117613. }
  117614. Object.keys(source).forEach(function(key) {
  117615. if (!options.isMergeableObject(source[key]) || !target[key]) {
  117616. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  117617. } else {
  117618. destination[key] = deepmerge(target[key], source[key], options);
  117619. }
  117620. });
  117621. return destination
  117622. }
  117623. function deepmerge(target, source, options) {
  117624. options = options || {};
  117625. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  117626. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  117627. var sourceIsArray = Array.isArray(source);
  117628. var targetIsArray = Array.isArray(target);
  117629. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  117630. if (!sourceAndTargetTypesMatch) {
  117631. return cloneUnlessOtherwiseSpecified(source, options)
  117632. } else if (sourceIsArray) {
  117633. return options.arrayMerge(target, source, options)
  117634. } else {
  117635. return mergeObject(target, source, options)
  117636. }
  117637. }
  117638. deepmerge.all = function deepmergeAll(array, options) {
  117639. if (!Array.isArray(array)) {
  117640. throw new Error('first argument should be an array')
  117641. }
  117642. return array.reduce(function(prev, next) {
  117643. return deepmerge(prev, next, options)
  117644. }, {})
  117645. };
  117646. var deepmerge_1 = deepmerge;
  117647. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  117648. /***/ }),
  117649. /* 26 */
  117650. /***/ (function(module, exports, __webpack_require__) {
  117651. "use strict";
  117652. Object.defineProperty(exports, "__esModule", { value: true });
  117653. var babylonjs_1 = __webpack_require__(0);
  117654. var ConfigurationContainer = /** @class */ (function () {
  117655. function ConfigurationContainer() {
  117656. this.mainColor = babylonjs_1.Color3.White();
  117657. this.reflectionColor = babylonjs_1.Color3.White();
  117658. }
  117659. return ConfigurationContainer;
  117660. }());
  117661. exports.ConfigurationContainer = ConfigurationContainer;
  117662. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  117663. /***/ }),
  117664. /* 27 */
  117665. /***/ (function(module, exports, __webpack_require__) {
  117666. "use strict";
  117667. Object.defineProperty(exports, "__esModule", { value: true });
  117668. var mappers_1 = __webpack_require__(3);
  117669. var types_1 = __webpack_require__(28);
  117670. var configurationCompatibility_1 = __webpack_require__(10);
  117671. var _1 = __webpack_require__(1);
  117672. var babylonjs_1 = __webpack_require__(0);
  117673. /**
  117674. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  117675. * parse the object and return a conform ViewerConfiguration.
  117676. * It is a private member of the scene.
  117677. */
  117678. var ConfigurationLoader = /** @class */ (function () {
  117679. function ConfigurationLoader(_enableCache) {
  117680. if (_enableCache === void 0) { _enableCache = false; }
  117681. this._enableCache = _enableCache;
  117682. this._configurationCache = {};
  117683. this._loadRequests = [];
  117684. }
  117685. /**
  117686. * load a configuration object that is defined in the initial configuration provided.
  117687. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  117688. *
  117689. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  117690. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  117691. * @returns A promise that delivers the extended viewer configuration, when done.
  117692. */
  117693. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  117694. var _this = this;
  117695. if (initConfig === void 0) { initConfig = {}; }
  117696. var loadedConfig = _1.deepmerge({}, initConfig);
  117697. this._processInitialConfiguration(loadedConfig);
  117698. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "extended");
  117699. if (loadedConfig.configuration) {
  117700. var mapperType_1 = "json";
  117701. return Promise.resolve().then(function () {
  117702. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  117703. // a file to load
  117704. var url = '';
  117705. if (typeof loadedConfig.configuration === "string") {
  117706. url = loadedConfig.configuration;
  117707. }
  117708. // if configuration is an object
  117709. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  117710. url = loadedConfig.configuration.url;
  117711. var type = loadedConfig.configuration.mapper;
  117712. // empty string?
  117713. if (!type) {
  117714. // load mapper type from filename / url
  117715. type = loadedConfig.configuration.url.split('.').pop();
  117716. }
  117717. mapperType_1 = type || mapperType_1;
  117718. }
  117719. return _this._loadFile(url);
  117720. }
  117721. else {
  117722. if (typeof loadedConfig.configuration === "object") {
  117723. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  117724. return loadedConfig.configuration.payload || {};
  117725. }
  117726. return {};
  117727. }
  117728. }).then(function (data) {
  117729. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  117730. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  117731. var merged = _1.deepmerge(extendedConfiguration, parsed);
  117732. configurationCompatibility_1.processConfigurationCompatibility(merged);
  117733. if (callback)
  117734. callback(merged);
  117735. return merged;
  117736. });
  117737. }
  117738. else {
  117739. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  117740. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  117741. if (callback)
  117742. callback(loadedConfig);
  117743. return Promise.resolve(loadedConfig);
  117744. }
  117745. };
  117746. /**
  117747. * Dispose the configuration loader. This will cancel file requests, if active.
  117748. */
  117749. ConfigurationLoader.prototype.dispose = function () {
  117750. this._loadRequests.forEach(function (request) {
  117751. request.abort();
  117752. });
  117753. this._loadRequests.length = 0;
  117754. };
  117755. /**
  117756. * This function will process the initial configuration and make needed changes for the viewer to work.
  117757. * @param config the mutable(!) initial configuration to process
  117758. */
  117759. ConfigurationLoader.prototype._processInitialConfiguration = function (config) {
  117760. if (config.model) {
  117761. if (typeof config.model === "string") {
  117762. config.model = {
  117763. url: config.model
  117764. };
  117765. }
  117766. }
  117767. };
  117768. ConfigurationLoader.prototype._loadFile = function (url) {
  117769. var _this = this;
  117770. var cacheReference = this._configurationCache;
  117771. if (this._enableCache && cacheReference[url]) {
  117772. return Promise.resolve(cacheReference[url]);
  117773. }
  117774. return new Promise(function (resolve, reject) {
  117775. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  117776. var idx = _this._loadRequests.indexOf(fileRequest);
  117777. if (idx !== -1)
  117778. _this._loadRequests.splice(idx, 1);
  117779. if (_this._enableCache)
  117780. cacheReference[url] = result;
  117781. resolve(result);
  117782. }, undefined, undefined, false, function (request, error) {
  117783. var idx = _this._loadRequests.indexOf(fileRequest);
  117784. if (idx !== -1)
  117785. _this._loadRequests.splice(idx, 1);
  117786. reject(error);
  117787. });
  117788. _this._loadRequests.push(fileRequest);
  117789. });
  117790. };
  117791. return ConfigurationLoader;
  117792. }());
  117793. exports.ConfigurationLoader = ConfigurationLoader;
  117794. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjo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xTQUFTLEVBQUUsS0FBSyxFQUFFLFVBQUMsT0FBTyxFQUFFLEtBQVU7Z0JBQ2hELElBQUksR0FBRyxHQUFHLEtBQUksQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLFdBQVcsQ0FBQyxDQUFDO2dCQUNsRCxJQUFJLEdBQUcsS0FBSyxDQUFDLENBQUM7b0JBQ1YsS0FBSSxDQUFDLGFBQWEsQ0FBQyxNQUFNLENBQUMsR0FBRyxFQUFFLENBQUMsQ0FBQyxDQUFDO2dCQUN0QyxNQUFNLENBQUMsS0FBSyxDQUFDLENBQUM7WUFDbEIsQ0FBQyxDQUFDLENBQUM7WUFDSCxLQUFJLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQztRQUN6QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTCwwQkFBQztBQUFELENBQUMsQUF6SEQsSUF5SEM7QUF6SFksa0RBQW1CIn0=
  117795. /***/ }),
  117796. /* 28 */
  117797. /***/ (function(module, exports, __webpack_require__) {
  117798. "use strict";
  117799. Object.defineProperty(exports, "__esModule", { value: true });
  117800. var minimal_1 = __webpack_require__(29);
  117801. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  117802. var default_1 = __webpack_require__(48);
  117803. exports.defaultConfiguration = default_1.defaultConfiguration;
  117804. var extended_1 = __webpack_require__(49);
  117805. var shadowLight_1 = __webpack_require__(50);
  117806. var environmentMap_1 = __webpack_require__(51);
  117807. var _1 = __webpack_require__(1);
  117808. /**
  117809. * Get the configuration type you need to use as the base for your viewer.
  117810. * The types can either be a single string, or comma separated types that will extend each other. for example:
  117811. *
  117812. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  117813. *
  117814. * @param types a comma-separated string of the type(s) or configuration to load.
  117815. */
  117816. var getConfigurationType = function (types) {
  117817. var config = {};
  117818. var typesSeparated = types.split(",");
  117819. typesSeparated.forEach(function (type) {
  117820. switch (type.trim()) {
  117821. case 'environmentMap':
  117822. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  117823. break;
  117824. case 'shadowDirectionalLight':
  117825. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  117826. break;
  117827. case 'shadowSpotLight':
  117828. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  117829. break;
  117830. case 'default':
  117831. config = _1.deepmerge(config, default_1.defaultConfiguration);
  117832. break;
  117833. case 'minimal':
  117834. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  117835. break;
  117836. case 'none':
  117837. break;
  117838. case 'extended':
  117839. default:
  117840. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  117841. break;
  117842. }
  117843. if (config.extends) {
  117844. config = _1.deepmerge(config, getConfigurationType(config.extends));
  117845. }
  117846. });
  117847. return config;
  117848. };
  117849. exports.getConfigurationType = getConfigurationType;
  117850. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQU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117851. /***/ }),
  117852. /* 29 */
  117853. /***/ (function(module, exports, __webpack_require__) {
  117854. "use strict";
  117855. Object.defineProperty(exports, "__esModule", { value: true });
  117856. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  117857. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  117858. /**
  117859. * The minimal configuration needed to make the viewer work.
  117860. * Some functionalities might not work correctly (like fill-screen)
  117861. */
  117862. exports.minimalConfiguration = {
  117863. version: "0.1",
  117864. templates: {
  117865. main: {
  117866. html: babylonjs_viewer_assets_1.defaultTemplate
  117867. },
  117868. fillContainer: {
  117869. html: babylonjs_viewer_assets_1.fillContainer,
  117870. params: {
  117871. disable: false
  117872. }
  117873. },
  117874. loadingScreen: {
  117875. html: babylonjs_viewer_assets_1.loadingScreen,
  117876. params: {
  117877. backgroundColor: "#000000",
  117878. loadingImage: babylonjs_viewer_assets_2.loading
  117879. }
  117880. },
  117881. viewer: {
  117882. html: babylonjs_viewer_assets_1.defaultViewer,
  117883. },
  117884. overlay: {
  117885. html: babylonjs_viewer_assets_1.overlay,
  117886. params: {
  117887. closeImage: babylonjs_viewer_assets_2.close,
  117888. closeText: 'Close'
  117889. }
  117890. },
  117891. error: {
  117892. html: babylonjs_viewer_assets_1.error
  117893. }
  117894. },
  117895. engine: {
  117896. antialiasing: true
  117897. }
  117898. };
  117899. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  117900. /***/ }),
  117901. /* 30 */
  117902. /***/ (function(module, exports, __webpack_require__) {
  117903. "use strict";
  117904. Object.defineProperty(exports, "__esModule", { value: true });
  117905. exports.babylonFont = __webpack_require__(31);
  117906. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  117907. /***/ }),
  117908. /* 31 */
  117909. /***/ (function(module, exports) {
  117910. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEgAAABgSlp+MVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAACIAAAA3oTfhSJjdnQgAAAEMAAAACAAAAAqCdkJr2ZwZ20AAARQAAAA8AAAAVn8nuaOZ2FzcAAABUAAAAAMAAAADAAIABtnbHlmAAAFTAAACPgAAAzOOMLcQmhlYWQAAA5EAAAAMgAAADb+Z7dYaGhlYQAADngAAAAVAAAAJBABCAZobXR4AAAOkAAAACsAAAA2EzQDvGxvY2EAAA68AAAALgAAAC4W1hOObWF4cAAADuwAAAAcAAAAIACPANFuYW1lAAAPCAAABTwAAAvzL/OWdXBvc3QAABREAAAAEwAAACD/UQB3cHJlcAAAFFgAAACJAAAA03i98g542mNgZp/IOIGBlYGDdRarMQMDozSEZr7IkMYkxMHKysXIxAgGDEAgwIAAvsEKCgwODLzf0zjAfAjJAFbHAuEpMDAAAL2BB0542hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63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GwcrDGiAQ8jqJPQTol/ocgwwzxJiPdRblP6FxB9p12AvsUzlhTRZnG/6FqWCMH0qtsCP+a/jHwPWkfez9DwA2xTIinBIYGpGNiw2yHC71birmEKinqAZ9ZYN8eUE6cKtHAXlHt2kq0Feu0UaYpawMamIdkAzinpFdSrxqStDPGQWbgrrVNPIv0Z0HcJXUWc3Z0h1YjiqPrRE4ZoVUXV2thqQvmKcl4lsPgX3W1pHMKNgmcB1Svdl5bv4OZnyczUDSLNdUpgXVxzWqfKWonkE1Fc5curD3a5ITOgf552HFCR74ui9jbGP5vbefsKTFNQGZojh11LpnN6qIMOu9Px3WtNwOYSZuLI3/dW4D8ba4pSGrKXNNb+azZE4emSlJftF/brFpc0ZtVkSVG23Wz40HNnN7kf57R9qtW+M7M2bs3RPkq4/xgvCOqdNvb+RdZ0AR35z/h1P9ay0PfZPoqH7oH79Gr0Wb0fvRu9DasVw4xFWB/B/QeUd2KNsrg++CbkFE3d0DTQLyYjfgbYLuFq3jaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  117911. /***/ }),
  117912. /* 32 */
  117913. /***/ (function(module, exports, __webpack_require__) {
  117914. "use strict";
  117915. Object.defineProperty(exports, "__esModule", { value: true });
  117916. exports.babylonLogo = __webpack_require__(33);
  117917. exports.close = __webpack_require__(34);
  117918. exports.fullscreen = __webpack_require__(35);
  117919. exports.helpCircle = __webpack_require__(36);
  117920. exports.loading = __webpack_require__(37);
  117921. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  117922. /***/ }),
  117923. /* 33 */
  117924. /***/ (function(module, exports) {
  117925. 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+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwA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AXokCAAAAgBopswEAOIaPSf4Uw5NZYQMAAAAwGspsAACOpUlyLoZHuUopsVeiAAAAAGAslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  117926. /***/ }),
  117927. /* 34 */
  117928. /***/ (function(module, exports) {
  117929. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  117930. /***/ }),
  117931. /* 35 */
  117932. /***/ (function(module, exports) {
  117933. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  117934. /***/ }),
  117935. /* 36 */
  117936. /***/ (function(module, exports) {
  117937. 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=="
  117938. /***/ }),
  117939. /* 37 */
  117940. /***/ (function(module, exports) {
  117941. 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/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N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L5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  117942. /***/ }),
  117943. /* 38 */
  117944. /***/ (function(module, exports, __webpack_require__) {
  117945. "use strict";
  117946. Object.defineProperty(exports, "__esModule", { value: true });
  117947. exports.defaultTemplate = __webpack_require__(39);
  117948. exports.defaultViewer = __webpack_require__(40);
  117949. exports.error = __webpack_require__(41);
  117950. exports.fillContainer = __webpack_require__(42);
  117951. exports.help = __webpack_require__(43);
  117952. exports.loadingScreen = __webpack_require__(44);
  117953. exports.navbar = __webpack_require__(45);
  117954. exports.overlay = __webpack_require__(46);
  117955. exports.share = __webpack_require__(47);
  117956. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  117957. /***/ }),
  117958. /* 39 */
  117959. /***/ (function(module, exports) {
  117960. 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>";
  117961. /***/ }),
  117962. /* 40 */
  117963. /***/ (function(module, exports) {
  117964. 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>";
  117965. /***/ }),
  117966. /* 41 */
  117967. /***/ (function(module, exports) {
  117968. module.exports = "Error loading the model";
  117969. /***/ }),
  117970. /* 42 */
  117971. /***/ (function(module, exports) {
  117972. 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>";
  117973. /***/ }),
  117974. /* 43 */
  117975. /***/ (function(module, exports) {
  117976. module.exports = "HELP";
  117977. /***/ }),
  117978. /* 44 */
  117979. /***/ (function(module, exports) {
  117980. 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}}>";
  117981. /***/ }),
  117982. /* 45 */
  117983. /***/ (function(module, exports) {
  117984. 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>";
  117985. /***/ }),
  117986. /* 46 */
  117987. /***/ (function(module, exports) {
  117988. 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>";
  117989. /***/ }),
  117990. /* 47 */
  117991. /***/ (function(module, exports) {
  117992. module.exports = "SHARE";
  117993. /***/ }),
  117994. /* 48 */
  117995. /***/ (function(module, exports, __webpack_require__) {
  117996. "use strict";
  117997. Object.defineProperty(exports, "__esModule", { value: true });
  117998. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  117999. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  118000. var images = __webpack_require__(2);
  118001. /**
  118002. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  118003. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  118004. */
  118005. exports.defaultConfiguration = {
  118006. version: "3.2.0-alpha4",
  118007. templates: {
  118008. main: {
  118009. html: babylonjs_viewer_assets_1.defaultTemplate,
  118010. params: {
  118011. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  118012. noEscape: true
  118013. }
  118014. },
  118015. fillContainer: {
  118016. html: babylonjs_viewer_assets_1.fillContainer,
  118017. params: {
  118018. disable: false
  118019. }
  118020. },
  118021. loadingScreen: {
  118022. html: babylonjs_viewer_assets_1.loadingScreen,
  118023. params: {
  118024. backgroundColor: "#000000",
  118025. loadingImage: images.loading
  118026. }
  118027. },
  118028. viewer: {
  118029. html: babylonjs_viewer_assets_1.defaultViewer,
  118030. params: {
  118031. enableDragAndDrop: false
  118032. }
  118033. },
  118034. navBar: {
  118035. html: babylonjs_viewer_assets_1.navbar,
  118036. params: {
  118037. speedList: {
  118038. "0.5x": "0.5",
  118039. "1.0x": "1.0",
  118040. "1.5x": "1.5",
  118041. "2.0x": "2.0",
  118042. },
  118043. logoImage: images.babylonLogo,
  118044. logoText: 'BabylonJS',
  118045. logoLink: 'https://babylonjs.com',
  118046. hideHelp: true,
  118047. hideHd: true,
  118048. hideVr: true,
  118049. disableOnFullscreen: false,
  118050. text: {
  118051. hdButton: "Toggle HD",
  118052. fullscreenButton: "Fullscreen",
  118053. helpButton: "Help",
  118054. vrButton: "Toggle VR"
  118055. }
  118056. },
  118057. events: {
  118058. pointerdown: {
  118059. '.navbar-control': true,
  118060. '.help-button': true
  118061. },
  118062. input: {
  118063. '.progress-wrapper': true
  118064. },
  118065. pointerup: {
  118066. '.progress-wrapper': true
  118067. }
  118068. }
  118069. },
  118070. overlay: {
  118071. html: babylonjs_viewer_assets_1.overlay,
  118072. params: {
  118073. closeImage: images.close,
  118074. closeText: 'Close'
  118075. }
  118076. },
  118077. help: {
  118078. html: babylonjs_viewer_assets_1.help
  118079. },
  118080. share: {
  118081. html: babylonjs_viewer_assets_1.share
  118082. },
  118083. error: {
  118084. html: babylonjs_viewer_assets_1.error
  118085. }
  118086. },
  118087. camera: {
  118088. behaviors: {
  118089. autoRotate: {
  118090. type: 0
  118091. },
  118092. framing: {
  118093. type: 2,
  118094. zoomOnBoundingInfo: true,
  118095. zoomStopsAnimation: false
  118096. },
  118097. bouncing: {
  118098. type: 1
  118099. }
  118100. }
  118101. },
  118102. skybox: {},
  118103. ground: {
  118104. receiveShadows: true
  118105. },
  118106. engine: {
  118107. antialiasing: true
  118108. },
  118109. scene: {}
  118110. };
  118111. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQUs7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osZUFBZSxFQUFFLFNBQVM7Z0JBQzFCLFlBQVksRUFBRSxNQUFNLENBQUMsT0FBTzthQUMvQjtTQUNKO1FBQ0QsTUFBTSxFQUFFO1lBQ0osSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixpQkFBaUIsRUFBRSxLQUFLO2FBQzNCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsZ0NBQU07WUF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1NBQ2Q7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtLQUVKO0lBQ0QsTUFBTSxFQUFFO1FBQ0osU0FBUyxFQUFFO1lBQ1AsVUFBVSxFQUFFO2dCQUNSLElBQUksRUFBRSxDQUFDO2FBQ1Y7WUFDRCxPQUFPLEVBQUU7Z0JBQ0wsSUFBSSxFQUFFLENBQUM7Z0JBQ1Asa0JBQWtCLEVBQUUsSUFBSTtnQkFDeEIsa0JBQWtCLEVBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  118112. /***/ }),
  118113. /* 49 */
  118114. /***/ (function(module, exports, __webpack_require__) {
  118115. "use strict";
  118116. Object.defineProperty(exports, "__esModule", { value: true });
  118117. var babylonjs_1 = __webpack_require__(0);
  118118. /**
  118119. * The viewer's "extended" configuration.
  118120. * This configuration defines specific obejcts and parameters that we think make any model look good.
  118121. */
  118122. exports.extendedConfiguration = {
  118123. version: "3.2.0",
  118124. extends: "default",
  118125. camera: {
  118126. exposure: 3.034578,
  118127. fov: 0.7853981633974483,
  118128. contrast: 1.6,
  118129. toneMappingEnabled: true,
  118130. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  118131. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  118132. behaviors: {
  118133. framing: {
  118134. type: 2,
  118135. mode: 0,
  118136. positionScale: 0.5,
  118137. defaultElevation: 0.2617993877991494,
  118138. elevationReturnWaitTime: 3000,
  118139. elevationReturnTime: 2000,
  118140. framingTime: 500,
  118141. zoomStopsAnimation: false,
  118142. radiusScale: 0.866
  118143. },
  118144. autoRotate: {
  118145. type: 0,
  118146. idleRotationWaitTime: 4000,
  118147. idleRotationSpeed: 0.17453292519943295,
  118148. idleRotationSpinupTime: 2500,
  118149. zoomStopsAnimation: false
  118150. },
  118151. bouncing: {
  118152. type: 1,
  118153. lowerRadiusTransitionRange: 0.05,
  118154. upperRadiusTransitionRange: -0.2
  118155. }
  118156. },
  118157. upperRadiusLimit: 5,
  118158. lowerRadiusLimit: 0.5,
  118159. frameOnModelLoad: true,
  118160. framingElevation: 0.2617993877991494,
  118161. framingRotation: 1.5707963267948966,
  118162. radius: 2,
  118163. alpha: 1.5708,
  118164. beta: Math.PI * 0.5 - 0.2618,
  118165. wheelPrecision: 300,
  118166. minZ: 0.1,
  118167. maxZ: 50,
  118168. fovMode: 0,
  118169. pinchPrecision: 1500,
  118170. panningSensibility: 3000
  118171. },
  118172. lights: {
  118173. light0: {
  118174. type: 0,
  118175. frustumEdgeFalloff: 0,
  118176. intensity: 7,
  118177. intensityMode: 0,
  118178. radius: 0.6,
  118179. range: 4.4,
  118180. spotAngle: 60,
  118181. diffuse: {
  118182. r: 1,
  118183. g: 1,
  118184. b: 1
  118185. },
  118186. position: {
  118187. x: -2,
  118188. y: 2.5,
  118189. z: 2
  118190. },
  118191. target: {
  118192. x: 0,
  118193. y: 0,
  118194. z: 0
  118195. },
  118196. enabled: true,
  118197. shadowEnabled: true,
  118198. shadowBufferSize: 512,
  118199. shadowMinZ: 1,
  118200. shadowMaxZ: 10,
  118201. shadowFieldOfView: 60,
  118202. shadowFrustumSize: 2,
  118203. shadowConfig: {
  118204. useBlurCloseExponentialShadowMap: true,
  118205. useKernelBlur: true,
  118206. blurScale: 1.0,
  118207. bias: 0.001,
  118208. depthScale: 50 * (10 - 1),
  118209. frustumEdgeFalloff: 0
  118210. }
  118211. },
  118212. light1: {
  118213. type: 0,
  118214. frustumEdgeFalloff: 0,
  118215. intensity: 7,
  118216. intensityMode: 0,
  118217. radius: 0.4,
  118218. range: 5.8,
  118219. spotAngle: 57,
  118220. diffuse: {
  118221. r: 1,
  118222. g: 1,
  118223. b: 1
  118224. },
  118225. position: {
  118226. x: 4,
  118227. y: 3,
  118228. z: -0.5
  118229. },
  118230. target: {
  118231. x: 0,
  118232. y: 0,
  118233. z: 0
  118234. },
  118235. enabled: true,
  118236. shadowEnabled: false,
  118237. shadowBufferSize: 512,
  118238. shadowMinZ: 0.2,
  118239. shadowMaxZ: 10,
  118240. shadowFieldOfView: 28,
  118241. shadowFrustumSize: 2
  118242. },
  118243. light2: {
  118244. type: 0,
  118245. frustumEdgeFalloff: 0,
  118246. intensity: 1,
  118247. intensityMode: 0,
  118248. radius: 0.5,
  118249. range: 6,
  118250. spotAngle: 42.85,
  118251. diffuse: {
  118252. r: 0.8,
  118253. g: 0.8,
  118254. b: 0.8
  118255. },
  118256. position: {
  118257. x: -1,
  118258. y: 3,
  118259. z: -3
  118260. },
  118261. target: {
  118262. x: 0,
  118263. y: 0,
  118264. z: 0
  118265. },
  118266. enabled: true,
  118267. shadowEnabled: false,
  118268. shadowBufferSize: 512,
  118269. shadowMinZ: 0.2,
  118270. shadowMaxZ: 10,
  118271. shadowFieldOfView: 45,
  118272. shadowFrustumSize: 2
  118273. }
  118274. },
  118275. ground: {
  118276. shadowLevel: 0.9,
  118277. texture: "Ground_2.0-1024.png",
  118278. material: {
  118279. primaryColorHighlightLevel: 0.035,
  118280. primaryColorShadowLevel: 0,
  118281. enableNoise: true,
  118282. useRGBColor: false,
  118283. maxSimultaneousLights: 1,
  118284. diffuseTexture: {
  118285. gammaSpace: true
  118286. }
  118287. },
  118288. opacity: 1,
  118289. mirror: false,
  118290. receiveShadows: true,
  118291. size: 5
  118292. },
  118293. skybox: {
  118294. scale: 11,
  118295. cubeTexture: {
  118296. url: "Skybox_2.0-256.dds"
  118297. },
  118298. material: {
  118299. primaryColorHighlightLevel: 0.03,
  118300. primaryColorShadowLevel: 0.03,
  118301. enableNoise: true,
  118302. useRGBColor: false,
  118303. reflectionTexture: {
  118304. gammaSpace: true
  118305. }
  118306. }
  118307. },
  118308. engine: {
  118309. renderInBackground: true
  118310. },
  118311. scene: {
  118312. flags: {
  118313. shadowsEnabled: true,
  118314. particlesEnabled: false,
  118315. collisionsEnabled: false,
  118316. lightsEnabled: true,
  118317. texturesEnabled: true,
  118318. lensFlaresEnabled: false,
  118319. proceduralTexturesEnabled: false,
  118320. renderTargetsEnabled: true,
  118321. spritesEnabled: false,
  118322. skeletonsEnabled: true,
  118323. audioEnabled: false,
  118324. },
  118325. defaultMaterial: {
  118326. materialType: 'pbr',
  118327. reflectivityColor: {
  118328. r: 0.1,
  118329. g: 0.1,
  118330. b: 0.1
  118331. },
  118332. microSurface: 0.6
  118333. },
  118334. clearColor: {
  118335. r: 0.9,
  118336. g: 0.9,
  118337. b: 0.9,
  118338. a: 1.0
  118339. },
  118340. imageProcessingConfiguration: {
  118341. vignetteCentreX: 0,
  118342. vignetteCentreY: 0,
  118343. vignetteColor: {
  118344. r: 0.086,
  118345. g: 0.184,
  118346. b: 0.259,
  118347. a: 1
  118348. },
  118349. vignetteWeight: 0.855,
  118350. vignetteStretch: 0.5,
  118351. vignetteBlendMode: 0,
  118352. vignetteCameraFov: 0.7853981633974483,
  118353. isEnabled: true,
  118354. colorCurves: {
  118355. shadowsHue: 0,
  118356. shadowsDensity: 0,
  118357. shadowsSaturation: 0,
  118358. shadowsExposure: 0,
  118359. midtonesHue: 0,
  118360. midtonesDensity: 0,
  118361. midtonesExposure: 0,
  118362. midtonesSaturation: 0,
  118363. highlightsHue: 0,
  118364. highlightsDensity: 0,
  118365. highlightsExposure: 0,
  118366. highlightsSaturation: 0
  118367. }
  118368. },
  118369. mainColor: {
  118370. r: 0.8823529411764706,
  118371. g: 0.8823529411764706,
  118372. b: 0.8823529411764706
  118373. }
  118374. },
  118375. loaderPlugins: {
  118376. extendedMaterial: true,
  118377. applyMaterialConfig: true,
  118378. msftLod: true,
  118379. telemetry: true
  118380. },
  118381. model: {
  118382. rotationOffsetAxis: {
  118383. x: 0,
  118384. y: -1,
  118385. z: 0
  118386. },
  118387. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  118388. material: {
  118389. directEnabled: true,
  118390. directIntensity: 0.884,
  118391. emissiveIntensity: 1.04,
  118392. environmentIntensity: 0.6
  118393. },
  118394. entryAnimation: {
  118395. scaling: {
  118396. x: 0,
  118397. y: 0,
  118398. z: 0
  118399. },
  118400. time: 0.5,
  118401. easingFunction: 4,
  118402. easingMode: 1
  118403. },
  118404. exitAnimation: {
  118405. scaling: {
  118406. x: 0,
  118407. y: 0,
  118408. z: 0
  118409. },
  118410. time: 0.5,
  118411. easingFunction: 4,
  118412. easingMode: 1
  118413. },
  118414. normalize: true,
  118415. castShadow: true,
  118416. receiveShadows: true
  118417. },
  118418. lab: {
  118419. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  118420. environmentMap: {
  118421. texture: "EnvMap_2.0-256.env",
  118422. rotationY: 3,
  118423. tintLevel: 0.4
  118424. },
  118425. defaultRenderingPipelines: {
  118426. bloomEnabled: true,
  118427. bloomThreshold: 1.0,
  118428. fxaaEnabled: true,
  118429. bloomWeight: 0.05
  118430. }
  118431. }
  118432. };
  118433. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0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Uk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  118434. /***/ }),
  118435. /* 50 */
  118436. /***/ (function(module, exports, __webpack_require__) {
  118437. "use strict";
  118438. Object.defineProperty(exports, "__esModule", { value: true });
  118439. /**
  118440. * Defines a default directional shadow light for normalized objects (!)
  118441. */
  118442. exports.shadowDirectionalLightConfiguration = {
  118443. model: {
  118444. receiveShadows: true,
  118445. castShadow: true
  118446. },
  118447. ground: {
  118448. receiveShadows: true
  118449. },
  118450. lights: {
  118451. shadowDirectionalLight: {
  118452. type: 1,
  118453. shadowEnabled: true,
  118454. target: { x: 0, y: 0, z: 0.5 },
  118455. position: { x: 1.49, y: 2.39, z: -1.33 },
  118456. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  118457. intensity: 4.887,
  118458. intensityMode: 0,
  118459. shadowBufferSize: 1024,
  118460. shadowFrustumSize: 6.0,
  118461. shadowFieldOfView: 50.977,
  118462. shadowMinZ: 0.1,
  118463. shadowMaxZ: 10.0,
  118464. shadowConfig: {
  118465. blurKernel: 32,
  118466. useBlurCloseExponentialShadowMap: true
  118467. }
  118468. }
  118469. }
  118470. };
  118471. /**
  118472. * Defines a default shadow-enabled spot light for normalized objects.
  118473. */
  118474. exports.shadowSpotlLightConfiguration = {
  118475. model: {
  118476. receiveShadows: true,
  118477. castShadow: true
  118478. },
  118479. ground: {
  118480. receiveShadows: true
  118481. },
  118482. lights: {
  118483. shadowSpotLight: {
  118484. type: 2,
  118485. intensity: 2,
  118486. shadowEnabled: true,
  118487. target: { x: 0, y: 0, z: 0.5 },
  118488. position: { x: 0, y: 3.5, z: 3.7 },
  118489. angle: 1,
  118490. shadowOrthoScale: 0.5,
  118491. shadowBufferSize: 1024,
  118492. shadowMinZ: 0.1,
  118493. shadowMaxZ: 50.0,
  118494. shadowConfig: {
  118495. frustumEdgeFalloff: 0.5,
  118496. blurKernel: 32,
  118497. useBlurExponentialShadowMap: true
  118498. }
  118499. }
  118500. }
  118501. };
  118502. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUUsSUFBSSxFQUFFLENBQUMsRUFBRSxDQUFDLElBQUksRUFBRT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FDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  118503. /***/ }),
  118504. /* 51 */
  118505. /***/ (function(module, exports, __webpack_require__) {
  118506. "use strict";
  118507. Object.defineProperty(exports, "__esModule", { value: true });
  118508. /**
  118509. * Lab-oriented default .env support
  118510. */
  118511. exports.environmentMapConfiguration = {
  118512. lab: {
  118513. assetsRootURL: '/assets/environment/',
  118514. environmentMap: {
  118515. texture: 'EnvMap_2.0-256.env',
  118516. rotationY: 0,
  118517. tintLevel: 0.4
  118518. }
  118519. }
  118520. };
  118521. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  118522. /***/ }),
  118523. /* 52 */
  118524. /***/ (function(module, exports, __webpack_require__) {
  118525. "use strict";
  118526. Object.defineProperty(exports, "__esModule", { value: true });
  118527. /**
  118528. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  118529. * native GroupAnimation class.
  118530. */
  118531. var GroupModelAnimation = /** @class */ (function () {
  118532. /**
  118533. * Create a new GroupModelAnimation object using an AnimationGroup object
  118534. * @param _animationGroup The aniamtion group to base the class on
  118535. */
  118536. function GroupModelAnimation(_animationGroup) {
  118537. var _this = this;
  118538. this._animationGroup = _animationGroup;
  118539. this._state = 0 /* INIT */;
  118540. this._playMode = 1 /* LOOP */;
  118541. this._animationGroup.onAnimationEndObservable.add(function () {
  118542. _this.stop();
  118543. _this._state = 4 /* ENDED */;
  118544. });
  118545. }
  118546. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  118547. /**
  118548. * Get the animation's name
  118549. */
  118550. get: function () {
  118551. return this._animationGroup.name;
  118552. },
  118553. enumerable: true,
  118554. configurable: true
  118555. });
  118556. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  118557. /**
  118558. * Get the current animation's state
  118559. */
  118560. get: function () {
  118561. return this._state;
  118562. },
  118563. enumerable: true,
  118564. configurable: true
  118565. });
  118566. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  118567. /**
  118568. * Gets the speed ratio to use for all animations
  118569. */
  118570. get: function () {
  118571. return this._animationGroup.speedRatio;
  118572. },
  118573. /**
  118574. * Sets the speed ratio to use for all animations
  118575. */
  118576. set: function (value) {
  118577. this._animationGroup.speedRatio = value;
  118578. },
  118579. enumerable: true,
  118580. configurable: true
  118581. });
  118582. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  118583. /**
  118584. * Get the max numbers of frame available in the animation group
  118585. *
  118586. * In correlation to an arry, this would be ".length"
  118587. */
  118588. get: function () {
  118589. return this._animationGroup.to - this._animationGroup.from;
  118590. },
  118591. enumerable: true,
  118592. configurable: true
  118593. });
  118594. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  118595. /**
  118596. * Get the current frame playing right now.
  118597. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  118598. *
  118599. * In correlation to an array, this would be the current index
  118600. */
  118601. get: function () {
  118602. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  118603. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  118604. }
  118605. else {
  118606. return 0;
  118607. }
  118608. },
  118609. enumerable: true,
  118610. configurable: true
  118611. });
  118612. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  118613. /**
  118614. * Get the FPS value of this animation
  118615. */
  118616. get: function () {
  118617. // get the first currentFrame found
  118618. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  118619. var animatable = this._animationGroup.animatables[i];
  118620. var animations = animatable.getAnimations();
  118621. if (!animations || !animations.length) {
  118622. continue;
  118623. }
  118624. for (var idx = 0; idx < animations.length; ++idx) {
  118625. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  118626. return animations[idx].animation.framePerSecond;
  118627. }
  118628. }
  118629. }
  118630. return 0;
  118631. },
  118632. enumerable: true,
  118633. configurable: true
  118634. });
  118635. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  118636. /**
  118637. * What is the animation'S play mode (looping or played once)
  118638. */
  118639. get: function () {
  118640. return this._playMode;
  118641. },
  118642. /**
  118643. * Set the play mode.
  118644. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  118645. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  118646. */
  118647. set: function (value) {
  118648. if (value === this._playMode) {
  118649. return;
  118650. }
  118651. this._playMode = value;
  118652. if (this.state === 1 /* PLAYING */) {
  118653. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  118654. }
  118655. else {
  118656. this._animationGroup.reset();
  118657. this._state = 0 /* INIT */;
  118658. }
  118659. },
  118660. enumerable: true,
  118661. configurable: true
  118662. });
  118663. /**
  118664. * Reset the animation group
  118665. */
  118666. GroupModelAnimation.prototype.reset = function () {
  118667. this._animationGroup.reset();
  118668. };
  118669. /**
  118670. * Restart the animation group
  118671. */
  118672. GroupModelAnimation.prototype.restart = function () {
  118673. if (this.state === 2 /* PAUSED */)
  118674. this._animationGroup.restart();
  118675. else
  118676. this.start();
  118677. };
  118678. /**
  118679. *
  118680. * @param frameNumber Go to a specific frame in the animation
  118681. */
  118682. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  118683. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  118684. };
  118685. /**
  118686. * Start playing the animation.
  118687. */
  118688. GroupModelAnimation.prototype.start = function () {
  118689. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  118690. if (this._animationGroup.isStarted) {
  118691. this._state = 1 /* PLAYING */;
  118692. }
  118693. };
  118694. /**
  118695. * Pause the animation
  118696. */
  118697. GroupModelAnimation.prototype.pause = function () {
  118698. this._animationGroup.pause();
  118699. this._state = 2 /* PAUSED */;
  118700. };
  118701. /**
  118702. * Stop the animation.
  118703. * This will fail silently if the animation group is already stopped.
  118704. */
  118705. GroupModelAnimation.prototype.stop = function () {
  118706. this._animationGroup.stop();
  118707. if (!this._animationGroup.isStarted) {
  118708. this._state = 3 /* STOPPED */;
  118709. }
  118710. };
  118711. /**
  118712. * Dispose this animation object.
  118713. */
  118714. GroupModelAnimation.prototype.dispose = function () {
  118715. this._animationGroup.dispose();
  118716. };
  118717. return GroupModelAnimation;
  118718. }());
  118719. exports.GroupModelAnimation = GroupModelAnimation;
  118720. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLEl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FDLGVBQWUsQ0FBQyxTQUFTLENBQUMsV0FBVyxHQUFHLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDNUUsQ0FBQztJQUVEOztPQUVHO0lBQ0ksbUNBQUssR0FBWjtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxRQUFRLGlCQUEyQixFQUFFLElBQUksQ0FBQyxVQUFVLENBQUMsQ0FBQztRQUN0RixJQUFJLElBQUksQ0FBQyxlQUFlLENBQUMsU0FBUyxFQUFFO1lBQ2hDLElBQUksQ0FBQyxNQUFNLGtCQUF5QixDQUFDO1NBQ3hDO0lBQ0wsQ0FBQztJQUVEOztPQUVHO0lBQ0gsbUNBQUssR0FBTDtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  118721. /***/ }),
  118722. /* 53 */
  118723. /***/ (function(module, exports, __webpack_require__) {
  118724. "use strict";
  118725. Object.defineProperty(exports, "__esModule", { value: true });
  118726. var telemetryLoaderPlugin_1 = __webpack_require__(54);
  118727. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  118728. var msftLodLoaderPlugin_1 = __webpack_require__(55);
  118729. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  118730. var applyMaterialConfig_1 = __webpack_require__(56);
  118731. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  118732. var extendedMaterialLoaderPlugin_1 = __webpack_require__(57);
  118733. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  118734. var babylonjs_1 = __webpack_require__(0);
  118735. var pluginCache = {};
  118736. /**
  118737. * Get a loader plugin according to its name.
  118738. * The plugin will be cached and will be reused if called for again.
  118739. *
  118740. * @param name the name of the plugin
  118741. */
  118742. function getLoaderPluginByName(name) {
  118743. if (!pluginCache[name]) {
  118744. switch (name) {
  118745. case 'telemetry':
  118746. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  118747. break;
  118748. case 'msftLod':
  118749. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  118750. break;
  118751. case 'applyMaterialConfig':
  118752. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  118753. break;
  118754. case 'extendedMaterial':
  118755. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  118756. break;
  118757. }
  118758. }
  118759. return pluginCache[name];
  118760. }
  118761. exports.getLoaderPluginByName = getLoaderPluginByName;
  118762. /**
  118763. *
  118764. */
  118765. function addLoaderPlugin(name, plugin) {
  118766. if (pluginCache[name]) {
  118767. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  118768. }
  118769. pluginCache[name] = plugin;
  118770. }
  118771. exports.addLoaderPlugin = addLoaderPlugin;
  118772. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiw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MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  118773. /***/ }),
  118774. /* 54 */
  118775. /***/ (function(module, exports, __webpack_require__) {
  118776. "use strict";
  118777. Object.defineProperty(exports, "__esModule", { value: true });
  118778. var telemetryManager_1 = __webpack_require__(6);
  118779. var babylonjs_1 = __webpack_require__(0);
  118780. var TelemetryLoaderPlugin = /** @class */ (function () {
  118781. function TelemetryLoaderPlugin() {
  118782. }
  118783. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  118784. this._model = model;
  118785. this._loadStart = babylonjs_1.Tools.Now;
  118786. };
  118787. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  118788. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  118789. model: model,
  118790. loadTime: babylonjs_1.Tools.Now - this._loadStart
  118791. });
  118792. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  118793. };
  118794. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  118795. this._loadEnd = babylonjs_1.Tools.Now;
  118796. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  118797. model: this._model,
  118798. loadTime: this._loadEnd - this._loadStart
  118799. });
  118800. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118801. };
  118802. TelemetryLoaderPlugin.prototype.onComplete = function () {
  118803. this._loadEnd = babylonjs_1.Tools.Now;
  118804. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  118805. model: this._model,
  118806. loadTime: this._loadEnd - this._loadStart
  118807. });
  118808. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118809. };
  118810. return TelemetryLoaderPlugin;
  118811. }());
  118812. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  118813. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0FBK0U7QUFHL0U7SUFBQTtJQXVDQSxDQUFDO0lBaENVLHNDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO1FBQ3BCLElBQUksQ0FBQyxVQUFVLEdBQUcsaUJBQUssQ0FBQyxHQUFHLENBQUM7SUFDaEMsQ0FBQztJQUVNLHdDQUFRLEdBQWYsVUFBZ0IsS0FBa0I7UUFDOUIsbUNBQWdCLENBQUMsU0FBUyxDQUFDLGNBQWMsRUFBRSxLQUFLLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDNUQsS0FBSyxFQUFFLEtBQUs7WUFDWixRQUFRLEVBQUUsaUJBQUssQ0FBQyxHQUFHLEdBQUcsSUFBSSxDQUFDLFVBQVU7U0FDeEMsQ0FBQyxDQUFDO1FBQ0gsbUNBQWdCLENBQUMsZ0JBQWdCLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxLQUFLLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUN2RixDQUFDO0lBRU0sdUNBQU8sR0FBZCxVQUFlLE9BQWUsRU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(function(module, exports, __webpack_require__) {
  118817. "use strict";
  118818. Object.defineProperty(exports, "__esModule", { value: true });
  118819. /**
  118820. * A loder plugin to use MSFT_lod extension correctly (glTF)
  118821. */
  118822. var MSFTLodLoaderPlugin = /** @class */ (function () {
  118823. function MSFTLodLoaderPlugin() {
  118824. }
  118825. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  118826. this._model = model;
  118827. };
  118828. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  118829. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  118830. var MSFT_lod = extension;
  118831. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  118832. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  118833. }
  118834. };
  118835. return MSFTLodLoaderPlugin;
  118836. }());
  118837. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  118838. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBTUE7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  118839. /***/ }),
  118840. /* 56 */
  118841. /***/ (function(module, exports, __webpack_require__) {
  118842. "use strict";
  118843. Object.defineProperty(exports, "__esModule", { value: true });
  118844. /**
  118845. * Force-apply material configuration right after a material was loaded.
  118846. */
  118847. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  118848. function ApplyMaterialConfigPlugin() {
  118849. }
  118850. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  118851. this._model = model;
  118852. };
  118853. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  118854. this._model && this._model._applyModelMaterialConfiguration(material);
  118855. };
  118856. return ApplyMaterialConfigPlugin;
  118857. }());
  118858. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  118859. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  118860. /***/ }),
  118861. /* 57 */
  118862. /***/ (function(module, exports, __webpack_require__) {
  118863. "use strict";
  118864. Object.defineProperty(exports, "__esModule", { value: true });
  118865. var babylonjs_1 = __webpack_require__(0);
  118866. /**
  118867. * A (PBR) material will be extended using this function.
  118868. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  118869. */
  118870. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  118871. function ExtendedMaterialLoaderPlugin() {
  118872. }
  118873. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  118874. var material = baseMaterial;
  118875. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  118876. };
  118877. return ExtendedMaterialLoaderPlugin;
  118878. }());
  118879. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  118880. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTBEO0FBSTFEOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  118881. /***/ }),
  118882. /* 58 */
  118883. /***/ (function(module, exports, __webpack_require__) {
  118884. "use strict";
  118885. Object.defineProperty(exports, "__esModule", { value: true });
  118886. var babylonjs_1 = __webpack_require__(0);
  118887. var ObservablesManager = /** @class */ (function () {
  118888. function ObservablesManager() {
  118889. this.onSceneInitObservable = new babylonjs_1.Observable();
  118890. this.onEngineInitObservable = new babylonjs_1.Observable();
  118891. this.onModelLoadedObservable = new babylonjs_1.Observable();
  118892. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  118893. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  118894. this.onModelAddedObservable = new babylonjs_1.Observable();
  118895. this.onModelRemovedObservable = new babylonjs_1.Observable();
  118896. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  118897. this.onViewerInitStartedObservable = new babylonjs_1.Observable();
  118898. this.onLoaderInitObservable = new babylonjs_1.Observable();
  118899. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  118900. }
  118901. ObservablesManager.prototype.dispose = function () {
  118902. this.onSceneInitObservable.clear();
  118903. this.onEngineInitObservable.clear();
  118904. this.onModelLoadedObservable.clear();
  118905. this.onModelLoadProgressObservable.clear();
  118906. this.onModelLoadErrorObservable.clear();
  118907. this.onModelAddedObservable.clear();
  118908. this.onModelRemovedObservable.clear();
  118909. this.onViewerInitDoneObservable.clear();
  118910. this.onLoaderInitObservable.clear();
  118911. this.onFrameRenderedObservable.clear();
  118912. };
  118913. return ObservablesManager;
  118914. }());
  118915. exports.ObservablesManager = ObservablesManager;
  118916. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUk3SDtJQW9ESTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ2hELElBQUksQ0FBQyw2QkFBNkIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUN0RCxJQUFJLENBQUMsMEJBQTBCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDbkQsSUFBSSxDQUFDLHNCQUFzQixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQy9DLElBQUksQ0FBQyx3QkFBd0IsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNqRCxJQUFJLENBQUMsMEJBQTBCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDbkQsSUFBSSxDQUFDLDZCQUE2QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ3RELElBQUksQ0FBQyxzQkFBc0IsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUMvQyxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVELG9DQUFPLEdBQVA7UUFDSSxJQUFJLENBQUMscUJBQXFCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDbkMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx1QkFBdUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUNyQyxJQUFJLENBQUMsNkJBQTZCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDM0MsSUFBSSxDQUFDLDBCQUEwQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3hDLElBQUksQ0FBQyxzQkFBc0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUNwQyxJQUFJLENBQUMsd0JBQXdCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDdEMsSUFBSSxDQUFDLDBCQUEwQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3hDLElBQUksQ0FBQyxzQkFBc0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUNwQyxJQUFJLENBQUMseUJBQXlCLENBQUMsS0FBSyxFQUFFLENBQUM7SUFDM0MsQ0FBQztJQUVMLHlCQUFDO0FBQUQsQ0FBQyxBQS9FRCxJQStFQztBQS9FWSxnREFBa0IifQ==
  118917. /***/ }),
  118918. /* 59 */
  118919. /***/ (function(module, exports, __webpack_require__) {
  118920. "use strict";
  118921. Object.defineProperty(exports, "__esModule", { value: true });
  118922. var babylonjs_1 = __webpack_require__(0);
  118923. var configuration_1 = __webpack_require__(14);
  118924. var viewerModel_1 = __webpack_require__(5);
  118925. var helper_1 = __webpack_require__(1);
  118926. var viewerLabs_1 = __webpack_require__(60);
  118927. var _1 = __webpack_require__(16);
  118928. var helper_2 = __webpack_require__(1);
  118929. var SceneManager = /** @class */ (function () {
  118930. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  118931. var _this = this;
  118932. this._engine = _engine;
  118933. this._configurationContainer = _configurationContainer;
  118934. this._observablesManager = _observablesManager;
  118935. this._animationBlendingEnabled = true;
  118936. this._white = babylonjs_1.Color3.White();
  118937. this._forceShadowUpdate = false;
  118938. this._processShadows = true;
  118939. this._groundEnabled = true;
  118940. this._groundMirrorEnabled = true;
  118941. this._defaultRenderingPipelineEnabled = false;
  118942. this._globalConfiguration = {};
  118943. this._defaultRenderingPipelineShouldBuild = true;
  118944. // default from rendering pipeline
  118945. this._bloomEnabled = false;
  118946. // default from rendering pipeline
  118947. this._fxaaEnabled = false;
  118948. this._focusOnModel = function (model) {
  118949. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  118950. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  118951. var halfSizeVec = sizeVec.scale(0.5);
  118952. var center = boundingInfo.min.add(halfSizeVec);
  118953. _this.camera.setTarget(center);
  118954. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  118955. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  118956. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  118957. var sceneDiagonalLenght = sizeVec.length();
  118958. if (isFinite(sceneDiagonalLenght))
  118959. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  118960. if (_this._configurationContainer.configuration)
  118961. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  118962. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  118963. // casting ais safe, due to the constraints tested before
  118964. (<ShadowLight>light).setDirectionToTarget(center);
  118965. });*/
  118966. };
  118967. this._cameraBehaviorMapping = {};
  118968. this.models = [];
  118969. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  118970. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  118971. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  118972. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  118973. this.onSceneInitObservable = new babylonjs_1.Observable();
  118974. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  118975. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  118976. this.onVRConfiguredObservable = new babylonjs_1.Observable();
  118977. //this._viewer.onEngineInitObservable.add(() => {
  118978. this._handleHardwareLimitations();
  118979. //});
  118980. this.onSceneInitObservable.add(function (scene) {
  118981. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  118982. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  118983. var updateShadows = function () {
  118984. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  118985. var light = _a[_i];
  118986. var generator = light.getShadowGenerator();
  118987. if (generator) {
  118988. // Processing shadows if animates
  118989. var shadowMap = generator.getShadowMap();
  118990. if (shadowMap) {
  118991. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  118992. }
  118993. }
  118994. }
  118995. };
  118996. scene.registerBeforeRender(function () {
  118997. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  118998. // make sure all models are loaded
  118999. updateShadows();
  119000. _this._forceShadowUpdate = false;
  119001. }
  119002. else if (!(_this.models.every(function (model) {
  119003. if (!model.shadowsRenderedAfterLoad) {
  119004. model.shadowsRenderedAfterLoad = true;
  119005. return false;
  119006. }
  119007. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  119008. }))) {
  119009. updateShadows();
  119010. }
  119011. });
  119012. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  119013. });
  119014. if (this._observablesManager) {
  119015. this._observablesManager.onModelLoadedObservable.add(function (model) {
  119016. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  119017. var light = _a[_i];
  119018. var generator = light.getShadowGenerator();
  119019. if (generator) {
  119020. // Processing shadows if animates
  119021. var shadowMap = generator.getShadowMap();
  119022. if (shadowMap) {
  119023. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  119024. }
  119025. }
  119026. }
  119027. _this._focusOnModel(model);
  119028. });
  119029. this._observablesManager.onModelAddedObservable.add(function (model) {
  119030. _this.models.push(model);
  119031. });
  119032. this._observablesManager.onModelRemovedObservable.add(function (model) {
  119033. _this.models.splice(_this.models.indexOf(model), 1);
  119034. });
  119035. }
  119036. }
  119037. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  119038. get: function () {
  119039. return this._defaultRenderingPipeline;
  119040. },
  119041. enumerable: true,
  119042. configurable: true
  119043. });
  119044. Object.defineProperty(SceneManager.prototype, "vrHelper", {
  119045. get: function () {
  119046. return this._vrHelper;
  119047. },
  119048. enumerable: true,
  119049. configurable: true
  119050. });
  119051. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  119052. /**
  119053. * Returns a boolean representing HDR support
  119054. */
  119055. get: function () {
  119056. return this._hdrSupport;
  119057. },
  119058. enumerable: true,
  119059. configurable: true
  119060. });
  119061. Object.defineProperty(SceneManager.prototype, "mainColor", {
  119062. /**
  119063. * Return the main color defined in the configuration.
  119064. */
  119065. get: function () {
  119066. return this._configurationContainer.mainColor;
  119067. },
  119068. enumerable: true,
  119069. configurable: true
  119070. });
  119071. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  119072. get: function () {
  119073. return this._configurationContainer.reflectionColor;
  119074. },
  119075. enumerable: true,
  119076. configurable: true
  119077. });
  119078. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  119079. get: function () {
  119080. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  119081. },
  119082. set: function (value) {
  119083. this.scene.animationPropertiesOverride.enableBlending = value;
  119084. },
  119085. enumerable: true,
  119086. configurable: true
  119087. });
  119088. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  119089. get: function () {
  119090. return this._observablesManager;
  119091. },
  119092. enumerable: true,
  119093. configurable: true
  119094. });
  119095. Object.defineProperty(SceneManager.prototype, "processShadows", {
  119096. /**
  119097. * The flag defining whether shadows are rendered constantly or once.
  119098. */
  119099. get: function () {
  119100. return this._processShadows;
  119101. },
  119102. /**
  119103. * Should shadows be rendered every frame, or only once and stop.
  119104. * This can be used to optimize a scene.
  119105. *
  119106. * Not that the shadows will NOT disapear but will remain in place.
  119107. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  119108. */
  119109. set: function (process) {
  119110. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  119111. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  119112. var light = _a[_i];
  119113. var generator = light.getShadowGenerator();
  119114. if (generator) {
  119115. var shadowMap = generator.getShadowMap();
  119116. if (shadowMap) {
  119117. shadowMap.refreshRate = refreshType;
  119118. }
  119119. }
  119120. }
  119121. this._processShadows = process;
  119122. },
  119123. enumerable: true,
  119124. configurable: true
  119125. });
  119126. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  119127. get: function () {
  119128. return this._groundEnabled;
  119129. },
  119130. set: function (newValue) {
  119131. if (newValue === this._groundEnabled)
  119132. return;
  119133. this._groundEnabled = newValue;
  119134. if (this.environmentHelper && this.environmentHelper.ground) {
  119135. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  119136. }
  119137. },
  119138. enumerable: true,
  119139. configurable: true
  119140. });
  119141. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  119142. /**
  119143. * gets wether the reflection is disabled.
  119144. */
  119145. get: function () {
  119146. return this._groundMirrorEnabled;
  119147. },
  119148. /**
  119149. * sets wether the reflection is disabled.
  119150. */
  119151. set: function (value) {
  119152. if (this._groundMirrorEnabled === value) {
  119153. return;
  119154. }
  119155. this._groundMirrorEnabled = value;
  119156. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  119157. if (!value) {
  119158. this.environmentHelper.groundMaterial.reflectionTexture = null;
  119159. }
  119160. else {
  119161. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  119162. }
  119163. }
  119164. },
  119165. enumerable: true,
  119166. configurable: true
  119167. });
  119168. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  119169. get: function () {
  119170. return this._defaultRenderingPipelineEnabled;
  119171. },
  119172. set: function (value) {
  119173. if (value === this._defaultRenderingPipelineEnabled) {
  119174. return;
  119175. }
  119176. this._defaultRenderingPipelineEnabled = value;
  119177. this._rebuildPostprocesses();
  119178. if (this._defaultRenderingPipeline) {
  119179. this._defaultRenderingPipelineShouldBuild = false;
  119180. this._defaultRenderingPipeline.prepare();
  119181. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  119182. }
  119183. },
  119184. enumerable: true,
  119185. configurable: true
  119186. });
  119187. /**
  119188. * Sets the engine flags to unlock all babylon features.
  119189. * Can also be configured using the scene.flags configuration object
  119190. */
  119191. SceneManager.prototype.unlockBabylonFeatures = function () {
  119192. this.scene.shadowsEnabled = true;
  119193. this.scene.particlesEnabled = true;
  119194. this.scene.postProcessesEnabled = true;
  119195. this.scene.collisionsEnabled = true;
  119196. this.scene.lightsEnabled = true;
  119197. this.scene.texturesEnabled = true;
  119198. this.scene.lensFlaresEnabled = true;
  119199. this.scene.proceduralTexturesEnabled = true;
  119200. this.scene.renderTargetsEnabled = true;
  119201. this.scene.spritesEnabled = true;
  119202. this.scene.skeletonsEnabled = true;
  119203. this.scene.audioEnabled = true;
  119204. };
  119205. /**
  119206. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  119207. */
  119208. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  119209. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  119210. // if the scen exists, dispose it.
  119211. if (this.scene) {
  119212. this.scene.dispose();
  119213. }
  119214. // create a new scene
  119215. this.scene = new babylonjs_1.Scene(this._engine);
  119216. this._configurationContainer.scene = this.scene;
  119217. // set a default PBR material
  119218. if (!sceneConfiguration.defaultMaterial) {
  119219. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  119220. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  119221. defaultMaterial.microSurface = 0.6;
  119222. if (this.scene.defaultMaterial) {
  119223. this.scene.defaultMaterial.dispose();
  119224. }
  119225. this.scene.defaultMaterial = defaultMaterial;
  119226. }
  119227. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  119228. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  119229. /*if (sceneConfiguration.glow) {
  119230. let options: Partial<IGlowLayerOptions> = {
  119231. mainTextureFixedSize: 512
  119232. };
  119233. if (typeof sceneConfiguration.glow === 'object') {
  119234. options = sceneConfiguration.glow
  119235. }
  119236. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  119237. }*/
  119238. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  119239. };
  119240. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  119241. if (clearModels === void 0) { clearModels = true; }
  119242. if (clearLights === void 0) { clearLights = false; }
  119243. if (clearModels) {
  119244. this.models.forEach(function (m) { return m.dispose(); });
  119245. this.models.length = 0;
  119246. }
  119247. if (clearLights) {
  119248. this.scene.lights.forEach(function (l) { return l.dispose(); });
  119249. }
  119250. };
  119251. /**
  119252. * This will update the scene's configuration, including camera, lights, environment.
  119253. * @param newConfiguration the delta that should be configured. This includes only the changes
  119254. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  119255. */
  119256. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  119257. var _this = this;
  119258. if (this._configurationContainer) {
  119259. this._globalConfiguration = this._configurationContainer.configuration;
  119260. }
  119261. else {
  119262. this._globalConfiguration = newConfiguration;
  119263. }
  119264. if (newConfiguration.lab) {
  119265. if (newConfiguration.lab.assetsRootURL) {
  119266. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  119267. }
  119268. }
  119269. // update scene configuration
  119270. if (newConfiguration.scene) {
  119271. this._configureScene(newConfiguration.scene);
  119272. }
  119273. // optimizer
  119274. if (newConfiguration.optimizer !== undefined) {
  119275. this._configureOptimizer(newConfiguration.optimizer);
  119276. }
  119277. // configure model
  119278. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  119279. this._configureModel(newConfiguration.model);
  119280. }*/
  119281. // lights
  119282. this._configureLights(newConfiguration.lights);
  119283. // environment
  119284. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  119285. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  119286. }
  119287. // camera
  119288. this._configureCamera(newConfiguration.camera);
  119289. if (newConfiguration.vr !== undefined) {
  119290. this._configureVR(newConfiguration.vr);
  119291. }
  119292. if (newConfiguration.lab) {
  119293. if (newConfiguration.lab.environmentMap) {
  119294. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  119295. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  119296. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  119297. });
  119298. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  119299. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  119300. }
  119301. }
  119302. // rendering piplines
  119303. if (newConfiguration.lab.defaultRenderingPipelines) {
  119304. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  119305. if (typeof pipelineConfig === 'boolean') {
  119306. this.defaultRenderingPipelineEnabled = pipelineConfig;
  119307. }
  119308. else {
  119309. this.defaultRenderingPipelineEnabled = true;
  119310. }
  119311. }
  119312. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  119313. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  119314. this.environmentHelper.setMainColor(mainColor);
  119315. }
  119316. if (newConfiguration.lab.globalLightRotation !== undefined) {
  119317. // rotate all lights that are shadow lights
  119318. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  119319. // casting and '!' are safe, due to the constraints tested before
  119320. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  119321. });
  119322. this._forceShadowUpdate = true;
  119323. }
  119324. }
  119325. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  119326. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  119327. }
  119328. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  119329. this._defaultRenderingPipelineShouldBuild = false;
  119330. this._defaultRenderingPipeline.prepare();
  119331. }
  119332. };
  119333. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  119334. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  119335. if (this._defaultRenderingPipeline) {
  119336. this._defaultRenderingPipeline.dispose();
  119337. this._defaultRenderingPipeline = null;
  119338. this.scene.autoClearDepthAndStencil = true;
  119339. this.scene.autoClear = true;
  119340. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  119341. }
  119342. return;
  119343. }
  119344. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  119345. if (pipelineConfig) {
  119346. if (!this._defaultRenderingPipeline) {
  119347. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  119348. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  119349. }
  119350. this.scene.autoClear = false;
  119351. this.scene.autoClearDepthAndStencil = false;
  119352. this._defaultRenderingPipelineShouldBuild = true;
  119353. var bloomEnabled = this._bloomEnabled;
  119354. if (typeof pipelineConfig !== 'boolean') {
  119355. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  119356. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  119357. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  119358. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  119359. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  119360. }
  119361. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  119362. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  119363. }
  119364. };
  119365. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  119366. get: function () {
  119367. return this._bloomEnabled;
  119368. },
  119369. set: function (value) {
  119370. if (this._bloomEnabled === value) {
  119371. return;
  119372. }
  119373. this._bloomEnabled = value;
  119374. this._rebuildPostprocesses();
  119375. if (this._defaultRenderingPipeline) {
  119376. this._defaultRenderingPipelineShouldBuild = false;
  119377. this._defaultRenderingPipeline.prepare();
  119378. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  119379. }
  119380. },
  119381. enumerable: true,
  119382. configurable: true
  119383. });
  119384. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  119385. get: function () {
  119386. return this._fxaaEnabled;
  119387. },
  119388. set: function (value) {
  119389. if (this._fxaaEnabled === value) {
  119390. return;
  119391. }
  119392. this._fxaaEnabled = value;
  119393. this._rebuildPostprocesses();
  119394. if (this._defaultRenderingPipeline) {
  119395. this._defaultRenderingPipelineShouldBuild = false;
  119396. this._defaultRenderingPipeline.prepare();
  119397. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  119398. }
  119399. },
  119400. enumerable: true,
  119401. configurable: true
  119402. });
  119403. /**
  119404. * internally configure the scene using the provided configuration.
  119405. * The scene will not be recreated, but just updated.
  119406. * @param sceneConfig the (new) scene configuration
  119407. */
  119408. SceneManager.prototype._configureScene = function (sceneConfig) {
  119409. // sanity check!
  119410. if (!this.scene) {
  119411. return;
  119412. }
  119413. var cc = sceneConfig.clearColor;
  119414. var oldcc = this.scene.clearColor;
  119415. if (cc) {
  119416. if (cc.r !== undefined) {
  119417. oldcc.r = cc.r;
  119418. }
  119419. if (cc.g !== undefined) {
  119420. oldcc.g = cc.g;
  119421. }
  119422. if (cc.b !== undefined) {
  119423. oldcc.b = cc.b;
  119424. }
  119425. if (cc.a !== undefined) {
  119426. oldcc.a = cc.a;
  119427. }
  119428. }
  119429. // image processing configuration - optional.
  119430. if (sceneConfig.imageProcessingConfiguration) {
  119431. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  119432. }
  119433. //animation properties override
  119434. if (sceneConfig.animationPropertiesOverride) {
  119435. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  119436. }
  119437. if (sceneConfig.environmentTexture) {
  119438. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  119439. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  119440. this.scene.environmentTexture.dispose();
  119441. }
  119442. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  119443. this.scene.environmentTexture = environmentTexture;
  119444. }
  119445. }
  119446. if (sceneConfig.debug === true) {
  119447. this.scene.debugLayer.show();
  119448. }
  119449. else if (sceneConfig.debug === false) {
  119450. if (this.scene.debugLayer.isVisible()) {
  119451. this.scene.debugLayer.hide();
  119452. }
  119453. }
  119454. if (sceneConfig.disableHdr) {
  119455. this._handleHardwareLimitations(false);
  119456. }
  119457. else {
  119458. this._handleHardwareLimitations(true);
  119459. }
  119460. if (sceneConfig.renderInBackground !== undefined) {
  119461. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  119462. }
  119463. var canvas = this._engine.getRenderingCanvas();
  119464. if (canvas) {
  119465. if (this.camera && sceneConfig.disableCameraControl) {
  119466. this.camera.detachControl(canvas);
  119467. }
  119468. else if (this.camera && sceneConfig.disableCameraControl === false) {
  119469. this.camera.attachControl(canvas);
  119470. }
  119471. }
  119472. // process mainColor changes:
  119473. if (sceneConfig.mainColor) {
  119474. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  119475. var mc = sceneConfig.mainColor;
  119476. if (mc.r !== undefined) {
  119477. this.mainColor.r = mc.r;
  119478. }
  119479. if (mc.g !== undefined) {
  119480. this.mainColor.g = mc.g;
  119481. }
  119482. if (mc.b !== undefined) {
  119483. this.mainColor.b = mc.b;
  119484. }
  119485. this.reflectionColor.copyFrom(this.mainColor);
  119486. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  119487. // reflection color
  119488. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  119489. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  119490. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  119491. this.reflectionColor.copyFrom(tmpColor3);
  119492. //update the environment, if exists
  119493. if (this.environmentHelper) {
  119494. if (this.environmentHelper.groundMaterial) {
  119495. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  119496. }
  119497. if (this.environmentHelper.skyboxMaterial) {
  119498. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  119499. }
  119500. }
  119501. }
  119502. if (sceneConfig.defaultMaterial) {
  119503. var conf = sceneConfig.defaultMaterial;
  119504. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  119505. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  119506. this.scene.defaultMaterial.dispose();
  119507. if (conf.materialType === 'standard') {
  119508. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  119509. }
  119510. else {
  119511. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  119512. }
  119513. }
  119514. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  119515. }
  119516. if (sceneConfig.flags) {
  119517. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  119518. }
  119519. this.onSceneConfiguredObservable.notifyObservers({
  119520. sceneManager: this,
  119521. object: this.scene,
  119522. newConfiguration: sceneConfig
  119523. });
  119524. };
  119525. /**
  119526. * Configure the scene optimizer.
  119527. * The existing scene optimizer will be disposed and a new one will be created.
  119528. * @param optimizerConfig the (new) optimizer configuration
  119529. */
  119530. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  119531. var _this = this;
  119532. if (typeof optimizerConfig === 'boolean') {
  119533. if (this.sceneOptimizer) {
  119534. this.sceneOptimizer.stop();
  119535. this.sceneOptimizer.dispose();
  119536. delete this.sceneOptimizer;
  119537. }
  119538. if (optimizerConfig) {
  119539. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  119540. this.sceneOptimizer.start();
  119541. }
  119542. }
  119543. else {
  119544. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  119545. // check for degradation
  119546. if (optimizerConfig.degradation) {
  119547. switch (optimizerConfig.degradation) {
  119548. case "low":
  119549. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  119550. break;
  119551. case "moderate":
  119552. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  119553. break;
  119554. case "hight":
  119555. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  119556. break;
  119557. }
  119558. }
  119559. if (this.sceneOptimizer) {
  119560. this.sceneOptimizer.stop();
  119561. this.sceneOptimizer.dispose();
  119562. }
  119563. if (optimizerConfig.custom) {
  119564. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  119565. if (customOptimizer_1) {
  119566. optimizerOptions.addCustomOptimization(function () {
  119567. return customOptimizer_1(_this);
  119568. }, function () {
  119569. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  119570. });
  119571. }
  119572. }
  119573. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  119574. this.sceneOptimizer.start();
  119575. }
  119576. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  119577. sceneManager: this,
  119578. object: this.sceneOptimizer,
  119579. newConfiguration: optimizerConfig
  119580. });
  119581. };
  119582. /**
  119583. * configure all models using the configuration.
  119584. * @param modelConfiguration the configuration to use to reconfigure the models
  119585. */
  119586. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  119587. this.models.forEach(model => {
  119588. model.updateConfiguration(modelConfiguration);
  119589. });
  119590. this.onModelsConfiguredObservable.notifyObservers({
  119591. sceneManager: this,
  119592. object: this.models,
  119593. newConfiguration: modelConfiguration
  119594. });
  119595. }*/
  119596. SceneManager.prototype._configureVR = function (vrConfig) {
  119597. var _this = this;
  119598. if (vrConfig.disabled) {
  119599. if (this._vrHelper) {
  119600. if (this._vrHelper.isInVRMode) {
  119601. this._vrHelper.exitVR();
  119602. }
  119603. this._vrHelper.dispose();
  119604. this._vrHelper = undefined;
  119605. }
  119606. return;
  119607. }
  119608. var vrOptions = helper_2.deepmerge({
  119609. useCustomVRButton: true,
  119610. createDeviceOrientationCamera: false,
  119611. trackPosition: true
  119612. }, vrConfig.vrOptions || {});
  119613. this._vrHelper = this.scene.createDefaultVRExperience(vrOptions);
  119614. if (!vrConfig.disableInteractions) {
  119615. this._vrHelper.enableInteractions();
  119616. }
  119617. if (!vrConfig.disableTeleportation) {
  119618. var floorMeshName = vrConfig.overrideFloorMeshName || "BackgroundPlane";
  119619. this._vrHelper.enableTeleportation({
  119620. floorMeshName: floorMeshName
  119621. });
  119622. }
  119623. if (vrConfig.rotateUsingControllers) {
  119624. var rotationOffset_1;
  119625. this._vrHelper.onControllerMeshLoadedObservable.add(function (controller) {
  119626. controller.onTriggerStateChangedObservable.add(function (data) {
  119627. if (controller.mesh && controller.mesh.rotationQuaternion) {
  119628. if (data.pressed) {
  119629. if (!rotationOffset_1) {
  119630. _this.models[0].rootMesh.rotationQuaternion = _this.models[0].rootMesh.rotationQuaternion || new babylonjs_1.Quaternion();
  119631. rotationOffset_1 = controller.mesh.rotationQuaternion.conjugate().multiply(_this.models[0].rootMesh.rotationQuaternion);
  119632. }
  119633. }
  119634. else {
  119635. rotationOffset_1 = null;
  119636. }
  119637. }
  119638. });
  119639. _this.scene.registerBeforeRender(function () {
  119640. if (_this.models[0]) {
  119641. if (rotationOffset_1 && controller.mesh && controller.mesh.rotationQuaternion) {
  119642. _this.models[0].rootMesh.rotationQuaternion.copyFrom(controller.mesh.rotationQuaternion).multiplyInPlace(rotationOffset_1);
  119643. }
  119644. else {
  119645. _this.models[0].rootMesh.rotationQuaternion = null;
  119646. }
  119647. }
  119648. });
  119649. });
  119650. }
  119651. this.onVRConfiguredObservable.notifyObservers({
  119652. sceneManager: this,
  119653. object: this._vrHelper,
  119654. newConfiguration: vrConfig
  119655. });
  119656. };
  119657. /**
  119658. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  119659. * @param cameraConfig the new camera configuration
  119660. * @param model optionally use the model to configure the camera.
  119661. */
  119662. SceneManager.prototype._configureCamera = function (cameraConfig) {
  119663. var _this = this;
  119664. if (cameraConfig === void 0) { cameraConfig = {}; }
  119665. if (!this.scene.activeCamera) {
  119666. var attachControl = true;
  119667. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  119668. attachControl = false;
  119669. }
  119670. this.scene.createDefaultCamera(true, true, attachControl);
  119671. this.camera = this.scene.activeCamera;
  119672. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  119673. }
  119674. if (!this.camera) {
  119675. this.camera = this.scene.activeCamera;
  119676. }
  119677. if (cameraConfig.position) {
  119678. var newPosition = this.camera.position.clone();
  119679. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  119680. this.camera.setPosition(newPosition);
  119681. }
  119682. if (cameraConfig.target) {
  119683. var newTarget = this.camera.target.clone();
  119684. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  119685. this.camera.setTarget(newTarget);
  119686. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  119687. this._focusOnModel(this.models[0]);
  119688. }*/
  119689. if (cameraConfig.rotation) {
  119690. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  119691. }
  119692. if (cameraConfig.behaviors) {
  119693. for (var name_1 in cameraConfig.behaviors) {
  119694. if (cameraConfig.behaviors[name_1] !== undefined) {
  119695. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  119696. }
  119697. }
  119698. }
  119699. ;
  119700. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  119701. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  119702. });
  119703. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  119704. var sceneDiagonalLength = sceneDiagonal.length();
  119705. if (isFinite(sceneDiagonalLength)) {
  119706. this.camera.upperRadiusLimit = sceneDiagonalLength * 4;
  119707. }
  119708. // sanity check!
  119709. if (this.scene.imageProcessingConfiguration) {
  119710. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  119711. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  119712. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  119713. }
  119714. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  119715. this.onCameraConfiguredObservable.notifyObservers({
  119716. sceneManager: this,
  119717. object: this.camera,
  119718. newConfiguration: cameraConfig
  119719. });
  119720. };
  119721. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  119722. var _this = this;
  119723. if (!skyboxConifguration && !groundConfiguration) {
  119724. if (this.environmentHelper) {
  119725. this.environmentHelper.dispose();
  119726. this.environmentHelper = undefined;
  119727. }
  119728. ;
  119729. }
  119730. else {
  119731. var options = {
  119732. createGround: !!groundConfiguration && this._groundEnabled,
  119733. createSkybox: !!skyboxConifguration,
  119734. setupImageProcessing: false,
  119735. };
  119736. // will that cause problems with model ground configuration?
  119737. /*if (model) {
  119738. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  119739. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  119740. const halfSizeVec = sizeVec.scale(0.5);
  119741. const center = boundingInfo.min.add(halfSizeVec);
  119742. options.groundYBias = -center.y;
  119743. }*/
  119744. if (groundConfiguration) {
  119745. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  119746. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  119747. if (groundSize) {
  119748. options.groundSize = groundSize;
  119749. }
  119750. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  119751. if (groundConfig_1.shadowLevel !== undefined) {
  119752. options.groundShadowLevel = groundConfig_1.shadowLevel;
  119753. }
  119754. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  119755. if (groundConfig_1.texture) {
  119756. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  119757. }
  119758. if (groundConfig_1.color) {
  119759. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  119760. }
  119761. if (groundConfig_1.opacity !== undefined) {
  119762. options.groundOpacity = groundConfig_1.opacity;
  119763. }
  119764. if (groundConfig_1.mirror) {
  119765. options.enableGroundMirror = true;
  119766. // to prevent undefines
  119767. if (typeof groundConfig_1.mirror === "object") {
  119768. if (groundConfig_1.mirror.amount !== undefined)
  119769. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  119770. if (groundConfig_1.mirror.sizeRatio !== undefined)
  119771. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  119772. if (groundConfig_1.mirror.blurKernel !== undefined)
  119773. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  119774. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  119775. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  119776. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  119777. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  119778. if (this._defaultPipelineTextureType !== undefined)
  119779. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  119780. }
  119781. }
  119782. }
  119783. var postInitSkyboxMaterial = false;
  119784. if (skyboxConifguration) {
  119785. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  119786. if (conf.material && conf.material.imageProcessingConfiguration) {
  119787. options.setupImageProcessing = false; // will be configured later manually.
  119788. }
  119789. var skyboxSize = conf.scale;
  119790. if (skyboxSize) {
  119791. options.skyboxSize = skyboxSize;
  119792. }
  119793. options.sizeAuto = !options.skyboxSize;
  119794. if (conf.color) {
  119795. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  119796. }
  119797. if (conf.cubeTexture && conf.cubeTexture.url) {
  119798. if (typeof conf.cubeTexture.url === "string") {
  119799. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  119800. }
  119801. else {
  119802. // init later!
  119803. postInitSkyboxMaterial = true;
  119804. }
  119805. }
  119806. if (conf.material) {
  119807. postInitSkyboxMaterial = true;
  119808. }
  119809. }
  119810. options.setupImageProcessing = false; // TMP
  119811. if (!this.environmentHelper) {
  119812. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  119813. }
  119814. else {
  119815. // unlikely, but there might be a new scene! we need to dispose.
  119816. // get the scene used by the envHelper
  119817. var scene = this.environmentHelper.rootMesh.getScene();
  119818. // is it a different scene? Oh no!
  119819. if (scene !== this.scene) {
  119820. this.environmentHelper.dispose();
  119821. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  119822. }
  119823. else {
  119824. // recreate the ground
  119825. if (this.environmentHelper.ground) {
  119826. this.environmentHelper.ground.dispose();
  119827. }
  119828. // recreate the skybox
  119829. if (this.environmentHelper.skybox) {
  119830. this.environmentHelper.skybox.dispose();
  119831. }
  119832. this.environmentHelper.updateOptions(options);
  119833. // update doesn't change the size of the skybox and ground, so we have to recreate!
  119834. //this.environmentHelper.dispose();
  119835. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  119836. }
  119837. }
  119838. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  119839. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  119840. }
  119841. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  119842. if (this.environmentHelper.groundMaterial && groundConfig) {
  119843. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  119844. if (groundConfig.material) {
  119845. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  119846. }
  119847. if (this.environmentHelper.groundMirror) {
  119848. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  119849. // TODO user camera exposure value to set the mirror clear color
  119850. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  119851. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  119852. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  119853. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  119854. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  119855. this.environmentHelper.groundMirror.clearColor.a = 1;
  119856. if (!this.groundMirrorEnabled) {
  119857. this.environmentHelper.groundMaterial.reflectionTexture = null;
  119858. }
  119859. }
  119860. }
  119861. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  119862. if (skyboxMaterial) {
  119863. skyboxMaterial._perceptualColor = this.mainColor;
  119864. if (postInitSkyboxMaterial) {
  119865. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  119866. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  119867. }
  119868. }
  119869. }
  119870. }
  119871. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  119872. _this._updateGroundMirrorRenderList(model);
  119873. });
  119874. this.onEnvironmentConfiguredObservable.notifyObservers({
  119875. sceneManager: this,
  119876. object: this.environmentHelper,
  119877. newConfiguration: {
  119878. skybox: skyboxConifguration,
  119879. ground: groundConfiguration
  119880. }
  119881. });
  119882. };
  119883. /**
  119884. * configure the lights.
  119885. *
  119886. * @param lightsConfiguration the (new) light(s) configuration
  119887. * @param model optionally use the model to configure the camera.
  119888. */
  119889. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  119890. var _this = this;
  119891. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  119892. // sanity check!
  119893. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  119894. if (!lightKeys.length) {
  119895. if (!this.scene.lights.length)
  119896. this.scene.createDefaultLight(true);
  119897. }
  119898. else {
  119899. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  119900. // compare to the global (!) configuration object and dispose unneeded:
  119901. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  119902. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  119903. lightsAvailable_1.forEach(function (lName) {
  119904. if (lightsToConfigure_1.indexOf(lName) === -1) {
  119905. _this.scene.getLightByName(lName).dispose();
  119906. }
  119907. });
  119908. }
  119909. lightKeys.forEach(function (name, idx) {
  119910. var lightConfig = { type: 0 };
  119911. if (typeof lightsConfiguration[name] === 'object') {
  119912. lightConfig = lightsConfiguration[name];
  119913. }
  119914. if (typeof lightsConfiguration[name] === 'number') {
  119915. lightConfig.type = lightsConfiguration[name];
  119916. }
  119917. lightConfig.name = name;
  119918. var light;
  119919. // light is not already available
  119920. if (lightsAvailable_1.indexOf(name) === -1) {
  119921. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  119922. if (!constructor)
  119923. return;
  119924. light = constructor();
  119925. }
  119926. else {
  119927. // available? get it from the scene
  119928. light = _this.scene.getLightByName(name);
  119929. if (typeof lightsConfiguration[name] === 'boolean') {
  119930. lightConfig.type = light.getTypeID();
  119931. }
  119932. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  119933. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  119934. light.dispose();
  119935. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  119936. if (!constructor)
  119937. return;
  119938. light = constructor();
  119939. }
  119940. }
  119941. // if config set the light to false, dispose it.
  119942. if (lightsConfiguration[name] === false) {
  119943. light.dispose();
  119944. return;
  119945. }
  119946. //enabled
  119947. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  119948. light.setEnabled(enabled);
  119949. helper_1.extendClassWithConfig(light, lightConfig);
  119950. //position. Some lights don't support shadows
  119951. if (light instanceof babylonjs_1.ShadowLight) {
  119952. // set default values
  119953. light.shadowMinZ = light.shadowMinZ || 0.2;
  119954. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  119955. if (lightConfig.target) {
  119956. if (light.setDirectionToTarget) {
  119957. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  119958. light.setDirectionToTarget(target);
  119959. }
  119960. }
  119961. else if (lightConfig.direction) {
  119962. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  119963. light.direction = direction;
  119964. }
  119965. var isShadowEnabled = false;
  119966. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  119967. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  119968. isShadowEnabled = true;
  119969. }
  119970. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  119971. var spotLight = light;
  119972. if (lightConfig.spotAngle !== undefined) {
  119973. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  119974. }
  119975. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  119976. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  119977. }
  119978. isShadowEnabled = true;
  119979. }
  119980. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  119981. if (lightConfig.shadowFieldOfView) {
  119982. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  119983. }
  119984. isShadowEnabled = true;
  119985. }
  119986. var shadowGenerator_1 = light.getShadowGenerator();
  119987. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  119988. var bufferSize = lightConfig.shadowBufferSize || 256;
  119989. if (!shadowGenerator_1) {
  119990. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  119991. }
  119992. var blurKernel = _this.getBlurKernel(light, bufferSize);
  119993. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  119994. shadowGenerator_1.blurKernel = blurKernel;
  119995. //override defaults
  119996. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  119997. // add the focues meshes to the shadow list
  119998. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  119999. _this._updateShadowRenderList(shadowGenerator_1, model);
  120000. });
  120001. //if (model) {
  120002. _this._updateShadowRenderList(shadowGenerator_1);
  120003. //}
  120004. }
  120005. else if (shadowGenerator_1) {
  120006. shadowGenerator_1.dispose();
  120007. }
  120008. }
  120009. });
  120010. // render priority
  120011. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  120012. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  120013. var configuration = globalLightsConfiguration_1[name];
  120014. var light = _this.scene.getLightByName(name);
  120015. // sanity check
  120016. if (!light)
  120017. return;
  120018. light.renderPriority = -idx;
  120019. });
  120020. }
  120021. this.onLightsConfiguredObservable.notifyObservers({
  120022. sceneManager: this,
  120023. object: this.scene.lights,
  120024. newConfiguration: lightsConfiguration
  120025. });
  120026. };
  120027. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  120028. var focusMeshes = model ? model.meshes : this.scene.meshes;
  120029. // add the focues meshes to the shadow list
  120030. var shadownMap = shadowGenerator.getShadowMap();
  120031. if (!shadownMap)
  120032. return;
  120033. if (resetList && shadownMap.renderList) {
  120034. shadownMap.renderList.length = 0;
  120035. }
  120036. else {
  120037. shadownMap.renderList = shadownMap.renderList || [];
  120038. }
  120039. for (var index = 0; index < focusMeshes.length; index++) {
  120040. var mesh = focusMeshes[index];
  120041. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  120042. shadownMap.renderList.push(mesh);
  120043. }
  120044. }
  120045. if (!this._shadowGroundPlane) {
  120046. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  120047. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  120048. shadowGroundPlane.useVertexColors = false;
  120049. //material isn't ever used in rendering, just used to set back face culling
  120050. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  120051. shadowGroundPlane.material.backFaceCulling = false;
  120052. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  120053. shadowGroundPlane.freezeWorldMatrix();
  120054. this._shadowGroundPlane = shadowGroundPlane;
  120055. this.scene.removeMesh(shadowGroundPlane);
  120056. }
  120057. }
  120058. else {
  120059. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  120060. this._shadowGroundPlane.dispose();
  120061. this._shadowGroundPlane = null;
  120062. }
  120063. }
  120064. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  120065. shadownMap.renderList.push(this._shadowGroundPlane);
  120066. }
  120067. };
  120068. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  120069. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  120070. var focusMeshes = model ? model.meshes : this.scene.meshes;
  120071. var renderList = this.environmentHelper.groundMirror.renderList;
  120072. if (resetList) {
  120073. renderList.length = 0;
  120074. }
  120075. for (var index = 0; index < focusMeshes.length; index++) {
  120076. var mesh = focusMeshes[index];
  120077. if (renderList.indexOf(mesh) === -1) {
  120078. renderList.push(mesh);
  120079. }
  120080. }
  120081. }
  120082. };
  120083. /**
  120084. * Gets the shadow map blur kernel according to the light configuration.
  120085. * @param light The light used to generate the shadows
  120086. * @param bufferSize The size of the shadow map
  120087. * @return the kernel blur size
  120088. */
  120089. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  120090. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  120091. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  120092. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  120093. }
  120094. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  120095. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  120096. }
  120097. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  120098. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  120099. }
  120100. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  120101. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  120102. return blurKernel;
  120103. };
  120104. /**
  120105. * Alters render settings to reduce features based on hardware feature limitations
  120106. * @param enableHDR Allows the viewer to run in HDR mode.
  120107. */
  120108. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  120109. if (enableHDR === void 0) { enableHDR = true; }
  120110. //flip rendering settings switches based on hardware support
  120111. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  120112. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  120113. //shadows are disabled if there's not enough varyings for a single shadow
  120114. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  120115. this._maxShadows = 0;
  120116. }
  120117. else {
  120118. this._maxShadows = 3;
  120119. }
  120120. //can we render to any >= 16-bit targets (required for HDR)
  120121. var caps = this._engine.getCaps();
  120122. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  120123. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  120124. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  120125. if (linearHalfFloatTargets) {
  120126. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  120127. this._shadowGeneratorBias = 0.002;
  120128. }
  120129. else if (linearFloatTargets) {
  120130. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  120131. this._shadowGeneratorBias = 0.001;
  120132. }
  120133. else {
  120134. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  120135. this._shadowGeneratorBias = 0.001;
  120136. }
  120137. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  120138. };
  120139. /**
  120140. * Dispoe the entire viewer including the scene and the engine
  120141. */
  120142. SceneManager.prototype.dispose = function () {
  120143. // this.onCameraConfiguredObservable.clear();
  120144. this.onEnvironmentConfiguredObservable.clear();
  120145. this.onLightsConfiguredObservable.clear();
  120146. this.onModelsConfiguredObservable.clear();
  120147. this.onSceneConfiguredObservable.clear();
  120148. this.onSceneInitObservable.clear();
  120149. this.onSceneOptimizerConfiguredObservable.clear();
  120150. this.onVRConfiguredObservable.clear();
  120151. if (this.sceneOptimizer) {
  120152. this.sceneOptimizer.stop();
  120153. this.sceneOptimizer.dispose();
  120154. }
  120155. if (this.environmentHelper) {
  120156. this.environmentHelper.dispose();
  120157. }
  120158. this.models.forEach(function (model) {
  120159. model.dispose();
  120160. });
  120161. if (this._defaultRenderingPipeline) {
  120162. this._defaultRenderingPipeline.dispose();
  120163. }
  120164. this.models.length = 0;
  120165. if (this.scene) {
  120166. this.scene.dispose();
  120167. }
  120168. };
  120169. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  120170. var behavior;
  120171. var type;
  120172. if (typeof behaviorConfig === 'object') {
  120173. type = behaviorConfig.type;
  120174. }
  120175. else if (typeof behaviorConfig === 'number') {
  120176. type = behaviorConfig;
  120177. }
  120178. else {
  120179. type = this._cameraBehaviorMapping[name];
  120180. }
  120181. if (type === undefined)
  120182. return;
  120183. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  120184. var enabled = true;
  120185. if (typeof behaviorConfig === 'boolean') {
  120186. enabled = behaviorConfig;
  120187. }
  120188. // constructing behavior
  120189. switch (type) {
  120190. case 0 /* AUTOROTATION */:
  120191. this.camera.useAutoRotationBehavior = enabled;
  120192. behavior = this.camera.autoRotationBehavior;
  120193. break;
  120194. case 1 /* BOUNCING */:
  120195. this.camera.useBouncingBehavior = enabled;
  120196. behavior = this.camera.bouncingBehavior;
  120197. break;
  120198. case 2 /* FRAMING */:
  120199. this.camera.useFramingBehavior = enabled;
  120200. behavior = this.camera.framingBehavior;
  120201. break;
  120202. default:
  120203. behavior = null;
  120204. break;
  120205. }
  120206. if (behavior) {
  120207. this._cameraBehaviorMapping[name] = type;
  120208. if (typeof behaviorConfig === "object") {
  120209. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  120210. }
  120211. }
  120212. // post attach configuration. Some functionalities require the attached camera.
  120213. switch (type) {
  120214. case 0 /* AUTOROTATION */:
  120215. break;
  120216. case 1 /* BOUNCING */:
  120217. break;
  120218. case 2 /* FRAMING */:
  120219. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  120220. if (config.zoomOnBoundingInfo) {
  120221. behavior.zoomOnMeshHierarchy(model.rootMesh);
  120222. }
  120223. });
  120224. break;
  120225. }
  120226. };
  120227. return SceneManager;
  120228. }());
  120229. exports.SceneManager = SceneManager;
  120230. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4bUI7QUFDOW1CLGtEQUFxUztBQUNyUyxvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFHaEUsb0NBQXNDO0FBY3RDO0lBa0dJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQTBFQztRQTFFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBeEN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU0sR0FBRyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBRWpDLHVCQUFrQixHQUFZLEtBQUssQ0FBQztRQStIcEMsb0JBQWUsR0FBWSxJQUFJLENBQUM7UUFrQ2hDLG1CQUFjLEdBQVksSUFBSSxDQUFDO1FBZ0IvQix5QkFBb0IsR0FBRyxJQUFJLENBQUM7UUF5QjVCLHFDQUFnQyxHQUFZLEtBQUssQ0FBQzt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QsQ0FBQyxBQTU4Q0QsSUE0OENDO0FBNThDWSxvQ0FBWSJ9
  120231. /***/ }),
  120232. /* 60 */
  120233. /***/ (function(module, exports, __webpack_require__) {
  120234. "use strict";
  120235. Object.defineProperty(exports, "__esModule", { value: true });
  120236. var environmentSerializer_1 = __webpack_require__(61);
  120237. var babylonjs_1 = __webpack_require__(0);
  120238. var texture_1 = __webpack_require__(15);
  120239. /**
  120240. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  120241. * The APIs in all labs-related classes and configuration might change.
  120242. * Once stable, lab features will be moved to the publis API and configuration object.
  120243. */
  120244. var ViewerLabs = /** @class */ (function () {
  120245. function ViewerLabs(_scene) {
  120246. this._scene = _scene;
  120247. this.environment = {
  120248. //irradiance
  120249. irradiancePolynomialCoefficients: {
  120250. x: new babylonjs_1.Vector3(0, 0, 0),
  120251. y: new babylonjs_1.Vector3(0, 0, 0),
  120252. z: new babylonjs_1.Vector3(0, 0, 0),
  120253. xx: new babylonjs_1.Vector3(0, 0, 0),
  120254. yy: new babylonjs_1.Vector3(0, 0, 0),
  120255. zz: new babylonjs_1.Vector3(0, 0, 0),
  120256. yz: new babylonjs_1.Vector3(0, 0, 0),
  120257. zx: new babylonjs_1.Vector3(0, 0, 0),
  120258. xy: new babylonjs_1.Vector3(0, 0, 0)
  120259. },
  120260. textureIntensityScale: 1.0
  120261. };
  120262. }
  120263. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  120264. var _this = this;
  120265. //@! todo: should loadEnvironment cancel any currently loading environments?
  120266. if (data instanceof ArrayBuffer) {
  120267. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  120268. if (onSuccess)
  120269. onSuccess(this.environment);
  120270. }
  120271. else if (typeof data === 'string') {
  120272. var url = this.getAssetUrl(data);
  120273. this._scene._loadFile(url, function (arrayBuffer) {
  120274. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  120275. if (onSuccess)
  120276. onSuccess(_this.environment);
  120277. }, function (progressEvent) { if (onProgress)
  120278. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  120279. if (onError) {
  120280. onError(e);
  120281. }
  120282. });
  120283. }
  120284. else {
  120285. //data assumed to be PBREnvironment object
  120286. this.environment = data;
  120287. if (onSuccess)
  120288. onSuccess(data);
  120289. }
  120290. };
  120291. /**
  120292. * Applies an `EnvironmentMapConfiguration` to the scene
  120293. * @param environmentMapConfiguration Environment map configuration to apply
  120294. */
  120295. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  120296. if (!this.environment)
  120297. return;
  120298. //set orientation
  120299. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  120300. // Add env texture to the scene.
  120301. if (this.environment.specularTexture) {
  120302. // IE crashes when disposing the old texture and setting a new one
  120303. if (!this._scene.environmentTexture) {
  120304. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  120305. }
  120306. if (this._scene.environmentTexture) {
  120307. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  120308. this._scene.environmentTexture.invertZ = true;
  120309. this._scene.environmentTexture.lodLevelInAlpha = true;
  120310. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  120311. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  120312. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  120313. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  120314. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  120315. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  120316. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  120317. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  120318. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  120319. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  120320. this._scene.environmentTexture.sphericalPolynomial = poly;
  120321. //set orientation
  120322. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  120323. }
  120324. }
  120325. };
  120326. /**
  120327. * Get an environment asset url by using the configuration if the path is not absolute.
  120328. * @param url Asset url
  120329. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  120330. */
  120331. ViewerLabs.prototype.getAssetUrl = function (url) {
  120332. var returnUrl = url;
  120333. if (url && url.toLowerCase().indexOf("//") === -1) {
  120334. if (!this.assetsRootURL) {
  120335. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  120336. return url;
  120337. }
  120338. returnUrl = this.assetsRootURL + returnUrl;
  120339. }
  120340. return returnUrl;
  120341. };
  120342. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  120343. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  120344. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  120345. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  120346. axis.normalize();
  120347. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  120348. 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]);
  120349. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  120350. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  120351. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  120352. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  120353. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  120354. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  120355. shadowLight.setDirectionToTarget(target);
  120356. };
  120357. return ViewerLabs;
  120358. }());
  120359. exports.ViewerLabs = ViewerLabs;
  120360. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN4QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN4QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUU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xDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  120361. /***/ }),
  120362. /* 61 */
  120363. /***/ (function(module, exports, __webpack_require__) {
  120364. "use strict";
  120365. Object.defineProperty(exports, "__esModule", { value: true });
  120366. var babylonjs_1 = __webpack_require__(0);
  120367. var texture_1 = __webpack_require__(15);
  120368. /**
  120369. * A static class proving methods to aid parsing Spectre environment files
  120370. */
  120371. var EnvironmentDeserializer = /** @class */ (function () {
  120372. function EnvironmentDeserializer() {
  120373. }
  120374. /**
  120375. * Parses an arraybuffer into a new PBREnvironment object
  120376. * @param arrayBuffer The arraybuffer of the Spectre environment file
  120377. * @return a PBREnvironment object
  120378. */
  120379. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  120380. var environment = {
  120381. //irradiance
  120382. irradiancePolynomialCoefficients: {
  120383. x: new babylonjs_1.Vector3(0, 0, 0),
  120384. y: new babylonjs_1.Vector3(0, 0, 0),
  120385. z: new babylonjs_1.Vector3(0, 0, 0),
  120386. xx: new babylonjs_1.Vector3(0, 0, 0),
  120387. yy: new babylonjs_1.Vector3(0, 0, 0),
  120388. zz: new babylonjs_1.Vector3(0, 0, 0),
  120389. yz: new babylonjs_1.Vector3(0, 0, 0),
  120390. zx: new babylonjs_1.Vector3(0, 0, 0),
  120391. xy: new babylonjs_1.Vector3(0, 0, 0)
  120392. },
  120393. //specular
  120394. textureIntensityScale: 1.0,
  120395. };
  120396. //read .env
  120397. var littleEndian = false;
  120398. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  120399. var dataView = new DataView(arrayBuffer);
  120400. var pos = 0;
  120401. for (var i = 0; i < magicBytes.length; i++) {
  120402. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  120403. babylonjs_1.Tools.Error('Not a Spectre environment map');
  120404. }
  120405. }
  120406. var version = dataView.getUint16(pos, littleEndian);
  120407. pos += 2;
  120408. if (version !== 1) {
  120409. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  120410. }
  120411. //read json descriptor - collect characters up to null terminator
  120412. var descriptorString = '';
  120413. var charCode = 0x00;
  120414. while ((charCode = dataView.getUint8(pos++))) {
  120415. descriptorString += String.fromCharCode(charCode);
  120416. }
  120417. var descriptor = JSON.parse(descriptorString);
  120418. var payloadPos = pos;
  120419. //irradiance
  120420. switch (descriptor.irradiance.type) {
  120421. case 'irradiance_sh_coefficients_9':
  120422. //irradiance
  120423. var harmonics = descriptor.irradiance;
  120424. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  120425. //harmonics now represent radiance
  120426. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  120427. break;
  120428. default:
  120429. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  120430. }
  120431. //specular
  120432. switch (descriptor.specular.type) {
  120433. case 'cubemap_faces':
  120434. var specularDescriptor = descriptor.specular;
  120435. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  120436. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  120437. var mipmaps = specularDescriptor.mipmaps;
  120438. var imageType = specularDescriptor.imageType;
  120439. for (var l = 0; l < mipmaps.length; l++) {
  120440. var faceRanges = mipmaps[l];
  120441. specularTexture.source[l] = [];
  120442. for (var i = 0; i < 6; i++) {
  120443. var range = faceRanges[i];
  120444. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  120445. switch (imageType) {
  120446. case 'png':
  120447. //construct image element from bytes
  120448. var image = new Image();
  120449. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  120450. image.src = src;
  120451. specularTexture.source[l][i] = image;
  120452. break;
  120453. default:
  120454. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  120455. }
  120456. }
  120457. }
  120458. break;
  120459. default:
  120460. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  120461. }
  120462. return environment;
  120463. };
  120464. /**
  120465. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  120466. * L = (1/pi) * E * rho
  120467. *
  120468. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  120469. * @param harmonics Spherical harmonic coefficients (9)
  120470. */
  120471. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  120472. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  120473. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  120474. // (The pixel shader must apply albedo after texture fetches, etc).
  120475. };
  120476. /**
  120477. * Convert spherical harmonics to spherical polynomial coefficients
  120478. * @param harmonics Spherical harmonic coefficients (9)
  120479. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  120480. */
  120481. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  120482. var rPi = 1 / Math.PI;
  120483. //x
  120484. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  120485. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  120486. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  120487. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  120488. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  120489. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  120490. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  120491. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  120492. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  120493. //xx
  120494. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  120495. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  120496. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  120497. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  120498. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  120499. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  120500. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  120501. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  120502. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  120503. //yz
  120504. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  120505. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  120506. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  120507. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  120508. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  120509. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  120510. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  120511. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  120512. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  120513. };
  120514. /**
  120515. * Multiplies harmonic coefficients in place
  120516. * @param harmonics Spherical harmonic coefficients (9)
  120517. * @param scaleFactor Value to multiply by
  120518. */
  120519. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  120520. harmonics.l00[0] *= scaleFactor;
  120521. harmonics.l00[1] *= scaleFactor;
  120522. harmonics.l00[2] *= scaleFactor;
  120523. harmonics.l1_1[0] *= scaleFactor;
  120524. harmonics.l1_1[1] *= scaleFactor;
  120525. harmonics.l1_1[2] *= scaleFactor;
  120526. harmonics.l10[0] *= scaleFactor;
  120527. harmonics.l10[1] *= scaleFactor;
  120528. harmonics.l10[2] *= scaleFactor;
  120529. harmonics.l11[0] *= scaleFactor;
  120530. harmonics.l11[1] *= scaleFactor;
  120531. harmonics.l11[2] *= scaleFactor;
  120532. harmonics.l2_2[0] *= scaleFactor;
  120533. harmonics.l2_2[1] *= scaleFactor;
  120534. harmonics.l2_2[2] *= scaleFactor;
  120535. harmonics.l2_1[0] *= scaleFactor;
  120536. harmonics.l2_1[1] *= scaleFactor;
  120537. harmonics.l2_1[2] *= scaleFactor;
  120538. harmonics.l20[0] *= scaleFactor;
  120539. harmonics.l20[1] *= scaleFactor;
  120540. harmonics.l20[2] *= scaleFactor;
  120541. harmonics.l21[0] *= scaleFactor;
  120542. harmonics.l21[1] *= scaleFactor;
  120543. harmonics.l21[2] *= scaleFactor;
  120544. harmonics.l22[0] *= scaleFactor;
  120545. harmonics.l22[1] *= scaleFactor;
  120546. harmonics.l22[2] *= scaleFactor;
  120547. };
  120548. return EnvironmentDeserializer;
  120549. }());
  120550. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  120551. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLEVBQUUsRUFBRSxJQUFJL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yxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  120552. /***/ }),
  120553. /* 62 */
  120554. /***/ (function(module, exports, __webpack_require__) {
  120555. "use strict";
  120556. Object.defineProperty(exports, "__esModule", { value: true });
  120557. var babylonjs_1 = __webpack_require__(0);
  120558. /**
  120559. * A custom upgrade-oriented function configuration for the scene optimizer.
  120560. *
  120561. * @param viewer the viewer to optimize
  120562. */
  120563. function extendedUpgrade(sceneManager) {
  120564. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  120565. // if (!this.Scene.BackgroundHelper) {
  120566. // this.Scene.EngineScene.autoClear = false;
  120567. // this.Scene.BackgroundHelper = true;
  120568. // Would require a dedicated clear color;
  120569. // return false;
  120570. // }
  120571. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  120572. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  120573. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  120574. return false;
  120575. }
  120576. if (!sceneManager.scene.postProcessesEnabled) {
  120577. sceneManager.scene.postProcessesEnabled = true;
  120578. return false;
  120579. }
  120580. if (!sceneManager.groundEnabled) {
  120581. sceneManager.groundEnabled = true;
  120582. return false;
  120583. }
  120584. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  120585. sceneManager.fxaaEnabled = true;
  120586. return false;
  120587. }
  120588. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  120589. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  120590. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  120591. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  120592. return false;
  120593. }
  120594. if (!sceneManager.processShadows) {
  120595. sceneManager.processShadows = true;
  120596. return false;
  120597. }
  120598. if (defaultPipeline && !sceneManager.bloomEnabled) {
  120599. sceneManager.bloomEnabled = true;
  120600. return false;
  120601. }
  120602. if (!sceneManager.groundMirrorEnabled) {
  120603. sceneManager.groundMirrorEnabled = true;
  120604. return false;
  120605. }
  120606. return true;
  120607. }
  120608. exports.extendedUpgrade = extendedUpgrade;
  120609. /**
  120610. * A custom degrade-oriented function configuration for the scene optimizer.
  120611. *
  120612. * @param viewer the viewer to optimize
  120613. */
  120614. function extendedDegrade(sceneManager) {
  120615. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  120616. if (sceneManager.groundMirrorEnabled) {
  120617. sceneManager.groundMirrorEnabled = false;
  120618. return false;
  120619. }
  120620. if (defaultPipeline && sceneManager.bloomEnabled) {
  120621. sceneManager.bloomEnabled = false;
  120622. return false;
  120623. }
  120624. if (sceneManager.processShadows) {
  120625. sceneManager.processShadows = false;
  120626. return false;
  120627. }
  120628. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  120629. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  120630. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  120631. return false;
  120632. }
  120633. if (defaultPipeline && sceneManager.fxaaEnabled) {
  120634. sceneManager.fxaaEnabled = false;
  120635. return false;
  120636. }
  120637. if (sceneManager.groundEnabled) {
  120638. sceneManager.groundEnabled = false;
  120639. return false;
  120640. }
  120641. if (sceneManager.scene.postProcessesEnabled) {
  120642. sceneManager.scene.postProcessesEnabled = false;
  120643. return false;
  120644. }
  120645. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  120646. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  120647. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  120648. return false;
  120649. }
  120650. // if (this.Scene.BackgroundHelper) {
  120651. // this.Scene.EngineScene.autoClear = true;
  120652. // this.Scene.BackgroundHelper = false;
  120653. // Would require a dedicated clear color;
  120654. // return false;
  120655. // }
  120656. return true;
  120657. }
  120658. exports.extendedDegrade = extendedDegrade;
  120659. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFDdEMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osSUFBSSxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsQ0FBQyxFQUFFO1FBQzlELElBQUksT0FBTyxHQUFHLGtCQUFNLENBQUMsS0FBSyxDQUFDLFlBQVksQ0FBQyxL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0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  120660. /***/ }),
  120661. /* 63 */
  120662. /***/ (function(module, exports, __webpack_require__) {
  120663. "use strict";
  120664. Object.defineProperty(exports, "__esModule", { value: true });
  120665. var babylonjs_1 = __webpack_require__(0);
  120666. var helper_1 = __webpack_require__(1);
  120667. var Handlebars = __webpack_require__(17);
  120668. var eventManager_1 = __webpack_require__(64);
  120669. var _1 = __webpack_require__(1);
  120670. /**
  120671. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  120672. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  120673. */
  120674. var TemplateManager = /** @class */ (function () {
  120675. function TemplateManager(containerElement) {
  120676. this.containerElement = containerElement;
  120677. this.templates = {};
  120678. this.onTemplateInit = new babylonjs_1.Observable();
  120679. this.onTemplateLoaded = new babylonjs_1.Observable();
  120680. this.onTemplateStateChange = new babylonjs_1.Observable();
  120681. this.onAllLoaded = new babylonjs_1.Observable();
  120682. this.onEventTriggered = new babylonjs_1.Observable();
  120683. this.eventManager = new eventManager_1.EventManager(this);
  120684. }
  120685. /**
  120686. * Initialize the template(s) for the viewer. Called bay the Viewer class
  120687. * @param templates the templates to be used to initialize the main template
  120688. */
  120689. TemplateManager.prototype.initTemplate = function (templates) {
  120690. var _this = this;
  120691. var internalInit = function (dependencyMap, name, parentTemplate) {
  120692. //init template
  120693. var template = _this.templates[name];
  120694. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  120695. return internalInit(dependencyMap[childName], childName, template);
  120696. });
  120697. // register the observers
  120698. //template.onLoaded.add(() => {
  120699. var addToParent = function () {
  120700. var lastElements = parentTemplate && parentTemplate.parent.querySelectorAll(helper_1.camelToKebab(name));
  120701. var containingElement = (lastElements && lastElements.length && lastElements.item(lastElements.length - 1)) || _this.containerElement;
  120702. template.appendTo(containingElement);
  120703. _this._checkLoadedState();
  120704. };
  120705. if (parentTemplate && !parentTemplate.parent) {
  120706. parentTemplate.onAppended.add(function () {
  120707. addToParent();
  120708. });
  120709. }
  120710. else {
  120711. addToParent();
  120712. }
  120713. //});
  120714. return template;
  120715. };
  120716. //build the html tree
  120717. return this._buildHTMLTree(templates).then(function (htmlTree) {
  120718. if (_this.templates['main']) {
  120719. internalInit(htmlTree, 'main');
  120720. }
  120721. else {
  120722. _this._checkLoadedState();
  120723. }
  120724. return;
  120725. });
  120726. };
  120727. /**
  120728. *
  120729. * This function will create a simple map with child-dependencies of the template html tree.
  120730. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  120731. * It is expected that the main template will be called main!
  120732. *
  120733. * @param templates
  120734. */
  120735. TemplateManager.prototype._buildHTMLTree = function (templates) {
  120736. var _this = this;
  120737. var promises = Object.keys(templates).map(function (name) {
  120738. // if the template was overridden
  120739. if (!templates[name])
  120740. return Promise.resolve(false);
  120741. // else - we have a template, let's do our job!
  120742. var template = new Template(name, templates[name]);
  120743. template.onLoaded.add(function () {
  120744. _this.onTemplateLoaded.notifyObservers(template);
  120745. });
  120746. template.onStateChange.add(function () {
  120747. _this.onTemplateStateChange.notifyObservers(template);
  120748. });
  120749. _this.onTemplateInit.notifyObservers(template);
  120750. // make sure the global onEventTriggered is called as well
  120751. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  120752. _this.templates[name] = template;
  120753. return template.initPromise;
  120754. });
  120755. return Promise.all(promises).then(function () {
  120756. var templateStructure = {};
  120757. // now iterate through all templates and check for children:
  120758. var buildTree = function (parentObject, name) {
  120759. _this.templates[name].isInHtmlTree = true;
  120760. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  120761. childNodes.forEach(function (element) {
  120762. parentObject[element] = {};
  120763. buildTree(parentObject[element], element);
  120764. });
  120765. };
  120766. if (_this.templates['main']) {
  120767. buildTree(templateStructure, "main");
  120768. }
  120769. return templateStructure;
  120770. });
  120771. };
  120772. /**
  120773. * Get the canvas in the template tree.
  120774. * There must be one and only one canvas inthe template.
  120775. */
  120776. TemplateManager.prototype.getCanvas = function () {
  120777. return this.containerElement.querySelector('canvas');
  120778. };
  120779. /**
  120780. * Get a specific template from the template tree
  120781. * @param name the name of the template to load
  120782. */
  120783. TemplateManager.prototype.getTemplate = function (name) {
  120784. return this.templates[name];
  120785. };
  120786. TemplateManager.prototype._checkLoadedState = function () {
  120787. var _this = this;
  120788. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  120789. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  120790. });
  120791. if (done) {
  120792. this.onAllLoaded.notifyObservers(this);
  120793. }
  120794. };
  120795. /**
  120796. * Dispose the template manager
  120797. */
  120798. TemplateManager.prototype.dispose = function () {
  120799. var _this = this;
  120800. // dispose all templates
  120801. Object.keys(this.templates).forEach(function (template) {
  120802. _this.templates[template].dispose();
  120803. });
  120804. this.templates = {};
  120805. this.eventManager.dispose();
  120806. this.onTemplateInit.clear();
  120807. this.onAllLoaded.clear();
  120808. this.onEventTriggered.clear();
  120809. this.onTemplateLoaded.clear();
  120810. this.onTemplateStateChange.clear();
  120811. };
  120812. return TemplateManager;
  120813. }());
  120814. exports.TemplateManager = TemplateManager;
  120815. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  120816. Handlebars.registerHelper('eachInMap', function (map, block) {
  120817. var out = '';
  120818. Object.keys(map).map(function (prop) {
  120819. var data = map[prop];
  120820. if (typeof data === 'object') {
  120821. data.id = data.id || prop;
  120822. out += block.fn(data);
  120823. }
  120824. else {
  120825. out += block.fn({ id: prop, value: data });
  120826. }
  120827. });
  120828. return out;
  120829. });
  120830. Handlebars.registerHelper('add', function (a, b) {
  120831. var out = a + b;
  120832. return out;
  120833. });
  120834. Handlebars.registerHelper('eq', function (a, b) {
  120835. var out = (a == b);
  120836. return out;
  120837. });
  120838. Handlebars.registerHelper('or', function (a, b) {
  120839. var out = a || b;
  120840. return out;
  120841. });
  120842. Handlebars.registerHelper('not', function (a) {
  120843. var out = !a;
  120844. return out;
  120845. });
  120846. Handlebars.registerHelper('count', function (map) {
  120847. return map.length;
  120848. });
  120849. Handlebars.registerHelper('gt', function (a, b) {
  120850. var out = a > b;
  120851. return out;
  120852. });
  120853. /**
  120854. * This class represents a single template in the viewer's template tree.
  120855. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  120856. * A template is injected using the template manager in the correct position.
  120857. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  120858. *
  120859. * For further information please refer to the documentation page, https://doc.babylonjs.com
  120860. */
  120861. var Template = /** @class */ (function () {
  120862. function Template(name, _configuration) {
  120863. var _this = this;
  120864. this.name = name;
  120865. this._configuration = _configuration;
  120866. this.onLoaded = new babylonjs_1.Observable();
  120867. this.onAppended = new babylonjs_1.Observable();
  120868. this.onStateChange = new babylonjs_1.Observable();
  120869. this.onEventTriggered = new babylonjs_1.Observable();
  120870. this.onParamsUpdated = new babylonjs_1.Observable();
  120871. this.onHTMLRendered = new babylonjs_1.Observable();
  120872. this.loadRequests = [];
  120873. this.isLoaded = false;
  120874. this.isShown = false;
  120875. this.isInHtmlTree = false;
  120876. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  120877. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  120878. if (htmlTemplate) {
  120879. _this._htmlTemplate = htmlTemplate;
  120880. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  120881. var config = _this._configuration.params || {};
  120882. _this._rawHtml = compiledTemplate(config);
  120883. try {
  120884. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  120885. }
  120886. catch (e) {
  120887. var test = document.createElement(_this.name);
  120888. test.innerHTML = _this._rawHtml;
  120889. _this._fragment = test;
  120890. }
  120891. _this.isLoaded = true;
  120892. _this.isShown = true;
  120893. _this.onLoaded.notifyObservers(_this);
  120894. }
  120895. return _this;
  120896. });
  120897. }
  120898. /**
  120899. * Some templates have parameters (like background color for example).
  120900. * The parameters are provided to Handlebars which in turn generates the template.
  120901. * This function will update the template with the new parameters
  120902. *
  120903. * Note that when updating parameters the events will be registered again (after being cleared).
  120904. *
  120905. * @param params the new template parameters
  120906. */
  120907. Template.prototype.updateParams = function (params, append) {
  120908. if (append === void 0) { append = true; }
  120909. if (append) {
  120910. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  120911. }
  120912. else {
  120913. this._configuration.params = params;
  120914. }
  120915. // update the template
  120916. if (this.isLoaded) {
  120917. // this.dispose();
  120918. }
  120919. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  120920. var config = this._configuration.params || {};
  120921. this._rawHtml = compiledTemplate(config);
  120922. try {
  120923. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  120924. }
  120925. catch (e) {
  120926. var test = document.createElement(this.name);
  120927. test.innerHTML = this._rawHtml;
  120928. this._fragment = test;
  120929. }
  120930. if (this.parent) {
  120931. this.appendTo(this.parent, true);
  120932. }
  120933. };
  120934. Template.prototype.redraw = function () {
  120935. this.updateParams({});
  120936. };
  120937. Object.defineProperty(Template.prototype, "configuration", {
  120938. /**
  120939. * Get the template'S configuration
  120940. */
  120941. get: function () {
  120942. return this._configuration;
  120943. },
  120944. enumerable: true,
  120945. configurable: true
  120946. });
  120947. /**
  120948. * A template can be a parent element for other templates or HTML elements.
  120949. * This function will deliver all child HTML elements of this template.
  120950. */
  120951. Template.prototype.getChildElements = function () {
  120952. var childrenArray = [];
  120953. //Edge and IE don't support frage,ent.children
  120954. var children = this._fragment && this._fragment.children;
  120955. if (!this._fragment) {
  120956. var fragment = this.parent.querySelector(this.name);
  120957. if (fragment) {
  120958. children = fragment.querySelectorAll('*');
  120959. }
  120960. }
  120961. if (!children) {
  120962. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  120963. children = this._fragment.querySelectorAll('*');
  120964. }
  120965. for (var i = 0; i < children.length; ++i) {
  120966. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  120967. }
  120968. return childrenArray;
  120969. };
  120970. /**
  120971. * Appending the template to a parent HTML element.
  120972. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  120973. * @param parent the parent to which the template is added
  120974. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  120975. */
  120976. Template.prototype.appendTo = function (parent, forceRemove) {
  120977. var _this = this;
  120978. if (this.parent) {
  120979. if (forceRemove && this._addedFragment) {
  120980. /*let fragement = this.parent.querySelector(this.name)
  120981. if (fragement)
  120982. this.parent.removeChild(fragement);*/
  120983. this.parent.innerHTML = '';
  120984. }
  120985. else {
  120986. return;
  120987. }
  120988. }
  120989. this.parent = parent;
  120990. if (this._configuration.id) {
  120991. this.parent.id = this._configuration.id;
  120992. }
  120993. if (this._fragment) {
  120994. this.parent.appendChild(this._fragment);
  120995. this._addedFragment = this._fragment;
  120996. }
  120997. else {
  120998. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  120999. }
  121000. this.onHTMLRendered.notifyObservers(this);
  121001. // appended only one frame after.
  121002. setTimeout(function () {
  121003. _this._registerEvents();
  121004. _this.onAppended.notifyObservers(_this);
  121005. });
  121006. };
  121007. /**
  121008. * Show the template using the provided visibilityFunction, or natively using display: flex.
  121009. * The provided function returns a promise that should be fullfilled when the element is shown.
  121010. * Since it is a promise async operations are more than possible.
  121011. * See the default viewer for an opacity example.
  121012. * @param visibilityFunction The function to execute to show the template.
  121013. */
  121014. Template.prototype.show = function (visibilityFunction) {
  121015. var _this = this;
  121016. if (this._isHiding)
  121017. return Promise.resolve(this);
  121018. return Promise.resolve().then(function () {
  121019. _this._isShowing = true;
  121020. if (visibilityFunction) {
  121021. return visibilityFunction(_this);
  121022. }
  121023. else {
  121024. // flex? box? should this be configurable easier than the visibilityFunction?
  121025. _this.parent.style.display = 'flex';
  121026. // support old browsers with no flex:
  121027. if (_this.parent.style.display !== 'flex') {
  121028. _this.parent.style.display = '';
  121029. }
  121030. return _this;
  121031. }
  121032. }).then(function () {
  121033. _this.isShown = true;
  121034. _this._isShowing = false;
  121035. _this.onStateChange.notifyObservers(_this);
  121036. return _this;
  121037. });
  121038. };
  121039. /**
  121040. * Hide the template using the provided visibilityFunction, or natively using display: none.
  121041. * The provided function returns a promise that should be fullfilled when the element is hidden.
  121042. * Since it is a promise async operations are more than possible.
  121043. * See the default viewer for an opacity example.
  121044. * @param visibilityFunction The function to execute to show the template.
  121045. */
  121046. Template.prototype.hide = function (visibilityFunction) {
  121047. var _this = this;
  121048. if (this._isShowing)
  121049. return Promise.resolve(this);
  121050. return Promise.resolve().then(function () {
  121051. _this._isHiding = true;
  121052. if (visibilityFunction) {
  121053. return visibilityFunction(_this);
  121054. }
  121055. else {
  121056. // flex? box? should this be configurable easier than the visibilityFunction?
  121057. _this.parent.style.display = 'none';
  121058. return _this;
  121059. }
  121060. }).then(function () {
  121061. _this.isShown = false;
  121062. _this._isHiding = false;
  121063. _this.onStateChange.notifyObservers(_this);
  121064. return _this;
  121065. });
  121066. };
  121067. /**
  121068. * Dispose this template
  121069. */
  121070. Template.prototype.dispose = function () {
  121071. this.onAppended.clear();
  121072. this.onEventTriggered.clear();
  121073. this.onLoaded.clear();
  121074. this.onStateChange.clear();
  121075. this.isLoaded = false;
  121076. // remove from parent
  121077. try {
  121078. this.parent.removeChild(this._fragment);
  121079. }
  121080. catch (e) {
  121081. //noop
  121082. }
  121083. this.loadRequests.forEach(function (request) {
  121084. request.abort();
  121085. });
  121086. if (this._registeredEvents) {
  121087. this._registeredEvents.forEach(function (evt) {
  121088. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  121089. });
  121090. }
  121091. delete this._fragment;
  121092. };
  121093. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  121094. var _this = this;
  121095. if (!templateConfig) {
  121096. return Promise.reject('No templateConfig provided');
  121097. }
  121098. else if (templateConfig.html && !templateConfig.location) {
  121099. return Promise.resolve(templateConfig.html);
  121100. }
  121101. else {
  121102. var location_1 = this._getTemplateLocation(templateConfig);
  121103. if (helper_1.isUrl(location_1)) {
  121104. return new Promise(function (resolve, reject) {
  121105. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  121106. resolve(data);
  121107. }, undefined, undefined, false, function (request, error) {
  121108. reject(error);
  121109. });
  121110. _this.loadRequests.push(fileRequest);
  121111. });
  121112. }
  121113. else {
  121114. location_1 = location_1.replace('#', '');
  121115. var element = document.getElementById(location_1);
  121116. if (element) {
  121117. return Promise.resolve(element.innerHTML);
  121118. }
  121119. else {
  121120. return Promise.reject('Template ID not found');
  121121. }
  121122. }
  121123. }
  121124. };
  121125. Template.prototype._registerEvents = function () {
  121126. var _this = this;
  121127. this._registeredEvents = this._registeredEvents || [];
  121128. if (this._registeredEvents.length) {
  121129. // first remove the registered events
  121130. this._registeredEvents.forEach(function (evt) {
  121131. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  121132. });
  121133. }
  121134. if (this._configuration.events) {
  121135. var _loop_1 = function (eventName) {
  121136. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  121137. var functionToFire_1 = function (selector, event) {
  121138. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  121139. };
  121140. // if boolean, set the parent as the event listener
  121141. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  121142. var selector = this_1.parent.id;
  121143. if (selector) {
  121144. selector = '#' + selector;
  121145. }
  121146. else {
  121147. selector = this_1.parent.tagName;
  121148. }
  121149. var binding = functionToFire_1.bind(this_1, selector);
  121150. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  121151. this_1._registeredEvents.push({
  121152. htmlElement: this_1.parent,
  121153. eventName: eventName,
  121154. function: binding
  121155. });
  121156. }
  121157. else if (typeof this_1._configuration.events[eventName] === 'object') {
  121158. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  121159. // strict null checl is working incorrectly, must override:
  121160. var event_1 = this_1._configuration.events[eventName] || {};
  121161. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  121162. var htmlElement = _this.parent.querySelector(selector);
  121163. if (!htmlElement) {
  121164. // backcompat, fallback to id
  121165. if (selector && selector.indexOf('#') !== 0) {
  121166. selector = '#' + selector;
  121167. }
  121168. try {
  121169. htmlElement = _this.parent.querySelector(selector);
  121170. }
  121171. catch (e) { }
  121172. }
  121173. if (htmlElement) {
  121174. var binding = functionToFire_1.bind(_this, selector);
  121175. htmlElement.addEventListener(eventName, binding, false);
  121176. _this._registeredEvents.push({
  121177. htmlElement: htmlElement,
  121178. eventName: eventName,
  121179. function: binding
  121180. });
  121181. }
  121182. });
  121183. }
  121184. }
  121185. };
  121186. var this_1 = this;
  121187. for (var eventName in this._configuration.events) {
  121188. _loop_1(eventName);
  121189. }
  121190. }
  121191. };
  121192. Template.prototype._getTemplateLocation = function (templateConfig) {
  121193. if (!templateConfig || typeof templateConfig === 'string') {
  121194. return templateConfig;
  121195. }
  121196. else {
  121197. return templateConfig.location;
  121198. }
  121199. };
  121200. return Template;
  121201. }());
  121202. exports.Template = Template;
  121203. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9v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xTQUFTLElBQUksSUFBSSxDQUFDLGNBQWMsQ0FBQyxNQUFNO3dCQUF2QyxTQUFTO2FBZ0RqQjtTQUNKO0lBQ0wsQ0FBQztJQUVPLHVDQUFvQixHQUE1QixVQUE2QixjQUFjO1FBQ3ZDLElBQUksQ0FBQyxjQUFjLElBQUksT0FBTyxjQUFjLEtBQUssUUFBUSxFQUFFO1lBQ3ZELE9BQU8sY0FBYyxDQUFDO1NBQ3pCO2FBQU07WUFDSCxPQUFPLGNBQWMsQ0FBQyxRQUFRLENBQUM7U0FDbEM7SUFDTCxDQUFDO0lBQ0wsZUFBQztBQUFELENBQUMsQUFsWUQsSUFrWUM7QUFsWVksNEJBQVEifQ==
  121204. /***/ }),
  121205. /* 64 */
  121206. /***/ (function(module, exports, __webpack_require__) {
  121207. "use strict";
  121208. Object.defineProperty(exports, "__esModule", { value: true });
  121209. /**
  121210. * The EventManager is in charge of registering user interctions with the viewer.
  121211. * It is used in the TemplateManager
  121212. */
  121213. var EventManager = /** @class */ (function () {
  121214. function EventManager(_templateManager) {
  121215. var _this = this;
  121216. this._templateManager = _templateManager;
  121217. this._callbacksContainer = {};
  121218. this._templateManager.onEventTriggered.add(function (eventData) {
  121219. _this._eventTriggered(eventData);
  121220. });
  121221. }
  121222. /**
  121223. * Register a new callback to a specific template.
  121224. * The best example for the usage can be found in the DefaultViewer
  121225. *
  121226. * @param templateName the templateName to register the event to
  121227. * @param callback The callback to be executed
  121228. * @param eventType the type of event to register
  121229. * @param selector an optional selector. if not defined the parent object in the template will be selected
  121230. */
  121231. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  121232. if (!this._callbacksContainer[templateName]) {
  121233. this._callbacksContainer[templateName] = [];
  121234. }
  121235. this._callbacksContainer[templateName].push({
  121236. eventType: eventType,
  121237. callback: callback,
  121238. selector: selector
  121239. });
  121240. };
  121241. /**
  121242. * This will remove a registered event from the defined template.
  121243. * Each one of the variables apart from the template name are optional, but one must be provided.
  121244. *
  121245. * @param templateName the templateName
  121246. * @param callback the callback to remove (optional)
  121247. * @param eventType the event type to remove (optional)
  121248. * @param selector the selector from which to remove the event (optional)
  121249. */
  121250. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  121251. var callbackDefs = this._callbacksContainer[templateName] || [];
  121252. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  121253. };
  121254. EventManager.prototype._eventTriggered = function (data) {
  121255. var templateName = data.template.name;
  121256. var eventType = data.event.type;
  121257. var selector = data.selector;
  121258. var callbackDefs = this._callbacksContainer[templateName] || [];
  121259. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  121260. callbackDef.callback(data);
  121261. });
  121262. };
  121263. /**
  121264. * Dispose the event manager
  121265. */
  121266. EventManager.prototype.dispose = function () {
  121267. this._callbacksContainer = {};
  121268. };
  121269. return EventManager;
  121270. }());
  121271. exports.EventManager = EventManager;
  121272. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLFVBQUEsU0FBUztZQUNoRCxLQUFJLENBQU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d0IsSUFBbUI7UUFDdkMsSUFBSSxZQUFZLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUM7UUFDdEMsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUM7UUFDaEMsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  121273. /***/ }),
  121274. /* 65 */
  121275. /***/ (function(module, exports, __webpack_require__) {
  121276. "use strict";
  121277. var __extends = (this && this.__extends) || (function () {
  121278. var extendStatics = Object.setPrototypeOf ||
  121279. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  121280. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  121281. return function (d, b) {
  121282. extendStatics(d, b);
  121283. function __() { this.constructor = d; }
  121284. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  121285. };
  121286. })();
  121287. Object.defineProperty(exports, "__esModule", { value: true });
  121288. var viewerTemplatePlugin_1 = __webpack_require__(18);
  121289. var HDButtonPlugin = /** @class */ (function (_super) {
  121290. __extends(HDButtonPlugin, _super);
  121291. function HDButtonPlugin(_viewer) {
  121292. var _this = _super.call(this, "hd", "hd-button", HDButtonPlugin.HtmlTemplate) || this;
  121293. _this._viewer = _viewer;
  121294. return _this;
  121295. }
  121296. HDButtonPlugin.prototype.onEvent = function (event) {
  121297. var button = event.template.parent.querySelector(".hd-button");
  121298. if (button) {
  121299. button.classList.contains("hd-toggled") ? button.classList.remove("hd-toggled") : button.classList.add("hd-toggled");
  121300. }
  121301. this._viewer.toggleHD();
  121302. };
  121303. HDButtonPlugin.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";
  121304. return HDButtonPlugin;
  121305. }(viewerTemplatePlugin_1.AbstractViewerNavbarButton));
  121306. exports.HDButtonPlugin = HDButtonPlugin;
  121307. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGRCdXR0b25QbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy9wbHVnaW5zL2hkQnV0dG9uUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7OztBQUFBLGdFQUFxRTtBQUlyRTtJQUFvQyxrQ0FBMEI7SUFFMUQsd0JBQW9CLE9BQXNCO1FBQTFDLFlBQ0ksa0JBQU0sSUFBSSxFQUFFLFdBQVcsRUFBRSxjQUFjLENBQUMsWUFBWSxDQUFDLFNBQ3hEO1FBRm1CLGFBQU8sR0FBUCxPQUFPLENBQWU7O0lBRTFDLENBQUM7SUFFRCxnQ0FBTyxHQUFQLFVBQVEsS0FBb0I7UUFDeEIsSUFBSSxNQUFNLEdBQUcsS0FBSyxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLFlBQVksQ0FBQyxDQUFDO1FBQy9ELElBQUksTUFBTSxFQUFFO1lBQ1IsTUFBTSxDQUFDLFNBQVMsQ0FBQyxRQUFRLENBQUMsWUFBWSxDQUFDLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxTQUFTLENBQUMsTUFBTSxDQUFDLFlBQVksQ0FBQyxDQUFDLENBQUMsQ0FBQyxNQUFNLENBQUMsU0FBUyxDQUFDLEdBQUcsQ0FBQyxZQUFZLENBQUMsQ0FBQztTQUN4SDtRQUNELElBQUksQ0FBQyxPQUFPLENBQUMsUUFBUSxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVnQiwyQkFBWSxHQUFXLGdUQWdCM0MsQ0FBQztJQUNGLHFCQUFDO0NBQUEsQUEvQkQsQ0FBb0MsaURBQTBCLEdBK0I3RDtBQS9CWSx3Q0FBYyJ9
  121308. /***/ }),
  121309. /* 66 */
  121310. /***/ (function(module, exports, __webpack_require__) {
  121311. /*!
  121312. * PEP v0.4.3 | https://github.com/jquery/PEP
  121313. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  121314. */
  121315. (function (global, factory) {
  121316. true ? module.exports = factory() :
  121317. typeof define === 'function' && define.amd ? define(factory) :
  121318. (global.PointerEventsPolyfill = factory());
  121319. }(this, function () { 'use strict';
  121320. /**
  121321. * This is the constructor for new PointerEvents.
  121322. *
  121323. * New Pointer Events must be given a type, and an optional dictionary of
  121324. * initialization properties.
  121325. *
  121326. * Due to certain platform requirements, events returned from the constructor
  121327. * identify as MouseEvents.
  121328. *
  121329. * @constructor
  121330. * @param {String} inType The type of the event to create.
  121331. * @param {Object} [inDict] An optional dictionary of initial event properties.
  121332. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  121333. */
  121334. var MOUSE_PROPS = [
  121335. 'bubbles',
  121336. 'cancelable',
  121337. 'view',
  121338. 'detail',
  121339. 'screenX',
  121340. 'screenY',
  121341. 'clientX',
  121342. 'clientY',
  121343. 'ctrlKey',
  121344. 'altKey',
  121345. 'shiftKey',
  121346. 'metaKey',
  121347. 'button',
  121348. 'relatedTarget',
  121349. 'pageX',
  121350. 'pageY'
  121351. ];
  121352. var MOUSE_DEFAULTS = [
  121353. false,
  121354. false,
  121355. null,
  121356. null,
  121357. 0,
  121358. 0,
  121359. 0,
  121360. 0,
  121361. false,
  121362. false,
  121363. false,
  121364. false,
  121365. 0,
  121366. null,
  121367. 0,
  121368. 0
  121369. ];
  121370. function PointerEvent(inType, inDict) {
  121371. inDict = inDict || Object.create(null);
  121372. var e = document.createEvent('Event');
  121373. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  121374. // define inherited MouseEvent properties
  121375. // skip bubbles and cancelable since they're set above in initEvent()
  121376. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  121377. p = MOUSE_PROPS[i];
  121378. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  121379. }
  121380. e.buttons = inDict.buttons || 0;
  121381. // Spec requires that pointers without pressure specified use 0.5 for down
  121382. // state and 0 for up state.
  121383. var pressure = 0;
  121384. if (inDict.pressure && e.buttons) {
  121385. pressure = inDict.pressure;
  121386. } else {
  121387. pressure = e.buttons ? 0.5 : 0;
  121388. }
  121389. // add x/y properties aliased to clientX/Y
  121390. e.x = e.clientX;
  121391. e.y = e.clientY;
  121392. // define the properties of the PointerEvent interface
  121393. e.pointerId = inDict.pointerId || 0;
  121394. e.width = inDict.width || 0;
  121395. e.height = inDict.height || 0;
  121396. e.pressure = pressure;
  121397. e.tiltX = inDict.tiltX || 0;
  121398. e.tiltY = inDict.tiltY || 0;
  121399. e.twist = inDict.twist || 0;
  121400. e.tangentialPressure = inDict.tangentialPressure || 0;
  121401. e.pointerType = inDict.pointerType || '';
  121402. e.hwTimestamp = inDict.hwTimestamp || 0;
  121403. e.isPrimary = inDict.isPrimary || false;
  121404. return e;
  121405. }
  121406. /**
  121407. * This module implements a map of pointer states
  121408. */
  121409. var USE_MAP = window.Map && window.Map.prototype.forEach;
  121410. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  121411. function SparseArrayMap() {
  121412. this.array = [];
  121413. this.size = 0;
  121414. }
  121415. SparseArrayMap.prototype = {
  121416. set: function(k, v) {
  121417. if (v === undefined) {
  121418. return this.delete(k);
  121419. }
  121420. if (!this.has(k)) {
  121421. this.size++;
  121422. }
  121423. this.array[k] = v;
  121424. },
  121425. has: function(k) {
  121426. return this.array[k] !== undefined;
  121427. },
  121428. delete: function(k) {
  121429. if (this.has(k)) {
  121430. delete this.array[k];
  121431. this.size--;
  121432. }
  121433. },
  121434. get: function(k) {
  121435. return this.array[k];
  121436. },
  121437. clear: function() {
  121438. this.array.length = 0;
  121439. this.size = 0;
  121440. },
  121441. // return value, key, map
  121442. forEach: function(callback, thisArg) {
  121443. return this.array.forEach(function(v, k) {
  121444. callback.call(thisArg, v, k, this);
  121445. }, this);
  121446. }
  121447. };
  121448. var CLONE_PROPS = [
  121449. // MouseEvent
  121450. 'bubbles',
  121451. 'cancelable',
  121452. 'view',
  121453. 'detail',
  121454. 'screenX',
  121455. 'screenY',
  121456. 'clientX',
  121457. 'clientY',
  121458. 'ctrlKey',
  121459. 'altKey',
  121460. 'shiftKey',
  121461. 'metaKey',
  121462. 'button',
  121463. 'relatedTarget',
  121464. // DOM Level 3
  121465. 'buttons',
  121466. // PointerEvent
  121467. 'pointerId',
  121468. 'width',
  121469. 'height',
  121470. 'pressure',
  121471. 'tiltX',
  121472. 'tiltY',
  121473. 'pointerType',
  121474. 'hwTimestamp',
  121475. 'isPrimary',
  121476. // event instance
  121477. 'type',
  121478. 'target',
  121479. 'currentTarget',
  121480. 'which',
  121481. 'pageX',
  121482. 'pageY',
  121483. 'timeStamp'
  121484. ];
  121485. var CLONE_DEFAULTS = [
  121486. // MouseEvent
  121487. false,
  121488. false,
  121489. null,
  121490. null,
  121491. 0,
  121492. 0,
  121493. 0,
  121494. 0,
  121495. false,
  121496. false,
  121497. false,
  121498. false,
  121499. 0,
  121500. null,
  121501. // DOM Level 3
  121502. 0,
  121503. // PointerEvent
  121504. 0,
  121505. 0,
  121506. 0,
  121507. 0,
  121508. 0,
  121509. 0,
  121510. '',
  121511. 0,
  121512. false,
  121513. // event instance
  121514. '',
  121515. null,
  121516. null,
  121517. 0,
  121518. 0,
  121519. 0,
  121520. 0
  121521. ];
  121522. var BOUNDARY_EVENTS = {
  121523. 'pointerover': 1,
  121524. 'pointerout': 1,
  121525. 'pointerenter': 1,
  121526. 'pointerleave': 1
  121527. };
  121528. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  121529. /**
  121530. * This module is for normalizing events. Mouse and Touch events will be
  121531. * collected here, and fire PointerEvents that have the same semantics, no
  121532. * matter the source.
  121533. * Events fired:
  121534. * - pointerdown: a pointing is added
  121535. * - pointerup: a pointer is removed
  121536. * - pointermove: a pointer is moved
  121537. * - pointerover: a pointer crosses into an element
  121538. * - pointerout: a pointer leaves an element
  121539. * - pointercancel: a pointer will no longer generate events
  121540. */
  121541. var dispatcher = {
  121542. pointermap: new PointerMap(),
  121543. eventMap: Object.create(null),
  121544. captureInfo: Object.create(null),
  121545. // Scope objects for native events.
  121546. // This exists for ease of testing.
  121547. eventSources: Object.create(null),
  121548. eventSourceList: [],
  121549. /**
  121550. * Add a new event source that will generate pointer events.
  121551. *
  121552. * `inSource` must contain an array of event names named `events`, and
  121553. * functions with the names specified in the `events` array.
  121554. * @param {string} name A name for the event source
  121555. * @param {Object} source A new source of platform events.
  121556. */
  121557. registerSource: function(name, source) {
  121558. var s = source;
  121559. var newEvents = s.events;
  121560. if (newEvents) {
  121561. newEvents.forEach(function(e) {
  121562. if (s[e]) {
  121563. this.eventMap[e] = s[e].bind(s);
  121564. }
  121565. }, this);
  121566. this.eventSources[name] = s;
  121567. this.eventSourceList.push(s);
  121568. }
  121569. },
  121570. register: function(element) {
  121571. var l = this.eventSourceList.length;
  121572. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  121573. // call eventsource register
  121574. es.register.call(es, element);
  121575. }
  121576. },
  121577. unregister: function(element) {
  121578. var l = this.eventSourceList.length;
  121579. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  121580. // call eventsource register
  121581. es.unregister.call(es, element);
  121582. }
  121583. },
  121584. contains: /*scope.external.contains || */function(container, contained) {
  121585. try {
  121586. return container.contains(contained);
  121587. } catch (ex) {
  121588. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  121589. return false;
  121590. }
  121591. },
  121592. // EVENTS
  121593. down: function(inEvent) {
  121594. inEvent.bubbles = true;
  121595. this.fireEvent('pointerdown', inEvent);
  121596. },
  121597. move: function(inEvent) {
  121598. inEvent.bubbles = true;
  121599. this.fireEvent('pointermove', inEvent);
  121600. },
  121601. up: function(inEvent) {
  121602. inEvent.bubbles = true;
  121603. this.fireEvent('pointerup', inEvent);
  121604. },
  121605. enter: function(inEvent) {
  121606. inEvent.bubbles = false;
  121607. this.fireEvent('pointerenter', inEvent);
  121608. },
  121609. leave: function(inEvent) {
  121610. inEvent.bubbles = false;
  121611. this.fireEvent('pointerleave', inEvent);
  121612. },
  121613. over: function(inEvent) {
  121614. inEvent.bubbles = true;
  121615. this.fireEvent('pointerover', inEvent);
  121616. },
  121617. out: function(inEvent) {
  121618. inEvent.bubbles = true;
  121619. this.fireEvent('pointerout', inEvent);
  121620. },
  121621. cancel: function(inEvent) {
  121622. inEvent.bubbles = true;
  121623. this.fireEvent('pointercancel', inEvent);
  121624. },
  121625. leaveOut: function(event) {
  121626. this.out(event);
  121627. this.propagate(event, this.leave, false);
  121628. },
  121629. enterOver: function(event) {
  121630. this.over(event);
  121631. this.propagate(event, this.enter, true);
  121632. },
  121633. // LISTENER LOGIC
  121634. eventHandler: function(inEvent) {
  121635. // This is used to prevent multiple dispatch of pointerevents from
  121636. // platform events. This can happen when two elements in different scopes
  121637. // are set up to create pointer events, which is relevant to Shadow DOM.
  121638. if (inEvent._handledByPE) {
  121639. return;
  121640. }
  121641. var type = inEvent.type;
  121642. var fn = this.eventMap && this.eventMap[type];
  121643. if (fn) {
  121644. fn(inEvent);
  121645. }
  121646. inEvent._handledByPE = true;
  121647. },
  121648. // set up event listeners
  121649. listen: function(target, events) {
  121650. events.forEach(function(e) {
  121651. this.addEvent(target, e);
  121652. }, this);
  121653. },
  121654. // remove event listeners
  121655. unlisten: function(target, events) {
  121656. events.forEach(function(e) {
  121657. this.removeEvent(target, e);
  121658. }, this);
  121659. },
  121660. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  121661. target.addEventListener(eventName, this.boundHandler);
  121662. },
  121663. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  121664. target.removeEventListener(eventName, this.boundHandler);
  121665. },
  121666. // EVENT CREATION AND TRACKING
  121667. /**
  121668. * Creates a new Event of type `inType`, based on the information in
  121669. * `inEvent`.
  121670. *
  121671. * @param {string} inType A string representing the type of event to create
  121672. * @param {Event} inEvent A platform event with a target
  121673. * @return {Event} A PointerEvent of type `inType`
  121674. */
  121675. makeEvent: function(inType, inEvent) {
  121676. // relatedTarget must be null if pointer is captured
  121677. if (this.captureInfo[inEvent.pointerId]) {
  121678. inEvent.relatedTarget = null;
  121679. }
  121680. var e = new PointerEvent(inType, inEvent);
  121681. if (inEvent.preventDefault) {
  121682. e.preventDefault = inEvent.preventDefault;
  121683. }
  121684. e._target = e._target || inEvent.target;
  121685. return e;
  121686. },
  121687. // make and dispatch an event in one call
  121688. fireEvent: function(inType, inEvent) {
  121689. var e = this.makeEvent(inType, inEvent);
  121690. return this.dispatchEvent(e);
  121691. },
  121692. /**
  121693. * Returns a snapshot of inEvent, with writable properties.
  121694. *
  121695. * @param {Event} inEvent An event that contains properties to copy.
  121696. * @return {Object} An object containing shallow copies of `inEvent`'s
  121697. * properties.
  121698. */
  121699. cloneEvent: function(inEvent) {
  121700. var eventCopy = Object.create(null);
  121701. var p;
  121702. for (var i = 0; i < CLONE_PROPS.length; i++) {
  121703. p = CLONE_PROPS[i];
  121704. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  121705. // Work around SVGInstanceElement shadow tree
  121706. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  121707. // This is the behavior implemented by Firefox.
  121708. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  121709. if (eventCopy[p] instanceof SVGElementInstance) {
  121710. eventCopy[p] = eventCopy[p].correspondingUseElement;
  121711. }
  121712. }
  121713. }
  121714. // keep the semantics of preventDefault
  121715. if (inEvent.preventDefault) {
  121716. eventCopy.preventDefault = function() {
  121717. inEvent.preventDefault();
  121718. };
  121719. }
  121720. return eventCopy;
  121721. },
  121722. getTarget: function(inEvent) {
  121723. var capture = this.captureInfo[inEvent.pointerId];
  121724. if (!capture) {
  121725. return inEvent._target;
  121726. }
  121727. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  121728. return capture;
  121729. }
  121730. },
  121731. propagate: function(event, fn, propagateDown) {
  121732. var target = event.target;
  121733. var targets = [];
  121734. // Order of conditions due to document.contains() missing in IE.
  121735. while (target !== document && !target.contains(event.relatedTarget)) {
  121736. targets.push(target);
  121737. target = target.parentNode;
  121738. // Touch: Do not propagate if node is detached.
  121739. if (!target) {
  121740. return;
  121741. }
  121742. }
  121743. if (propagateDown) {
  121744. targets.reverse();
  121745. }
  121746. targets.forEach(function(target) {
  121747. event.target = target;
  121748. fn.call(this, event);
  121749. }, this);
  121750. },
  121751. setCapture: function(inPointerId, inTarget, skipDispatch) {
  121752. if (this.captureInfo[inPointerId]) {
  121753. this.releaseCapture(inPointerId, skipDispatch);
  121754. }
  121755. this.captureInfo[inPointerId] = inTarget;
  121756. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  121757. document.addEventListener('pointerup', this.implicitRelease);
  121758. document.addEventListener('pointercancel', this.implicitRelease);
  121759. var e = new PointerEvent('gotpointercapture');
  121760. e.pointerId = inPointerId;
  121761. e._target = inTarget;
  121762. if (!skipDispatch) {
  121763. this.asyncDispatchEvent(e);
  121764. }
  121765. },
  121766. releaseCapture: function(inPointerId, skipDispatch) {
  121767. var t = this.captureInfo[inPointerId];
  121768. if (!t) {
  121769. return;
  121770. }
  121771. this.captureInfo[inPointerId] = undefined;
  121772. document.removeEventListener('pointerup', this.implicitRelease);
  121773. document.removeEventListener('pointercancel', this.implicitRelease);
  121774. var e = new PointerEvent('lostpointercapture');
  121775. e.pointerId = inPointerId;
  121776. e._target = t;
  121777. if (!skipDispatch) {
  121778. this.asyncDispatchEvent(e);
  121779. }
  121780. },
  121781. /**
  121782. * Dispatches the event to its target.
  121783. *
  121784. * @param {Event} inEvent The event to be dispatched.
  121785. * @return {Boolean} True if an event handler returns true, false otherwise.
  121786. */
  121787. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  121788. var t = this.getTarget(inEvent);
  121789. if (t) {
  121790. return t.dispatchEvent(inEvent);
  121791. }
  121792. },
  121793. asyncDispatchEvent: function(inEvent) {
  121794. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  121795. }
  121796. };
  121797. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  121798. var targeting = {
  121799. shadow: function(inEl) {
  121800. if (inEl) {
  121801. return inEl.shadowRoot || inEl.webkitShadowRoot;
  121802. }
  121803. },
  121804. canTarget: function(shadow) {
  121805. return shadow && Boolean(shadow.elementFromPoint);
  121806. },
  121807. targetingShadow: function(inEl) {
  121808. var s = this.shadow(inEl);
  121809. if (this.canTarget(s)) {
  121810. return s;
  121811. }
  121812. },
  121813. olderShadow: function(shadow) {
  121814. var os = shadow.olderShadowRoot;
  121815. if (!os) {
  121816. var se = shadow.querySelector('shadow');
  121817. if (se) {
  121818. os = se.olderShadowRoot;
  121819. }
  121820. }
  121821. return os;
  121822. },
  121823. allShadows: function(element) {
  121824. var shadows = [];
  121825. var s = this.shadow(element);
  121826. while (s) {
  121827. shadows.push(s);
  121828. s = this.olderShadow(s);
  121829. }
  121830. return shadows;
  121831. },
  121832. searchRoot: function(inRoot, x, y) {
  121833. if (inRoot) {
  121834. var t = inRoot.elementFromPoint(x, y);
  121835. var st, sr;
  121836. // is element a shadow host?
  121837. sr = this.targetingShadow(t);
  121838. while (sr) {
  121839. // find the the element inside the shadow root
  121840. st = sr.elementFromPoint(x, y);
  121841. if (!st) {
  121842. // check for older shadows
  121843. sr = this.olderShadow(sr);
  121844. } else {
  121845. // shadowed element may contain a shadow root
  121846. var ssr = this.targetingShadow(st);
  121847. return this.searchRoot(ssr, x, y) || st;
  121848. }
  121849. }
  121850. // light dom element is the target
  121851. return t;
  121852. }
  121853. },
  121854. owner: function(element) {
  121855. var s = element;
  121856. // walk up until you hit the shadow root or document
  121857. while (s.parentNode) {
  121858. s = s.parentNode;
  121859. }
  121860. // the owner element is expected to be a Document or ShadowRoot
  121861. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  121862. s = document;
  121863. }
  121864. return s;
  121865. },
  121866. findTarget: function(inEvent) {
  121867. var x = inEvent.clientX;
  121868. var y = inEvent.clientY;
  121869. // if the listener is in the shadow root, it is much faster to start there
  121870. var s = this.owner(inEvent.target);
  121871. // if x, y is not in this root, fall back to document search
  121872. if (!s.elementFromPoint(x, y)) {
  121873. s = document;
  121874. }
  121875. return this.searchRoot(s, x, y);
  121876. }
  121877. };
  121878. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  121879. var map = Array.prototype.map.call.bind(Array.prototype.map);
  121880. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  121881. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  121882. var MO = window.MutationObserver || window.WebKitMutationObserver;
  121883. var SELECTOR = '[touch-action]';
  121884. var OBSERVER_INIT = {
  121885. subtree: true,
  121886. childList: true,
  121887. attributes: true,
  121888. attributeOldValue: true,
  121889. attributeFilter: ['touch-action']
  121890. };
  121891. function Installer(add, remove, changed, binder) {
  121892. this.addCallback = add.bind(binder);
  121893. this.removeCallback = remove.bind(binder);
  121894. this.changedCallback = changed.bind(binder);
  121895. if (MO) {
  121896. this.observer = new MO(this.mutationWatcher.bind(this));
  121897. }
  121898. }
  121899. Installer.prototype = {
  121900. watchSubtree: function(target) {
  121901. // Only watch scopes that can target find, as these are top-level.
  121902. // Otherwise we can see duplicate additions and removals that add noise.
  121903. //
  121904. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  121905. // a removal without an insertion when a node is redistributed among
  121906. // shadows. Since it all ends up correct in the document, watching only
  121907. // the document will yield the correct mutations to watch.
  121908. if (this.observer && targeting.canTarget(target)) {
  121909. this.observer.observe(target, OBSERVER_INIT);
  121910. }
  121911. },
  121912. enableOnSubtree: function(target) {
  121913. this.watchSubtree(target);
  121914. if (target === document && document.readyState !== 'complete') {
  121915. this.installOnLoad();
  121916. } else {
  121917. this.installNewSubtree(target);
  121918. }
  121919. },
  121920. installNewSubtree: function(target) {
  121921. forEach(this.findElements(target), this.addElement, this);
  121922. },
  121923. findElements: function(target) {
  121924. if (target.querySelectorAll) {
  121925. return target.querySelectorAll(SELECTOR);
  121926. }
  121927. return [];
  121928. },
  121929. removeElement: function(el) {
  121930. this.removeCallback(el);
  121931. },
  121932. addElement: function(el) {
  121933. this.addCallback(el);
  121934. },
  121935. elementChanged: function(el, oldValue) {
  121936. this.changedCallback(el, oldValue);
  121937. },
  121938. concatLists: function(accum, list) {
  121939. return accum.concat(toArray(list));
  121940. },
  121941. // register all touch-action = none nodes on document load
  121942. installOnLoad: function() {
  121943. document.addEventListener('readystatechange', function() {
  121944. if (document.readyState === 'complete') {
  121945. this.installNewSubtree(document);
  121946. }
  121947. }.bind(this));
  121948. },
  121949. isElement: function(n) {
  121950. return n.nodeType === Node.ELEMENT_NODE;
  121951. },
  121952. flattenMutationTree: function(inNodes) {
  121953. // find children with touch-action
  121954. var tree = map(inNodes, this.findElements, this);
  121955. // make sure the added nodes are accounted for
  121956. tree.push(filter(inNodes, this.isElement));
  121957. // flatten the list
  121958. return tree.reduce(this.concatLists, []);
  121959. },
  121960. mutationWatcher: function(mutations) {
  121961. mutations.forEach(this.mutationHandler, this);
  121962. },
  121963. mutationHandler: function(m) {
  121964. if (m.type === 'childList') {
  121965. var added = this.flattenMutationTree(m.addedNodes);
  121966. added.forEach(this.addElement, this);
  121967. var removed = this.flattenMutationTree(m.removedNodes);
  121968. removed.forEach(this.removeElement, this);
  121969. } else if (m.type === 'attributes') {
  121970. this.elementChanged(m.target, m.oldValue);
  121971. }
  121972. }
  121973. };
  121974. function shadowSelector(v) {
  121975. return 'body /shadow-deep/ ' + selector(v);
  121976. }
  121977. function selector(v) {
  121978. return '[touch-action="' + v + '"]';
  121979. }
  121980. function rule(v) {
  121981. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  121982. }
  121983. var attrib2css = [
  121984. 'none',
  121985. 'auto',
  121986. 'pan-x',
  121987. 'pan-y',
  121988. {
  121989. rule: 'pan-x pan-y',
  121990. selectors: [
  121991. 'pan-x pan-y',
  121992. 'pan-y pan-x'
  121993. ]
  121994. }
  121995. ];
  121996. var styles = '';
  121997. // only install stylesheet if the browser has touch action support
  121998. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  121999. // only add shadow selectors if shadowdom is supported
  122000. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  122001. function applyAttributeStyles() {
  122002. if (hasNativePE) {
  122003. attrib2css.forEach(function(r) {
  122004. if (String(r) === r) {
  122005. styles += selector(r) + rule(r) + '\n';
  122006. if (hasShadowRoot) {
  122007. styles += shadowSelector(r) + rule(r) + '\n';
  122008. }
  122009. } else {
  122010. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  122011. if (hasShadowRoot) {
  122012. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  122013. }
  122014. }
  122015. });
  122016. var el = document.createElement('style');
  122017. el.textContent = styles;
  122018. document.head.appendChild(el);
  122019. }
  122020. }
  122021. var pointermap = dispatcher.pointermap;
  122022. // radius around touchend that swallows mouse events
  122023. var DEDUP_DIST = 25;
  122024. // left, middle, right, back, forward
  122025. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  122026. var HAS_BUTTONS = false;
  122027. try {
  122028. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  122029. } catch (e) {}
  122030. // handler block for native mouse events
  122031. var mouseEvents = {
  122032. POINTER_ID: 1,
  122033. POINTER_TYPE: 'mouse',
  122034. events: [
  122035. 'mousedown',
  122036. 'mousemove',
  122037. 'mouseup',
  122038. 'mouseover',
  122039. 'mouseout'
  122040. ],
  122041. register: function(target) {
  122042. dispatcher.listen(target, this.events);
  122043. },
  122044. unregister: function(target) {
  122045. dispatcher.unlisten(target, this.events);
  122046. },
  122047. lastTouches: [],
  122048. // collide with the global mouse listener
  122049. isEventSimulatedFromTouch: function(inEvent) {
  122050. var lts = this.lastTouches;
  122051. var x = inEvent.clientX;
  122052. var y = inEvent.clientY;
  122053. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  122054. // simulated mouse events will be swallowed near a primary touchend
  122055. var dx = Math.abs(x - t.x);
  122056. var dy = Math.abs(y - t.y);
  122057. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  122058. return true;
  122059. }
  122060. }
  122061. },
  122062. prepareEvent: function(inEvent) {
  122063. var e = dispatcher.cloneEvent(inEvent);
  122064. // forward mouse preventDefault
  122065. var pd = e.preventDefault;
  122066. e.preventDefault = function() {
  122067. inEvent.preventDefault();
  122068. pd();
  122069. };
  122070. e.pointerId = this.POINTER_ID;
  122071. e.isPrimary = true;
  122072. e.pointerType = this.POINTER_TYPE;
  122073. return e;
  122074. },
  122075. prepareButtonsForMove: function(e, inEvent) {
  122076. var p = pointermap.get(this.POINTER_ID);
  122077. // Update buttons state after possible out-of-document mouseup.
  122078. if (inEvent.which === 0 || !p) {
  122079. e.buttons = 0;
  122080. } else {
  122081. e.buttons = p.buttons;
  122082. }
  122083. inEvent.buttons = e.buttons;
  122084. },
  122085. mousedown: function(inEvent) {
  122086. if (!this.isEventSimulatedFromTouch(inEvent)) {
  122087. var p = pointermap.get(this.POINTER_ID);
  122088. var e = this.prepareEvent(inEvent);
  122089. if (!HAS_BUTTONS) {
  122090. e.buttons = BUTTON_TO_BUTTONS[e.button];
  122091. if (p) { e.buttons |= p.buttons; }
  122092. inEvent.buttons = e.buttons;
  122093. }
  122094. pointermap.set(this.POINTER_ID, inEvent);
  122095. if (!p || p.buttons === 0) {
  122096. dispatcher.down(e);
  122097. } else {
  122098. dispatcher.move(e);
  122099. }
  122100. }
  122101. },
  122102. mousemove: function(inEvent) {
  122103. if (!this.isEventSimulatedFromTouch(inEvent)) {
  122104. var e = this.prepareEvent(inEvent);
  122105. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  122106. e.button = -1;
  122107. pointermap.set(this.POINTER_ID, inEvent);
  122108. dispatcher.move(e);
  122109. }
  122110. },
  122111. mouseup: function(inEvent) {
  122112. if (!this.isEventSimulatedFromTouch(inEvent)) {
  122113. var p = pointermap.get(this.POINTER_ID);
  122114. var e = this.prepareEvent(inEvent);
  122115. if (!HAS_BUTTONS) {
  122116. var up = BUTTON_TO_BUTTONS[e.button];
  122117. // Produces wrong state of buttons in Browsers without `buttons` support
  122118. // when a mouse button that was pressed outside the document is released
  122119. // inside and other buttons are still pressed down.
  122120. e.buttons = p ? p.buttons & ~up : 0;
  122121. inEvent.buttons = e.buttons;
  122122. }
  122123. pointermap.set(this.POINTER_ID, inEvent);
  122124. // Support: Firefox <=44 only
  122125. // FF Ubuntu includes the lifted button in the `buttons` property on
  122126. // mouseup.
  122127. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  122128. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  122129. if (e.buttons === 0) {
  122130. dispatcher.up(e);
  122131. } else {
  122132. dispatcher.move(e);
  122133. }
  122134. }
  122135. },
  122136. mouseover: function(inEvent) {
  122137. if (!this.isEventSimulatedFromTouch(inEvent)) {
  122138. var e = this.prepareEvent(inEvent);
  122139. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  122140. e.button = -1;
  122141. pointermap.set(this.POINTER_ID, inEvent);
  122142. dispatcher.enterOver(e);
  122143. }
  122144. },
  122145. mouseout: function(inEvent) {
  122146. if (!this.isEventSimulatedFromTouch(inEvent)) {
  122147. var e = this.prepareEvent(inEvent);
  122148. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  122149. e.button = -1;
  122150. dispatcher.leaveOut(e);
  122151. }
  122152. },
  122153. cancel: function(inEvent) {
  122154. var e = this.prepareEvent(inEvent);
  122155. dispatcher.cancel(e);
  122156. this.deactivateMouse();
  122157. },
  122158. deactivateMouse: function() {
  122159. pointermap.delete(this.POINTER_ID);
  122160. }
  122161. };
  122162. var captureInfo = dispatcher.captureInfo;
  122163. var findTarget = targeting.findTarget.bind(targeting);
  122164. var allShadows = targeting.allShadows.bind(targeting);
  122165. var pointermap$1 = dispatcher.pointermap;
  122166. // This should be long enough to ignore compat mouse events made by touch
  122167. var DEDUP_TIMEOUT = 2500;
  122168. var CLICK_COUNT_TIMEOUT = 200;
  122169. var ATTRIB = 'touch-action';
  122170. var INSTALLER;
  122171. // handler block for native touch events
  122172. var touchEvents = {
  122173. events: [
  122174. 'touchstart',
  122175. 'touchmove',
  122176. 'touchend',
  122177. 'touchcancel'
  122178. ],
  122179. register: function(target) {
  122180. INSTALLER.enableOnSubtree(target);
  122181. },
  122182. unregister: function() {
  122183. // TODO(dfreedman): is it worth it to disconnect the MO?
  122184. },
  122185. elementAdded: function(el) {
  122186. var a = el.getAttribute(ATTRIB);
  122187. var st = this.touchActionToScrollType(a);
  122188. if (st) {
  122189. el._scrollType = st;
  122190. dispatcher.listen(el, this.events);
  122191. // set touch-action on shadows as well
  122192. allShadows(el).forEach(function(s) {
  122193. s._scrollType = st;
  122194. dispatcher.listen(s, this.events);
  122195. }, this);
  122196. }
  122197. },
  122198. elementRemoved: function(el) {
  122199. el._scrollType = undefined;
  122200. dispatcher.unlisten(el, this.events);
  122201. // remove touch-action from shadow
  122202. allShadows(el).forEach(function(s) {
  122203. s._scrollType = undefined;
  122204. dispatcher.unlisten(s, this.events);
  122205. }, this);
  122206. },
  122207. elementChanged: function(el, oldValue) {
  122208. var a = el.getAttribute(ATTRIB);
  122209. var st = this.touchActionToScrollType(a);
  122210. var oldSt = this.touchActionToScrollType(oldValue);
  122211. // simply update scrollType if listeners are already established
  122212. if (st && oldSt) {
  122213. el._scrollType = st;
  122214. allShadows(el).forEach(function(s) {
  122215. s._scrollType = st;
  122216. }, this);
  122217. } else if (oldSt) {
  122218. this.elementRemoved(el);
  122219. } else if (st) {
  122220. this.elementAdded(el);
  122221. }
  122222. },
  122223. scrollTypes: {
  122224. EMITTER: 'none',
  122225. XSCROLLER: 'pan-x',
  122226. YSCROLLER: 'pan-y',
  122227. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  122228. },
  122229. touchActionToScrollType: function(touchAction) {
  122230. var t = touchAction;
  122231. var st = this.scrollTypes;
  122232. if (t === 'none') {
  122233. return 'none';
  122234. } else if (t === st.XSCROLLER) {
  122235. return 'X';
  122236. } else if (t === st.YSCROLLER) {
  122237. return 'Y';
  122238. } else if (st.SCROLLER.exec(t)) {
  122239. return 'XY';
  122240. }
  122241. },
  122242. POINTER_TYPE: 'touch',
  122243. firstTouch: null,
  122244. isPrimaryTouch: function(inTouch) {
  122245. return this.firstTouch === inTouch.identifier;
  122246. },
  122247. setPrimaryTouch: function(inTouch) {
  122248. // set primary touch if there no pointers, or the only pointer is the mouse
  122249. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  122250. this.firstTouch = inTouch.identifier;
  122251. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  122252. this.scrolling = false;
  122253. this.cancelResetClickCount();
  122254. }
  122255. },
  122256. removePrimaryPointer: function(inPointer) {
  122257. if (inPointer.isPrimary) {
  122258. this.firstTouch = null;
  122259. this.firstXY = null;
  122260. this.resetClickCount();
  122261. }
  122262. },
  122263. clickCount: 0,
  122264. resetId: null,
  122265. resetClickCount: function() {
  122266. var fn = function() {
  122267. this.clickCount = 0;
  122268. this.resetId = null;
  122269. }.bind(this);
  122270. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  122271. },
  122272. cancelResetClickCount: function() {
  122273. if (this.resetId) {
  122274. clearTimeout(this.resetId);
  122275. }
  122276. },
  122277. typeToButtons: function(type) {
  122278. var ret = 0;
  122279. if (type === 'touchstart' || type === 'touchmove') {
  122280. ret = 1;
  122281. }
  122282. return ret;
  122283. },
  122284. touchToPointer: function(inTouch) {
  122285. var cte = this.currentTouchEvent;
  122286. var e = dispatcher.cloneEvent(inTouch);
  122287. // We reserve pointerId 1 for Mouse.
  122288. // Touch identifiers can start at 0.
  122289. // Add 2 to the touch identifier for compatibility.
  122290. var id = e.pointerId = inTouch.identifier + 2;
  122291. e.target = captureInfo[id] || findTarget(e);
  122292. e.bubbles = true;
  122293. e.cancelable = true;
  122294. e.detail = this.clickCount;
  122295. e.button = 0;
  122296. e.buttons = this.typeToButtons(cte.type);
  122297. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  122298. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  122299. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  122300. e.isPrimary = this.isPrimaryTouch(inTouch);
  122301. e.pointerType = this.POINTER_TYPE;
  122302. // forward modifier keys
  122303. e.altKey = cte.altKey;
  122304. e.ctrlKey = cte.ctrlKey;
  122305. e.metaKey = cte.metaKey;
  122306. e.shiftKey = cte.shiftKey;
  122307. // forward touch preventDefaults
  122308. var self = this;
  122309. e.preventDefault = function() {
  122310. self.scrolling = false;
  122311. self.firstXY = null;
  122312. cte.preventDefault();
  122313. };
  122314. return e;
  122315. },
  122316. processTouches: function(inEvent, inFunction) {
  122317. var tl = inEvent.changedTouches;
  122318. this.currentTouchEvent = inEvent;
  122319. for (var i = 0, t; i < tl.length; i++) {
  122320. t = tl[i];
  122321. inFunction.call(this, this.touchToPointer(t));
  122322. }
  122323. },
  122324. // For single axis scrollers, determines whether the element should emit
  122325. // pointer events or behave as a scroller
  122326. shouldScroll: function(inEvent) {
  122327. if (this.firstXY) {
  122328. var ret;
  122329. var scrollAxis = inEvent.currentTarget._scrollType;
  122330. if (scrollAxis === 'none') {
  122331. // this element is a touch-action: none, should never scroll
  122332. ret = false;
  122333. } else if (scrollAxis === 'XY') {
  122334. // this element should always scroll
  122335. ret = true;
  122336. } else {
  122337. var t = inEvent.changedTouches[0];
  122338. // check the intended scroll axis, and other axis
  122339. var a = scrollAxis;
  122340. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  122341. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  122342. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  122343. // if delta in the scroll axis > delta other axis, scroll instead of
  122344. // making events
  122345. ret = da >= doa;
  122346. }
  122347. this.firstXY = null;
  122348. return ret;
  122349. }
  122350. },
  122351. findTouch: function(inTL, inId) {
  122352. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  122353. if (t.identifier === inId) {
  122354. return true;
  122355. }
  122356. }
  122357. },
  122358. // In some instances, a touchstart can happen without a touchend. This
  122359. // leaves the pointermap in a broken state.
  122360. // Therefore, on every touchstart, we remove the touches that did not fire a
  122361. // touchend event.
  122362. // To keep state globally consistent, we fire a
  122363. // pointercancel for this "abandoned" touch
  122364. vacuumTouches: function(inEvent) {
  122365. var tl = inEvent.touches;
  122366. // pointermap.size should be < tl.length here, as the touchstart has not
  122367. // been processed yet.
  122368. if (pointermap$1.size >= tl.length) {
  122369. var d = [];
  122370. pointermap$1.forEach(function(value, key) {
  122371. // Never remove pointerId == 1, which is mouse.
  122372. // Touch identifiers are 2 smaller than their pointerId, which is the
  122373. // index in pointermap.
  122374. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  122375. var p = value.out;
  122376. d.push(p);
  122377. }
  122378. }, this);
  122379. d.forEach(this.cancelOut, this);
  122380. }
  122381. },
  122382. touchstart: function(inEvent) {
  122383. this.vacuumTouches(inEvent);
  122384. this.setPrimaryTouch(inEvent.changedTouches[0]);
  122385. this.dedupSynthMouse(inEvent);
  122386. if (!this.scrolling) {
  122387. this.clickCount++;
  122388. this.processTouches(inEvent, this.overDown);
  122389. }
  122390. },
  122391. overDown: function(inPointer) {
  122392. pointermap$1.set(inPointer.pointerId, {
  122393. target: inPointer.target,
  122394. out: inPointer,
  122395. outTarget: inPointer.target
  122396. });
  122397. dispatcher.enterOver(inPointer);
  122398. dispatcher.down(inPointer);
  122399. },
  122400. touchmove: function(inEvent) {
  122401. if (!this.scrolling) {
  122402. if (this.shouldScroll(inEvent)) {
  122403. this.scrolling = true;
  122404. this.touchcancel(inEvent);
  122405. } else {
  122406. inEvent.preventDefault();
  122407. this.processTouches(inEvent, this.moveOverOut);
  122408. }
  122409. }
  122410. },
  122411. moveOverOut: function(inPointer) {
  122412. var event = inPointer;
  122413. var pointer = pointermap$1.get(event.pointerId);
  122414. // a finger drifted off the screen, ignore it
  122415. if (!pointer) {
  122416. return;
  122417. }
  122418. var outEvent = pointer.out;
  122419. var outTarget = pointer.outTarget;
  122420. dispatcher.move(event);
  122421. if (outEvent && outTarget !== event.target) {
  122422. outEvent.relatedTarget = event.target;
  122423. event.relatedTarget = outTarget;
  122424. // recover from retargeting by shadow
  122425. outEvent.target = outTarget;
  122426. if (event.target) {
  122427. dispatcher.leaveOut(outEvent);
  122428. dispatcher.enterOver(event);
  122429. } else {
  122430. // clean up case when finger leaves the screen
  122431. event.target = outTarget;
  122432. event.relatedTarget = null;
  122433. this.cancelOut(event);
  122434. }
  122435. }
  122436. pointer.out = event;
  122437. pointer.outTarget = event.target;
  122438. },
  122439. touchend: function(inEvent) {
  122440. this.dedupSynthMouse(inEvent);
  122441. this.processTouches(inEvent, this.upOut);
  122442. },
  122443. upOut: function(inPointer) {
  122444. if (!this.scrolling) {
  122445. dispatcher.up(inPointer);
  122446. dispatcher.leaveOut(inPointer);
  122447. }
  122448. this.cleanUpPointer(inPointer);
  122449. },
  122450. touchcancel: function(inEvent) {
  122451. this.processTouches(inEvent, this.cancelOut);
  122452. },
  122453. cancelOut: function(inPointer) {
  122454. dispatcher.cancel(inPointer);
  122455. dispatcher.leaveOut(inPointer);
  122456. this.cleanUpPointer(inPointer);
  122457. },
  122458. cleanUpPointer: function(inPointer) {
  122459. pointermap$1.delete(inPointer.pointerId);
  122460. this.removePrimaryPointer(inPointer);
  122461. },
  122462. // prevent synth mouse events from creating pointer events
  122463. dedupSynthMouse: function(inEvent) {
  122464. var lts = mouseEvents.lastTouches;
  122465. var t = inEvent.changedTouches[0];
  122466. // only the primary finger will synth mouse events
  122467. if (this.isPrimaryTouch(t)) {
  122468. // remember x/y of last touch
  122469. var lt = { x: t.clientX, y: t.clientY };
  122470. lts.push(lt);
  122471. var fn = (function(lts, lt) {
  122472. var i = lts.indexOf(lt);
  122473. if (i > -1) {
  122474. lts.splice(i, 1);
  122475. }
  122476. }).bind(null, lts, lt);
  122477. setTimeout(fn, DEDUP_TIMEOUT);
  122478. }
  122479. }
  122480. };
  122481. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  122482. touchEvents.elementChanged, touchEvents);
  122483. var pointermap$2 = dispatcher.pointermap;
  122484. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  122485. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  122486. var msEvents = {
  122487. events: [
  122488. 'MSPointerDown',
  122489. 'MSPointerMove',
  122490. 'MSPointerUp',
  122491. 'MSPointerOut',
  122492. 'MSPointerOver',
  122493. 'MSPointerCancel',
  122494. 'MSGotPointerCapture',
  122495. 'MSLostPointerCapture'
  122496. ],
  122497. register: function(target) {
  122498. dispatcher.listen(target, this.events);
  122499. },
  122500. unregister: function(target) {
  122501. dispatcher.unlisten(target, this.events);
  122502. },
  122503. POINTER_TYPES: [
  122504. '',
  122505. 'unavailable',
  122506. 'touch',
  122507. 'pen',
  122508. 'mouse'
  122509. ],
  122510. prepareEvent: function(inEvent) {
  122511. var e = inEvent;
  122512. if (HAS_BITMAP_TYPE) {
  122513. e = dispatcher.cloneEvent(inEvent);
  122514. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  122515. }
  122516. return e;
  122517. },
  122518. cleanup: function(id) {
  122519. pointermap$2.delete(id);
  122520. },
  122521. MSPointerDown: function(inEvent) {
  122522. pointermap$2.set(inEvent.pointerId, inEvent);
  122523. var e = this.prepareEvent(inEvent);
  122524. dispatcher.down(e);
  122525. },
  122526. MSPointerMove: function(inEvent) {
  122527. var e = this.prepareEvent(inEvent);
  122528. dispatcher.move(e);
  122529. },
  122530. MSPointerUp: function(inEvent) {
  122531. var e = this.prepareEvent(inEvent);
  122532. dispatcher.up(e);
  122533. this.cleanup(inEvent.pointerId);
  122534. },
  122535. MSPointerOut: function(inEvent) {
  122536. var e = this.prepareEvent(inEvent);
  122537. dispatcher.leaveOut(e);
  122538. },
  122539. MSPointerOver: function(inEvent) {
  122540. var e = this.prepareEvent(inEvent);
  122541. dispatcher.enterOver(e);
  122542. },
  122543. MSPointerCancel: function(inEvent) {
  122544. var e = this.prepareEvent(inEvent);
  122545. dispatcher.cancel(e);
  122546. this.cleanup(inEvent.pointerId);
  122547. },
  122548. MSLostPointerCapture: function(inEvent) {
  122549. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  122550. dispatcher.dispatchEvent(e);
  122551. },
  122552. MSGotPointerCapture: function(inEvent) {
  122553. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  122554. dispatcher.dispatchEvent(e);
  122555. }
  122556. };
  122557. function applyPolyfill() {
  122558. // only activate if this platform does not have pointer events
  122559. if (!window.PointerEvent) {
  122560. window.PointerEvent = PointerEvent;
  122561. if (window.navigator.msPointerEnabled) {
  122562. var tp = window.navigator.msMaxTouchPoints;
  122563. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  122564. value: tp,
  122565. enumerable: true
  122566. });
  122567. dispatcher.registerSource('ms', msEvents);
  122568. } else {
  122569. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  122570. value: 0,
  122571. enumerable: true
  122572. });
  122573. dispatcher.registerSource('mouse', mouseEvents);
  122574. if (window.ontouchstart !== undefined) {
  122575. dispatcher.registerSource('touch', touchEvents);
  122576. }
  122577. }
  122578. dispatcher.register(document);
  122579. }
  122580. }
  122581. var n = window.navigator;
  122582. var s;
  122583. var r;
  122584. var h;
  122585. function assertActive(id) {
  122586. if (!dispatcher.pointermap.has(id)) {
  122587. var error = new Error('InvalidPointerId');
  122588. error.name = 'InvalidPointerId';
  122589. throw error;
  122590. }
  122591. }
  122592. function assertConnected(elem) {
  122593. var parent = elem.parentNode;
  122594. while (parent && parent !== elem.ownerDocument) {
  122595. parent = parent.parentNode;
  122596. }
  122597. if (!parent) {
  122598. var error = new Error('InvalidStateError');
  122599. error.name = 'InvalidStateError';
  122600. throw error;
  122601. }
  122602. }
  122603. function inActiveButtonState(id) {
  122604. var p = dispatcher.pointermap.get(id);
  122605. return p.buttons !== 0;
  122606. }
  122607. if (n.msPointerEnabled) {
  122608. s = function(pointerId) {
  122609. assertActive(pointerId);
  122610. assertConnected(this);
  122611. if (inActiveButtonState(pointerId)) {
  122612. dispatcher.setCapture(pointerId, this, true);
  122613. this.msSetPointerCapture(pointerId);
  122614. }
  122615. };
  122616. r = function(pointerId) {
  122617. assertActive(pointerId);
  122618. dispatcher.releaseCapture(pointerId, true);
  122619. this.msReleasePointerCapture(pointerId);
  122620. };
  122621. } else {
  122622. s = function setPointerCapture(pointerId) {
  122623. assertActive(pointerId);
  122624. assertConnected(this);
  122625. if (inActiveButtonState(pointerId)) {
  122626. dispatcher.setCapture(pointerId, this);
  122627. }
  122628. };
  122629. r = function releasePointerCapture(pointerId) {
  122630. assertActive(pointerId);
  122631. dispatcher.releaseCapture(pointerId);
  122632. };
  122633. }
  122634. h = function hasPointerCapture(pointerId) {
  122635. return !!dispatcher.captureInfo[pointerId];
  122636. };
  122637. function applyPolyfill$1() {
  122638. if (window.Element && !Element.prototype.setPointerCapture) {
  122639. Object.defineProperties(Element.prototype, {
  122640. 'setPointerCapture': {
  122641. value: s
  122642. },
  122643. 'releasePointerCapture': {
  122644. value: r
  122645. },
  122646. 'hasPointerCapture': {
  122647. value: h
  122648. }
  122649. });
  122650. }
  122651. }
  122652. applyAttributeStyles();
  122653. applyPolyfill();
  122654. applyPolyfill$1();
  122655. var pointerevents = {
  122656. dispatcher: dispatcher,
  122657. Installer: Installer,
  122658. PointerEvent: PointerEvent,
  122659. PointerMap: PointerMap,
  122660. targetFinding: targeting
  122661. };
  122662. return pointerevents;
  122663. }));
  122664. /***/ }),
  122665. /* 67 */
  122666. /***/ (function(module, exports, __webpack_require__) {
  122667. "use strict";
  122668. Object.defineProperty(exports, "__esModule", { value: true });
  122669. var defaultViewer_1 = __webpack_require__(8);
  122670. var mappers_1 = __webpack_require__(3);
  122671. var globals_1 = __webpack_require__(4);
  122672. /**
  122673. * Will attach an init function the the DOMContentLoaded event.
  122674. * The init function will be removed automatically after the event was triggered.
  122675. */
  122676. function initListeners() {
  122677. document.addEventListener("DOMContentLoaded", init);
  122678. function init(event) {
  122679. document.removeEventListener("DOMContentLoaded", init);
  122680. if (globals_1.viewerGlobals.disableInit)
  122681. return;
  122682. InitTags();
  122683. }
  122684. }
  122685. exports.initListeners = initListeners;
  122686. /**
  122687. * Select all HTML tags on the page that match the selector and initialize a viewer
  122688. *
  122689. * @param selector the selector to initialize the viewer on (default is 'babylon')
  122690. */
  122691. function InitTags(selector) {
  122692. if (selector === void 0) { selector = 'babylon'; }
  122693. var elements = document.querySelectorAll(selector);
  122694. for (var i = 0; i < elements.length; ++i) {
  122695. var element = elements.item(i);
  122696. // get the html configuration
  122697. var configMapper = mappers_1.mapperManager.getMapper('dom');
  122698. var config = configMapper.map(element);
  122699. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  122700. }
  122701. }
  122702. exports.InitTags = InitTags;
  122703. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQztBQUNMLENBQUM7QUFQRCxzQ0FPQztBQUVEOzs7O0dBSUc7QUFDSCxrQkFBeUIsUUFBNEI7SUFBNUIseUJBQUEsRUFBQSxvQkFBNEI7SUFDakQsSUFBSSxRQUFRLEdBQUcsUUFBUSxDQUFDLGdCQUFnQixDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQ25ELEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBR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